Gathering detailed insights and metrics for web-xml-crypto
Gathering detailed insights and metrics for web-xml-crypto
Gathering detailed insights and metrics for web-xml-crypto
Gathering detailed insights and metrics for web-xml-crypto
xml-crypto
Xml digital signature and encryption library for Node.js
@aws-crypto/supports-web-crypto
Provides functions for detecting if the host environment supports the WebCrypto API
@types/xml-crypto
TypeScript definitions for xml-crypto
@redocly/xml-crypto
Xml digital signature and encryption library for Node.js
npm install web-xml-crypto
75.2
Supply Chain
97.8
Quality
75.2
Maintenance
25
Vulnerability
98.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
244 Commits
2 Watching
3 Branches
1 Contributors
Updated on 06 Jun 2019
JavaScript (87.68%)
C# (9.7%)
Java (2.62%)
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
0%
1
Compared to previous week
Last month
-14%
37
Compared to previous month
Last year
-24.2%
1,166
Compared to previous year
3
1
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.
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:
1 var SignedXml = require('xml-crypto').SignedXml 2 , fs = require('fs') 3 4 var xml = "<library>" + 5 "<book>" + 6 "<name>Harry Potter</name>" + 7 "</book>" + 8 "</library>" 9 10 var sig = new SignedXml() 11 sig.addReference("//*[local-name(.)='book']") 12 sig.signingKey = fs.readFileSync("client.pem") 13 sig.computeSignature(xml) 14 fs.writeFileSync("signed.xml", sig.getSignedXml()) 15
The result will be:
1 <library> 2 <book Id="_0"> 3 <name>Harry Potter</name> 4 </book> 5 <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> 6 <SignedInfo> 7 <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> 8 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> 9 <Reference URI="#_0"> 10 <Transforms> 11 <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> 12 </Transforms> 13 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> 14 <DigestValue>cdiS43aFDQMnb3X8yaIUej3+z9Q=</DigestValue> 15 </Reference> 16 </SignedInfo> 17 <SignatureValue>vhWzpQyIYuncHUZV9W...[long base64 removed]...</SignatureValue> 18 </Signature> 19 </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:
1 var select = require('xml-crypto').xpath 2 , dom = require('xmldom').DOMParser 3 , SignedXml = require('xml-crypto').SignedXml 4 , FileKeyInfo = require('xml-crypto').FileKeyInfo 5 , fs = require('fs') 6 7 var xml = fs.readFileSync("signed.xml").toString() 8 var doc = new dom().parseFromString(xml) 9 10 var signature = select(doc, "/*/*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0] 11 var sig = new SignedXml() 12 sig.keyInfoProvider = new FileKeyInfo(fs.readFileSync("client_public.pem")) 13 sig.loadSignature(signature) 14 var res = sig.checkSignature(xml) 15 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:
1 var elem = select(doc, "/xpath_to_interesting_element"); 2 var uri = sig.references[0].uri; // might not be 0 - depending on the document you verify 3 var id = (uri[0] === '#') ? uri.substring(1) : uri; 4 if (elem.getAttribute('ID') != id && elem.getAttribute('Id') != id && elem.getAttribute('id') != id) 5 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:
1var option = {implicitTransforms: ["http://www.w3.org/TR/2001/REC-xml-c14n-20010315"]} 2var sig = new SignedXml(null, option) 3sig.keyInfoProvider = new FileKeyInfo(fs.readFileSync("client_public.pem")) 4sig.loadSignature(signature) 5var 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([fileContents])
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:
1 var SignedXml = require('xml-crypto').SignedXml 2 , 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.
1 /**/ 2 function MyKeyInfo() { 3 this.getKeyInfo = function(key, prefix) { 4 prefix = prefix || '' 5 prefix = prefix ? prefix + ':' : prefix 6 return "<" + prefix + "X509Data></" + prefix + "X509Data>" 7 } 8 this.getKey = function(keyInfo) { 9 //you can use the keyInfo parameter to extract the key in any way you want 10 return fs.readFileSync("key.pem") 11 } 12 }
A custom hash algorithm is used to calculate digests. Implement it if you want a hash other than the default SHA1.
1 function MyDigest() { 2 3 4 this.getHash = function(xml) { 5 return "the base64 hash representation of the given xml string" 6 } 7 8 this.getAlgorithmName = function() { 9 return "http://myDigestAlgorithm" 10 } 11 }
A custom signing algorithm. The default is RSA-SHA1
1 function MySignatureAlgorithm() { 2 3 /*sign the given SignedInfo using the key. return base64 signature value*/ 4 this.getSignature = function(signedInfo, signingKey) { 5 return "signature of signedInfo as base64..." 6 } 7 8 this.getAlgorithmName = function() { 9 return "http://mySigningAlgorithm" 10 } 11 12 }
Custom transformation algorithm. The default is exclusive canonicalization.
1 function MyTransformation() { 2 3 /*given a node (from the xmldom module) return its canonical representation (as string)*/ 4 this.process = function(node) { 5 //you should apply your transformation before returning 6 return node.toString() 7 } 8 9 this.getAlgorithmName = function() { 10 return "http://myTransformation" 11 } 12 }
Custom canonicalization is actually the same as custom transformation. It is applied on the SignedInfo rather than on references.
1 function MyCanonicalization() { 2 3 /*given a node (from the xmldom module) return its canonical representation (as string)*/ 4 this.process = function(node) { 5 //you should apply your transformation before returning 6 return "< x/>" 7 } 8 9 this.getAlgorithmName = function() { 10 return "http://myCanonicalization" 11 } 12 }
Now you need to register the new algorithms:
1 /*register all the custom algorithms*/ 2 3 SignedXml.CanonicalizationAlgorithms["http://MyTransformation"] = MyTransformation 4 SignedXml.CanonicalizationAlgorithms["http://MyCanonicalization"] = MyCanonicalization 5 SignedXml.HashAlgorithms["http://myDigestAlgorithm"] = MyDigest 6 SignedXml.SignatureAlgorithms["http://mySigningAlgorithm"] = MySignatureAlgorithm
Now do the signing. Note how we configure the signature to use the above algorithms:
1 function signXml(xml, xpath, key, dest) 2 { 3 var sig = new SignedXml() 4 5 /*configure the signature object to use the custom algorithms*/ 6 sig.signatureAlgorithm = "http://mySignatureAlgorithm" 7 sig.keyInfoProvider = new MyKeyInfo() 8 sig.canonicalizationAlgorithm = "http://MyCanonicalization" 9 sig.addReference("//*[local-name(.)='x']", ["http://MyTransformation"], "http://myDigestAlgorithm") 10 11 sig.signingKey = fs.readFileSync(key) 12 sig.addReference(xpath) 13 sig.computeSignature(xml) 14 fs.writeFileSync(dest, sig.getSignedXml()) 15 } 16 17 var xml = "<library>" + 18 "<book>" + 19 "<name>Harry Potter</name>" + 20 "</book>" 21 "</library>" 22 23 signXml(xml, 24 "//*[local-name(.)='book']", 25 "client.pem", 26 "result.xml")
You can always look at the actual code as a sample (or drop me a mail).
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.
1var SignedXml = require('xml-crypto').SignedXml 2 , fs = require('fs'); 3 4var xml = "<library>" + 5 "<book>" + 6 "<name>Harry Potter</name>" + 7 "</book>" + 8 "</library>"; 9 10var sig = new SignedXml(); 11sig.addReference("//*[local-name(.)='book']"); 12sig.signingKey = fs.readFileSync("client.pem"); 13sig.computeSignature(xml,{ 14 prefix: 'ds' 15});
###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)1var SignedXml = require('xml-crypto').SignedXml 2 , fs = require('fs'); 3 4var xml = "<library>" + 5 "<book>" + 6 "<name>Harry Potter</name>" + 7 "</book>" + 8 "</library>"; 9 10var sig = new SignedXml(); 11sig.addReference("//*[local-name(.)='book']"); 12sig.signingKey = fs.readFileSync("client.pem"); 13sig.computeSignature(xml,{ 14 location: { reference: "//*[local-name(.)='book']", action: "after" } //This will place the signature after the book element 15}); 16
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.
No vulnerabilities found.
Reason
license file detected
Details
Reason
binaries present in source code
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
46 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More