Performance Zone is brought to you in partnership with:

Yaron is a Microsoft MVP in the Connected System Developer realm. Yaron authors the successful Web Services 2.0 blog, in which he helps the community with some of his favorite topics: Web services, security and interoperability. Yaron is also an architect in HP. Yaron is a DZone MVB and is not an employee of DZone and has posted 27 posts at DZone. You can read more from them at their website. View Full User Profile

Check Out this Digital Signature Library for Node.js

07.11.2012
| 3580 views |
  • submit to reddit

Get xml-crypto on github

Node.js does not always have the right libraries for Xml operations. When such libraries exist they are not always cross platform (read: work on windows). I've just published xml-crypto, the first xml digital signature library for node. As a bonus this library is written in pure javascript so it is cross platform.

What is Xml Digital signature?
There's a tl;dr version here. The essence is that dig-sig allows to protect content from unauthorized modification by telling us who created that content and if anyone had altered it since. Xml dig-sig is a special flavour which has some interesting implementation aspects.

A typical xml signature looks like this:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
    <Reference URI="#_0">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
      <DigestValue>b5GCZ2xpP5T7tbLWBTkOl4CYupQ=</DigestValue>
    </Reference>
  </SignedInfo>
 <SignatureValue>PI2xGt3XrVcxYZ3...</SignatureValue>
  <KeyInfo>
  </KeyInfo>
</Signature>


Installing Xml-Crypto

Install with npm:

npm install xml-crypto

A pre requisite it to have openssl installed and its /bin to be on the system path. I used version 1.0.1c but it should work on older versions too.

Signing an xml document

Use this code:

var SignedXml = require('xml-crypto').SignedXml
      , FileKeyInfo = require('xml-crypto').FileKeyInfo
      , fs = require('fs')

var xml = "<library>" +
             "<book>" +
               "<name>Harry Potter</name>" +
             "</book>"
           "</library>"

var sig = new SignedXml()
sig.addReference("//*[local-name(.)='book']")
sig.signingKey = fs.readFileSync("client.pem")
sig.computeSignature(xml)
fs.writeFileSync("signed.xml", sig.getSignedXml())

The result wil be:

<library>
  <book Id="_0">
    <name>Harry Potter</name>
  </book>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <Reference URI="#_0">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <DigestValue>cdiS43aFDQMnb3X8yaIUej3+z9Q=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>vhWzpQyIYuncHUZV9W...[long base64 removed]...</SignatureValue>
  </Signature>
</library>


Note:

sig.getSignedXml() returns the original xml document with the signature pushed as the last child of the root node (as above). This assumes you are not signing the root node but only sub node(s) otherwise this is not valid. If you do sign the root node call sig.getSignatureXml() to get just the signature part and sig.getOriginalXmlWithIds() to get the original xml with Id attributes added on relevant elements (required for validation).

Verifying a signed document

You can use any dom parser you want in your code (or none, depending on your usage). This sample uses xmldom so you should install it first:

npm install xmldom

Then run:

var select = require('xml-crypto').xpath.SelectNodes
  , dom = require('xmldom').DOMParser
  , SignedXml = require('xml-crypto').SignedXml
  , FileKeyInfo = require('xml-crypto').FileKeyInfo
  , fs = require('fs')

var xml = fs.readFileSync("signed.xml").toString()
var doc = new dom().parseFromString(xml)
var signature = select(doc, "/*/*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0]
var sig = new SignedXml()
sig.keyInfoProvider = new FileKeyInfo("client_public.pem")
sig.loadSignature(signature.toString())
var res = sig.checkSignature(xml)
if (!res) console.log(sig.validationErrors)

Note:

The xml-crypto api requires you to supply it separately the xml signature ("<Signature>...</Signature>", in loadSignature) and the signed xml (in checkSignature). The signed xml may or may not contain the signature in it, but you are still required to supply the signature separately.

Supported Algorithms

The first release always uses the following algorithems:

  • Exclusive Canonicalization http://www.w3.org/2001/10/xml-exc-c14n#
  • SHA1 digests http://www.w3.org/2000/09/xmldsig#sha1
  • RSA-SHA1 signature algorithm http://www.w3.org/2000/09/xmldsig#rsa-sha1

    you are able to extend xml-crypto with further algorithms. I will author a post about it soon.

    Key formats

    You need to use .pem formatted certificates for both signing and validation. If you have pfx x.509 certificates there's an easy way to convert them to pem. I will author a post about this soon.

    The code

    Get xml-crypto on github
  • Published at DZone with permission of Yaron Naveh, author and DZone MVB. (source)

    (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)