Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
xml-crypto
Advanced tools
The xml-crypto npm package is a library that provides tools for signing and verifying XML digital signatures, which are used to ensure the integrity and authenticity of XML documents. It is based on the standards of XML Signature and XML Encryption.
Signing XML documents
This feature allows you to sign XML documents. You can specify references to the parts of the XML that you want to sign, provide your private key, and then compute and obtain the signed XML.
const fs = require('fs');
const { SignedXml } = require('xml-crypto');
let sig = new SignedXml();
sig.addReference("//*[local-name(.)='x']");
sig.signingKey = fs.readFileSync('private.pem');
sig.computeSignature('<x xmlns="urn:xmpp:delay">example</x>');
fs.writeFileSync('signed.xml', sig.getSignedXml());
Verifying XML signatures
This feature allows you to verify the signature of an XML document. You can load the signed XML, provide the corresponding public key, and check if the signature is valid.
const fs = require('fs');
const { SignedXml } = require('xml-crypto');
let xml = fs.readFileSync('signed.xml').toString();
let sig = new SignedXml();
sig.keyInfoProvider = {
getKeyInfo: function(key) {
return '<X509Data></X509Data>';
},
getKey: function(keyInfo) {
return fs.readFileSync('public.pem');
}
};
sig.loadSignature(xml);
let result = sig.checkSignature(xml);
console.log('Signature is', result ? 'valid' : 'invalid');
Working with KeyInfo
This feature allows you to work with KeyInfo, which is an XML structure that contains information about the key used for signing. You can create a KeyInfoProvider with your key and obtain the KeyInfo XML.
const { KeyInfoProvider } = require('xml-crypto');
let keyInfoProvider = new KeyInfoProvider('key.pem');
let keyInfo = keyInfoProvider.getKeyInfo();
xml-encryption is a package specifically focused on XML Encryption. While xml-crypto also supports encryption, xml-encryption is dedicated to this aspect and provides a more specialized API for encrypting and decrypting XML data.
xadesjs is a package for building XMLDSIG and XAdES (XML Advanced Electronic Signatures) signatures. It is based on the Web Cryptography API and provides a more modern approach compared to xml-crypto, which might be beneficial for certain use cases.
An xml digital signature library for node. Xml encryption is coming soon. Written in pure javascript!
For more information visit my blog or my twitter.
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.
HMAC-SHA1 is also available but it is disabled by default
to enable HMAC-SHA1, do:
require( 'xml-crypto' ).SignedXml.enableHMAC();
This will enable HMAC and disable digital signature algorithms. Due to key confusion issues, it is risky to have both HMAC-based and public key digital signature algorithms enabled at same time.
by default the following algorithms are used:
Canonicalization/Transformation Algorithm: Exclusive Canonicalization http://www.w3.org/2001/10/xml-exc-c14n#
Hashing Algorithm: SHA1 digest http://www.w3.org/2000/09/xmldsig#sha1
Signature Algorithm: RSA-SHA1 http://www.w3.org/2000/09/xmldsig#rsa-sha1
You are able to extend xml-crypto with custom algorithms.
When signing a xml document you can specify the following properties on a SignedXml
instance to customize the signature process:
sign.signingKey
- [required] a Buffer
or pem encoded String
containing your private keysign.keyInfoProvider
- [optional] a key info provider instance, see customizing algorithms for an implementation examplesign.signatureAlgorithm
- [optional] one of the supported signature algorithms. Ex: sign.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
sign.canonicalizationAlgorithm
- [optional] one of the supported canonicalization algorithms. Ex: sign.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
Use this code:
var SignedXml = require('xml-crypto').SignedXml
, 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 will 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:
To generate a <X509Data></X509Data>
element in the signature you must provide a key info implementation, see customizing algorithms for an example.
When verifying a xml document you must specify the following properties on a ``SignedXml` instance:
sign.keyInfoProvider
- [required] a key info provider instance containing your certificate, see customizing algorithms for an implementation exampleYou 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
Example:
var select = require('xml-crypto').xpath
, 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)
var res = sig.checkSignature(xml)
if (!res) console.log(sig.validationErrors)
if the verification process fails sig.validationErrors
will have the errors.
In order to protect from some attacks we must check the content we want to use is the one that has been signed:
var elem = select(doc, "/xpath_to_interesting_element");
var uri = sig.references[0].uri; // might not be 0 - depending on the document you verify
var id = (uri[0] === '#') ? uri.substring(1) : uri;
if (elem.getAttribute('ID') != id && elem.getAttribute('Id') != id && elem.getAttribute('id') != id)
throw new Error('the interesting element was not the one verified by the signature')
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.
If you fail to verify signed XML, then one possible cause is that there are some hidden implicit transforms(#).
(#) Normalizing XML document to be verified. i.e. remove extra space within a tag, sorting attributes, importing namespace declared in ancestor nodes, etc.
The reason for these implicit transform might come from complex xml signature specification, which makes XML developers confused and then leads to incorrect implementation for signing XML document.
If you keep failing verification, it is worth trying to guess such a hidden transform and specify it to the option as below:
var option = {implicitTransforms: ["http://www.w3.org/TR/2001/REC-xml-c14n-20010315"]}
var sig = new SignedXml(null, option)
sig.keyInfoProvider = new FileKeyInfo("client_public.pem")
sig.loadSignature(signature)
var res = sig.checkSignature(xml)
You might find it difficult to guess such transforms, but there are typical transforms you can try.
See xpath.js for usage. Note that this is actually using another library as the underlying implementation.
The SignedXml
constructor provides an abstraction for sign and verify xml documents. The object is constructed using new SignedXml([idMode])
where:
idMode
- if the value of "wssecurity"
is passed it will create/validate id's with the ws-security namespace.API
A SignedXml
object provides the following methods:
To sign xml documents:
addReference(xpath, [transforms], [digestAlgorithm])
- adds a reference to a xml element where:
xpath
- a string containing a XPath expression referencing a xml elementtransforms
- an array of transform algorithms, the referenced element will be transformed for each value in the arraydigestAlgorithm
- one of the supported hashing algorithmscomputeSignature(xml, [options])
- compute the signature of the given xml where:
xml
- a string containing a xml documentoptions
- an object with the following properties:
prefix
- adds this value as a prefix for the generated signature tagsattrs
- a hash of attributes and values attrName: value
to add to the signature root nodelocation
- customize the location of the signature, pass an object with a reference
key which should contain a XPath expression to a reference node, an action
key which should contain one of the following values: append
, prepend
, before
, after
existingPrefixes
- A hash of prefixes and namespaces prefix: namespace
that shouldn't be in the signature because they already exist in the xmlgetSignedXml()
- returns the original xml document with the signature in it, must be called only after computeSignature
getSignatureXml()
- returns just the signature part, must be called only after computeSignature
getOriginalXmlWithIds()
- returns the original xml with Id attributes added on relevant elements (required for validation), must be called only after computeSignature
To verify xml documents:
loadSignature(signatureXml)
- loads the signature where:
signatureXml
- a string or node object (like an xml-dom node) containing the xml representation of the signaturecheckSignature(xml)
- validates the given xml document and returns true if the validation was successful, sig.validationErrors
will have the validation errors if any, where:
xml
- a string containing a xml documentA basic key info provider implementation using fs.readFileSync(file)
, is constructed using new FileKeyInfo([file])
where:
file
- a path to a pem encoded certificateSee verifying xml documents for an example usage
The following sample shows how to sign a message using custom algorithms.
First import some modules:
var SignedXml = require('xml-crypto').SignedXml
, fs = require('fs')
Now define the extension point you want to implement. You can choose one or more.
A key info provider is used to extract and construct the key and the KeyInfo xml section. Implement it if you want to create a signature with a KeyInfo section, or you want to read your key in a different way then the default file read option.
/**/
function MyKeyInfo() {
this.getKeyInfo = function(key, prefix) {
prefix = prefix || ''
prefix = prefix ? prefix + ':' : prefix
return "<" + prefix + "X509Data></" + prefix + "X509Data>"
}
this.getKey = function(keyInfo) {
//you can use the keyInfo parameter to extract the key in any way you want
return fs.readFileSync("key.pem")
}
}
A custom hash algorithm is used to calculate digests. Implement it if you want a hash other than the default SHA1.
function MyDigest() {
this.getHash = function(xml) {
return "the base64 hash representation of the given xml string"
}
this.getAlgorithmName = function() {
return "http://myDigestAlgorithm"
}
}
A custom signing algorithm. The default is RSA-SHA1
function MySignatureAlgorithm() {
/*sign the given SignedInfo using the key. return base64 signature value*/
this.getSignature = function(signedInfo, signingKey) {
return "signature of signedInfo as base64..."
}
this.getAlgorithmName = function() {
return "http://mySigningAlgorithm"
}
}
Custom transformation algorithm. The default is exclusive canonicalization.
function MyTransformation() {
/*given a node (from the xmldom module) return its canonical representation (as string)*/
this.process = function(node) {
//you should apply your transformation before returning
return node.toString()
}
this.getAlgorithmName = function() {
return "http://myTransformation"
}
}
Custom canonicalization is actually the same as custom transformation. It is applied on the SignedInfo rather than on references.
function MyCanonicalization() {
/*given a node (from the xmldom module) return its canonical representation (as string)*/
this.process = function(node) {
//you should apply your transformation before returning
return "< x/>"
}
this.getAlgorithmName = function() {
return "http://myCanonicalization"
}
}
Now you need to register the new algorithms:
/*register all the custom algorithms*/
SignedXml.CanonicalizationAlgorithms["http://MyTransformation"] = MyTransformation
SignedXml.CanonicalizationAlgorithms["http://MyCanonicalization"] = MyCanonicalization
SignedXml.HashAlgorithms["http://myDigestAlgorithm"] = MyDigest
SignedXml.SignatureAlgorithms["http://mySigningAlgorithm"] = MySignatureAlgorithm
Now do the signing. Note how we configure the signature to use the above algorithms:
function signXml(xml, xpath, key, dest)
{
var sig = new SignedXml()
/*configure the signature object to use the custom algorithms*/
sig.signatureAlgorithm = "http://mySignatureAlgorithm"
sig.keyInfoProvider = new MyKeyInfo()
sig.canonicalizationAlgorithm = "http://MyCanonicalization"
sig.addReference("//*[local-name(.)='x']", ["http://MyTransformation"], "http://myDigestAlgorithm")
sig.signingKey = fs.readFileSync(key)
sig.addReference(xpath)
sig.computeSignature(xml)
fs.writeFileSync(dest, sig.getSignedXml())
}
var xml = "<library>" +
"<book>" +
"<name>Harry Potter</name>" +
"</book>"
"</library>"
signXml(xml,
"//*[local-name(.)='book']",
"client.pem",
"result.xml")
You can always look at the actual code as a sample (or drop me a mail).
If the private key is not stored locally and you wish to use a signing server or Hardware Security Module (HSM) to sign documents you can create a custom signing algorithm that uses an asynchronous callback.
function AsyncSignatureAlgorithm() {
this.getSignature = function (signedInfo, signingKey, callback) {
var signer = crypto.createSign("RSA-SHA1")
signer.update(signedInfo)
var res = signer.sign(signingKey, 'base64')
//Do some asynchronous things here
callback(null, res)
}
this.getAlgorithmName = function () {
return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
}
}
SignedXml.SignatureAlgorithms["http://asyncSignatureAlgorithm"] = AsyncSignatureAlgorithm
var sig = new SignedXml()
sig.signatureAlgorithm = "http://asyncSignatureAlgorithm"
sig.computeSignature(xml, opts, function(err){
var signedResponse = sig.getSignedXml()
})
The function sig.checkSignature
may also use a callback if asynchronous verification is needed.
Xml-Crypto internally relies on node's crypto module. This means pem encoded certificates are supported. So to sign an xml use key.pem that looks like this (only the begining of the key content is shown):
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0...
-----END PRIVATE KEY-----
And for verification use key_public.pem:
-----BEGIN CERTIFICATE-----
MIIBxDCCAW6gAwIBAgIQxUSX...
-----END CERTIFICATE-----
Converting .pfx certificates to pem
If you have .pfx certificates you can convert them to .pem using openssl:
openssl pkcs12 -in c:\certs\yourcert.pfx -out c:\certs\cag.pem
Then you could use the result as is for the purpose of signing. For the purpose of validation open the resulting .pem with a text editor and copy from -----BEGIN CERTIFICATE----- to -----END CERTIFICATE----- (including) to a new text file and save it as .pem.
###how to add a prefix for the signature###
Use the prefix
option when calling computeSignature
to add a prefix to the signature.
var SignedXml = require('xml-crypto').SignedXml
, 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,{
prefix: 'ds'
});
###how to specify the location of the signature###
Use the location
option when calling computeSignature
to move the signature around.
Set action
to one of the following:
referenceNode
property)referenceNode
property)var SignedXml = require('xml-crypto').SignedXml
, 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,{
location: { reference: "//*[local-name(.)='book']", action: "after" } //This will place the signature after the book element
});
more examples coming soon
The test framework is nodeunit. To run tests use:
$> npm test
This project is licensed under the MIT License. See the LICENSE file for more info.
v2.1.0 (2021-03-15)
FAQs
Xml digital signature and encryption library for Node.js
The npm package xml-crypto receives a total of 0 weekly downloads. As such, xml-crypto popularity was classified as not popular.
We found that xml-crypto demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.