Inclusive canonicalization (http://www.w3.org/TR/2001/REC-xml-c14n-20010315 and its
#WithComments variant) renders namespace declarations as the
C14N specification requires,
including when:
a prefixed element in the signed content declares a default namespace, as in
<p:item xmlns="urn:x">
the signed element inherits a default namespace and declares a prefixed namespace of its own
the signed element is prefixed, inherits a default namespace, and contains an element that
clears it with xmlns=""
the signed element redeclares a prefix that an ancestor binds, after declaring another namespace
Exclusive canonicalization (http://www.w3.org/2001/10/xml-exc-c14n# and its #WithComments
variant) renders the last case the same way when the redeclared prefix is listed in the
InclusiveNamespacesPrefixList.
Inclusive and exclusive canonicalization escape namespace declaration values as they escape
attribute values.
Ordinary attributes whose names start with xmlns, such as xmlnsRole, are part of the canonical
output. Exclusive canonicalization takes PrefixList bindings only from namespace declarations.
Processing instructions inside signed content are rendered with their target and <? ?>
delimiters.
An empty-URIReference signs processing instructions outside the document element. They appear
in getSignedReferences() when the transforms preserve them. When such instructions exist, a custom
transform receives the Document node rather than the document element.
Comments in referenced content
A Reference whose URI is empty or # followed by an ID, such as #item, removes comments from
the referenced content before its transforms run, as
same-document references require.
Comments in that content are not signed, even with a #WithComments transform: adding, removing
or changing one does not invalidate the signature. Read signed content from
getSignedReferences(), which does not contain them.
A custom transform in such a reference does not receive comment nodes.
A #WithCommentsCanonicalizationMethod signs the comments inside SignedInfo.
Transforms that end in a DOM node
When the last transform of a Reference returns a DOM Node, it is converted to octets with
inclusive canonicalization, as the
reference processing model
requires. A SignedInfo canonicalization algorithm that returns a Node is converted the same way,
and getCanonXml() returns canonical XML for such transform lists, for example <y></y>.
Transforms that follow a canonicalization
When a transform returns a string and another transform follows it in the same Reference, the
string is parsed into a new document and the next transform is applied to that, as the
reference processing model
requires. Every built-in canonicalization algorithm returns a string, so:
Exclusive canonicalization after inclusive canonicalization omits inherited namespace declarations
that the referenced element does not use.
A custom transform after a canonicalization receives the parsed document.
A transform throws when the string returned by the transform before it is not well-formed XML.
enveloped-signature is the exception. XMLDSig applies it only to
a node-set from its parent XML document,
which the parsed document is not, so list enveloped-signature before any canonicalization. Applying
it after a transform that returns a string is deprecated, when signing and when verifying, and will
throw in 7.0. Until then it prints a DeprecationWarning, and:
enveloped-signature after a canonicalization removes the Signature, including one inside the
referenced element.
The result of a #WithComments canonicalization followed by enveloped-signature is
canonicalized without comments.
Copies of an enveloped signature
The enveloped-signature transform removes only the Signature element being verified, as
XMLDSig requires.
checkSignature() finds that element by its SignatureValue, and throws when the document
contains more than one Signature element with that value.
getCanonXml() finds the loaded signature in the node's document the same way, and removes nothing
when the signature is not there.
Documents with a DOCTYPE
computeSignature() and checkSignature() do not process a document type declaration. An entity
it declares is not expanded and a default attribute it declares is not added, though
Canonical XML requires both, so the canonical form is
not the one an implementation that processes the declaration computes. Signing or verifying a
document that has a DOCTYPE is deprecated and will throw in 7.0. Until then it prints a
DeprecationWarning.
Malformed certificates
A certificate whose encapsulated data is not base64 is rejected rather than decoded as far as it
goes. Buffer.from(value, "base64") discards what it does not recognize, so a corrupt certificate
used to reach KeyInfo, or Node's crypto, as whatever bytes survived that. What the parser accepts is
described under X.509 / Key formats.
The error for a value the parser cannot read is Invalid PEM format., in place of the
Unknown DER format. that derToPem() threw. A Buffer holding the bytes of a PEM file is read
as that file rather than base64-encoded, which is what made it a message with a body of
base64-encoded PEM. Both forms of PEM the parser does read produce the same canonical output.
Input that 7.0 rejects
Each of these works in 6.x, prints a DeprecationWarning, and is rejected in 7.0.
When verifying:
a Reference whose URI is neither empty nor # followed by an ID. It is resolved as a
same-document ID all the same, though only those two forms are
same-document references.
a Transform with no Algorithm attribute, which is skipped. The
schema requires the attribute.
an InclusiveNamespaces element outside the http://www.w3.org/2001/10/xml-exc-c14n#namespace, whose PrefixList is applied all the
same. xml-crypto 6.3.2 and earlier wrote one when signing with xml-exc-c14n#WithComments and a
prefix list, so documents signed that way need signing again.
When signing:
a location.reference that selects a text node, a comment or a processing instruction, which
before and after place the Signature next to.
isEmptyUri: true on a reference whose xpath selects anything but the document element.
URI="" identifies the whole document,
so the signature this produces does not verify.
Deprecated ahead of 7.0
These exports are deprecated and will be removed in 7.0:
these are the escaping step of C14nCanonicalization and ExclusiveCanonicalization, so use those; a custom canonicalizer must apply C14N escaping itself
isArrayHasLength
Array.isArray(x) && x.length > 0
validateDigestValue
decode both from base64, then compare with a.length === b.length && crypto.timingSafeEqual(a, b) — timingSafeEqual alone throws on a length mismatch instead of returning false. Never ===
toPem(), pemToDer() and pemCertificates() apply the rules these described, and validate the encapsulated data as well; see X.509 / Key formats
derToPem
toPem(), which is the same function under a name that describes it: it takes a PEM message, several of them, base64, or a Buffer, and DER is only one of those
Calling one prints a DeprecationWarning naming its replacement. The three regexes cannot warn —
util.deprecate needs a call to intercept — so TypeScript users see the @deprecated tag and
JavaScript users get no signal until the names go away.
renderNs() and processInner() on C14nCanonicalization and ExclusiveCanonicalization are
deprecated and will be private in 7.0; call process() instead. Calling either one from outside
process(), or overriding one in a subclass, prints a DeprecationWarning.
toPem, pemToDer, pemCertificates, normalizePem and findAncestorNs are not
deprecated and stay exported.
The callback form of computeSignature() and checkSignature() is deprecated, and so are
createOptionalCallbackFunction and ErrorFirstCallback. computeSignatureAsync() and
checkSignatureAsync() replace them; see
Moving from the callback form.
getReferences() and references are deprecated. Do not use them to obtain signed XML; use
getSignedReferences() instead, as shown in Verifying Xml documents.
to enable HMAC-SHA1, call enableHMAC() on your instance of SignedXml.
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.
When signing a xml document you can pass the following options to the SignedXml constructor to customize the signature process:
privateKey - [required] a Buffer or pem encoded String containing your private key
publicCert - [optional] the X.509 certificate to publish in <KeyInfo>, or a chain of them, as PEM or as one certificate's base64 without the PEM boundaries, in a String or Buffer. A value that holds no certificate, such as a public key, produces no <KeyInfo>.
signatureAlgorithm - [required] one of the supported signature algorithms. Ex: sign.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
canonicalizationAlgorithm - [required] one of the supported canonicalization algorithms. Ex: sign.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
Use this code:
const { SignedXml } = require("xml-crypto");const fs = require("fs");const xml = "<library><book><name>Harry Potter</name></book></library>";const sig = new SignedXml({ privateKey: fs.readFileSync("client.pem"), canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#", signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",});sig.addReference({ xpath: "//*[local-name(.)='book']", digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256", transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],});sig.computeSignature(xml);fs.writeFileSync("signed.xml", sig.getSignedXml());
When verifying a xml document you can pass the following options to the SignedXml constructor to customize the verify process:
publicCert - [optional] the certificate or public key to verify with, as a PEM String or Buffer. Verification uses one key from it.
privateKey - [optional] your private key as a string or a Buffer - used for verifying symmetrical signatures (HMAC)
The certificate that will be used to check the signature will first be determined by calling this.getCertFromKeyInfo(), which function you can customize as you see fit. If that returns null, then publicCert is used. If that is null, then privateKey is used (for symmetrical signing applications).
Example:
new SignedXml({ publicCert: client_public_pem, getCertFromKeyInfo: () => null,});
You can use any dom parser you want in your code (or none, depending on your usage). This sample uses xmldom and xpath, so you should install them first:
npm install @xmldom/xmldom xpath
Example:
const { DOMParser } = require("@xmldom/xmldom");const xpath = require("xpath");const { SignedXml } = require("xml-crypto");const fs = require("fs");const xml = fs.readFileSync("signed.xml", "utf8");const doc = new DOMParser().parseFromString(xml, "text/xml");// DO NOT attempt to parse whatever data object you have here in `doc`// and then use it to verify the signature. This can lead to security issues.// i.e. BAD: parseAssertion(doc),// good: see belowconst signature = xpath.select1( "//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']", doc,);const sig = new SignedXml({ publicCert: fs.readFileSync("client_public.pem") });sig.loadSignature(signature);const res = sig.checkSignature(xml);
In order to protect from some attacks we must check the content we want to use is the one that has been signed:
if (!res) { throw new Error("Invalid signature");}// good: The XML Signature has been verified, meaning some subset of XML is verified.const signedBytes = sig.getSignedReferences();const authenticatedDoc = new DOMParser().parseFromString(signedBytes[0], "text/xml"); // Take the first signed reference// It is now safe to load SAML, obtain the assertion XML, or do whatever else is needed.// Be sure to only use authenticated data.const signedAssertionNode = extractAssertion(authenticatedDoc);const parsedAssertion = parseAssertion(signedAssertionNode);return parsedAssertion; // This the correctly verified signed Assertion// BAD example: DO not use the .getReferences() API.
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.
Caring for Implicit transform
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:
const sig = new SignedXml({ implicitTransforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"], publicCert: fs.readFileSync("client_public.pem"),});sig.loadSignature(signature);const res = sig.checkSignature(xml);
Implicit transforms run after the transforms a <Reference> declares. xml-crypto converts a
node-set left after the last transform to octets with Canonical XML 1.0, so an implicit
http://www.w3.org/TR/2001/REC-xml-c14n-20010315 changes nothing where the transforms end in a
node-set, such as when there are none or the last one is enveloped-signature.
You might find it difficult to guess such transforms, but there are typical transforms you can try.
The SignedXml constructor provides an abstraction for sign and verify xml documents. The object is constructed using new SignedXml(options?: SignedXmlOptions) where the possible options are:
idMode - default null - if the value of wssecurity is passed it will create/validate id's with the ws-security namespace.
idAttribute - string - default undefined - the name of an additional attribute that holds an element's id; it is checked before Id, ID and id
privateKey - string or Buffer - default null - the private key to use for signing
publicCert - string or Buffer - default null - the public certificate to use for verifying
signatureAlgorithm - string - the signature algorithm to use
canonicalizationAlgorithm - string - default undefined - the canonicalization algorithm to use
inclusiveNamespacesPrefixList - string - default null - a list of namespace prefixes to include during canonicalization
implicitTransforms - string[] - default [] - a list of implicit transforms to use during verification
keyInfoAttributes - object - default {} - a hash of attributes and values attrName: value to add to the KeyInfo node
getKeyInfoContent - function - default SignedXml.getKeyInfoContent - a function that returns the content of the KeyInfo node
getCertFromKeyInfo - function - default noop - a function that returns the certificate from the <KeyInfo /> node
API
A SignedXml object provides the following methods:
To sign xml documents:
addReference({ xpath, transforms, digestAlgorithm, id, type, isEmptyUri, inclusiveNamespacesPrefixList }) - adds a reference to a xml element where:
xpath - a string containing a XPath expression referencing a xml element
transforms - an array of transform algorithms, the referenced element will be transformed for each value in the array
id - an optional Id attribute to add to the reference element
type - the optional Type attribute to add to the reference element (represented as a URI)
isEmptyUri - optional, default false - when true, the reference is written as URI="", which refers to the whole document, and no Id is added to the referenced element. xpath must then select the document element, for example /*: a signature that references any other element this way doesn't verify
inclusiveNamespacesPrefixList - an optional array of namespace prefixes that exclusive canonicalization of this reference renders even where they aren't visibly used. It is written as the InclusiveNamespacesPrefixList parameter of the reference's exclusive canonicalization transform. Use #default to include the default namespace, including on a prefixed element
computeSignature(xml, [options]) - compute the signature of the given xml where:
xml - a string containing a xml document
options - an object with the following properties:
prefix - adds this value as a prefix for the generated signature tags
attrs - a hash of attributes and values attrName: value to add to the signature root node
location - 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 xml
computeSignatureAsync(xml, [options]) - computeSignature for a signature algorithm that signs asynchronously; returns a promise for the SignedXml instance. See Asynchronous signing and verification
getSignedXml() - 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() - [deprecated] returns the original xml with Id attributes added on relevant elements, must be called only after computeSignature. Use the location option of computeSignature() to place the signature, then getSignedXml(). See how to specify the location of the signature. For a detached signature, put an ID attribute the signer recognizes on each referenced element (wsu:Id for WS-Security), sign that document, and send it alongside getSignatureXml(). Make sure each reference XPath still selects its intended element once those IDs are present, for example by selecting on the ID itself.
Every reference XPath is evaluated against the input document before any IDs or the signature
are added, so the order of addReference() calls does not change what a reference selects. A
reference that matches nothing in the input is evaluated after the signature is inserted and
selects only elements inside the new signature, such as generated Object or KeyInfo
elements. Use separate addReference() calls for input elements and generated signature content.
An input match takes precedence, so a reference whose XPath also matches an input element signs
that element and leaves the generated one unsigned. Select generated content by the Id you
configured for it, as in how to add custom Objects to the signature,
rather than by element name.
To verify xml documents:
loadSignature(signatureXml) - loads the signature where:
signatureXml - a string or node object (like an xmldom node) containing the xml representation of the signature
checkSignature(xml) - validates the given xml document and returns true if the validation was successful
checkSignatureAsync(xml) - checkSignature for a signature algorithm that verifies asynchronously; returns a promise for true if the validation was successful
getSignedReferences() - returns the canonical XML of each reference, only after checkSignature succeeds
validateElementAgainstReferences(elemOrXpath, doc) - [deprecated] after checkSignature succeeds, use the XML that getSignedReferences() returns instead of nodes from the original document
One instance per signature
Create a new SignedXml for each signature you create or verify, including each signature in a document that has more than one. An instance keeps state between calls:
computeSignature() signs every reference the instance holds. addReference() adds one, so calling it for each signature on a reused instance adds one more Reference to every new signature. checkSignature() replaces them with the references of the signature it checks.
getSignedReferences() returns the references of each successful checkSignature() call since the last failed one, which empties it. On a reused instance, that can include content that earlier signatures cover.
Customizing Algorithms
The following sample shows how to sign a message using custom algorithms.
Now define the extension point you want to implement. You can choose one or more.
To determine the inclusion and contents of a <KeyInfo /> element, the function
this.getKeyInfoContent() is called. There is a default implementation of this. If you wish to change
this implementation, provide your own function assigned to the property this.getKeyInfoContent. If
it returns no content, the <KeyInfo /> element is not included in the generated XML, even when
keyInfoAttributes are set.
To specify custom attributes on <KeyInfo />, add the properties to the .keyInfoAttributes property.
A custom hash algorithm is used to calculate digests. Implement it if you want a hash other than the built-in methods.
class MyDigest { getHash(xml) { return "the base64 hash representation of the given xml string"; } getAlgorithmName() { return "http://myDigestAlgorithm"; }}
A custom signing algorithm.
class MySignatureAlgorithm { // Sign the given SignedInfo using the key. Return the base64 signature value. getSignature(signedInfo, privateKey) { return "signature of signedInfo as base64..."; } getAlgorithmName() { return "http://mySigningAlgorithm"; }}
Custom transformation algorithm.
class MyTransformation { // Given a node (from the xmldom module), return its canonical representation as a string. process(node) { // You should apply your transformation before returning. return node.toString(); } getAlgorithmName() { return "http://myTransformation"; }}
Custom canonicalization is actually the same as custom transformation. It is applied on the SignedInfo rather than on references.
class MyCanonicalization { // Given a node (from the xmldom module), return its canonical representation as a string. process(node) { // You should apply your canonicalization before returning. return node.toString(); } getAlgorithmName() { return "http://myCanonicalization"; }}
Now register the new algorithms on a SignedXml instance, under the names their getAlgorithmName()
returns, and configure the instance to use them:
function signXml(xml, xpath, key, dest) { const sig = new SignedXml({ publicCert: fs.readFileSync("my_public_cert.pem", "latin1"), privateKey: fs.readFileSync(key), // Configure the signature object to use the custom algorithms. signatureAlgorithm: "http://mySigningAlgorithm", canonicalizationAlgorithm: "http://myCanonicalization", }); // Register all the custom algorithms. sig.CanonicalizationAlgorithms["http://myTransformation"] = MyTransformation; sig.CanonicalizationAlgorithms["http://myCanonicalization"] = MyCanonicalization; sig.HashAlgorithms["http://myDigestAlgorithm"] = MyDigest; sig.SignatureAlgorithms["http://mySigningAlgorithm"] = MySignatureAlgorithm; sig.addReference({ xpath, transforms: ["http://myTransformation"], digestAlgorithm: "http://myDigestAlgorithm", }); sig.computeSignature(xml); fs.writeFileSync(dest, sig.getSignedXml());}const 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.
Asynchronous signing and verification
If the private key is not stored locally, and you wish to use a signing server or Hardware Security Module (HSM) to sign documents, the signature algorithm has to wait for its answer. Give a custom signature algorithm a getSignatureAsync() method that returns a promise, and sign with computeSignatureAsync(). Register the algorithm under the URI of the algorithm it implements, which is the SignatureMethod a verifier reads.
const { SignedXml } = require("xml-crypto");const crypto = require("crypto");const fs = require("fs");class AsyncRsaSha256 { async getSignatureAsync(signedInfo, privateKey) { // Do some asynchronous things here, such as calling a signing server. const signer = crypto.createSign("RSA-SHA256"); signer.update(signedInfo); return signer.sign(privateKey, "base64"); } async verifySignatureAsync(material, key, signatureValue) { // Do some asynchronous things here, too. const verifier = crypto.createVerify("RSA-SHA256"); verifier.update(material); return verifier.verify(key, signatureValue, "base64"); } getAlgorithmName() { return "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; }}async function sign(xml) { const sig = new SignedXml({ privateKey: fs.readFileSync("client.pem"), canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#", signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", }); sig.SignatureAlgorithms["http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"] = AsyncRsaSha256; sig.addReference({ xpath: "//*[local-name(.)='book']", digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256", transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"], }); await sig.computeSignatureAsync(xml); return sig;}sign("<library><book><name>Harry Potter</name></book></library>").then((sig) => fs.writeFileSync("signed.xml", sig.getSignedXml()),);
computeSignatureAsync() takes what computeSignature() takes and resolves with the SignedXml instance. checkSignatureAsync() does the same for checkSignature(): it waits for the algorithm's verifySignatureAsync() and resolves with true for a valid signature.
async function verify(xml, signature) { const sig = new SignedXml({ publicCert: fs.readFileSync("client_public.pem") }); sig.SignatureAlgorithms["http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"] = AsyncRsaSha256; sig.loadSignature(signature); if (!(await sig.checkSignatureAsync(xml))) { throw new Error("Invalid signature"); } return sig.getSignedReferences();}
Both call getSignature() or verifySignature() on an algorithm that has no Async method, so they work with the built-in algorithms too. The SignatureAlgorithm type requires getSignature() and verifySignature(); an algorithm that only works asynchronously can have them throw.
Moving from the callback form
The callback form of computeSignature() and checkSignature() is deprecated and will be removed in 7.0. Passing a callback prints a DeprecationWarning.
With a built-in algorithm, or any other that returns its answer, call them without the callback:
createOptionalCallbackFunction and ErrorFirstCallback serve only the callback form. An algorithm needs neither once its methods return their answer or a promise for it.
X.509 / Key formats
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 beginning of the key content is shown):
privateKey when signing, and publicCert when verifying, are passed to Node's crypto, which uses
one key from the value.
privateKey holds one private key. A file that also holds its certificate, or its chain, is
fine.
Verification takes one key from publicCert. From several certificates it takes the first, which
is how a chain given leaf first works, so the chain's issuers are not trusted to sign.
To trust several independent keys, verify with each in turn, as node-saml does for its idpCert
array.
What the parser accepts
toPem(), pemToDer() and pemCertificates() read
RFC 7468 textual messages, and toPem() also reads bare
base64 with a label supplied by the caller. Either form is judged by the same rules, and toPem()
returns the same certificate whatever it arrived as: \n line endings, lines of 64 characters,
one message after another.
toPem(value, label?) returns canonical PEM. A Buffer that opens with an encapsulation
boundary is read as the bytes of a PEM file and any other as raw DER, so base64 text is given
as a string rather than a Buffer.
pemToDer(pem) returns the decoded bytes of the one message a value holds.
pemCertificates(pem) returns the base64 of each CERTIFICATE message and ignores messages of
any other label, so a private key in the same value is never published. It reads certificates
out of a larger value, passing over the explanatory text tools write around a message, while
toPem() rewrites the whole value and so must account for all of it.
Accepted:
\n, \r\n and \r line endings, and a leading UTF-8 BOM.
any line width, a single line included.
spaces and tabs anywhere in the encapsulated data. XMLDSig carries a certificate as
xs:base64Binary, whose lexical space
collapses whitespace, so a pretty-printed document indents it and a value that has been through
a text field may have had its line endings replaced by spaces.
a blank line after the header, and a blank line anywhere among the lines of base64 given
without boundaries, which is the form an X509Certificate element carries. A blank line inside
a message's body is rejected; RFC 7468's body does not have one.
explanatory text before, after or between the messages, which pemCertificates() passes over.
Section 5.2 shows a certificate written
under its subject and issuer lines, and OpenSSL and keytool both write them.
several messages in one value, of which toPem() keeps all, pemCertificates() takes the
certificates, and pemToDer() takes none.
any non-empty label of up to 48 characters that RFC 7468's grammar allows, which is every
registered label and the ones OpenSSL adds, such as RSA PRIVATE KEY. PemLabel names the
registered ones, the longest of which is 21 characters.
a certificate encoded as BER as well as DER, as
RFC 7468 section 5.1 allows. Its octets are
kept as given, because XML Signature 1.1
says an implementation SHOULD NOT alter or re-encode a certificate.
base64 whose pad bits are not zero, which is written back out with them zeroed, since only that
form is in xs:base64Binary's lexical space.
The octets are the same either way.
the Proc-Type and DEK-Info header fields of a traditional encrypted private key, as OpenSSL
and Node write one, so that pemCertificates() can read certificates out of a bundle holding
such a key. toPem() and pemToDer() refuse the key itself, whose data is lost without them.
Rejected, with an error rather than a certificate:
data outside the base64 alphabet, padding away from the end, or a final quantum that is not
whole, per RFC 4648 section 4.
a CERTIFICATE whose data is not exactly one X.509 certificate: base64 of something else, a
certificate cut short, or one with more bytes after it. Node's
X509Certificate decides whether
the data is a certificate, so it is judged as X.509 and not by its base64 alone.
a PRIVATE KEY or RSA PRIVATE KEY whose data Node cannot read as a private key under that
label: PKCS #1 data labelled PRIVATE KEY, a public key, or base64 of something else. Node's
crypto.createPrivateKey()
decides, so the answer follows the Node version: Node 16 refuses PKCS #8 data labelled
RSA PRIVATE KEY, and later versions read it. Base64 does not say whether a key is PKCS #8,
which is PRIVATE KEY, or PKCS #1, which is RSA PRIVATE KEY, so a caller that takes either as
bare base64 tries PRIVATE KEY first and RSA PRIVATE KEY second. In that order each key comes
out under its own label on every supported Node version. Tried the other way round, PKCS #8 data
comes out labelled RSA PRIVATE KEY on a Node version that reads it so, and Node 16 then refuses
that PEM.
a header with no data under it, and a blank line in the middle of a message's data.
a boundary sharing its line with other text.
Figure 1 gives an encapsulation boundary a
line of its own, so text on that line is not the explanatory text around a message.
a value that opens a message it does not close, or one whose header and footer labels disagree.
Section 3 permits a parser to disregard the
footer's label, but OpenSSL will not read such a message, so neither does this one.
an empty label, which the label production marks as empty ok. A message labelled nothing
names no format, and OpenSSL answers one with ERR_OSSL_UNSUPPORTED, so -----BEGIN ----- and
toPem(data, "") are both refused.
a label outside RFC 7468's grammar, which is one holding -- or opening or closing with a
blank, and one longer than 48 characters. A label is written into both boundaries, so one
holding -- would produce a message this parser could not read back, and -----BEGIN and
----- bracket it in 16 characters, so 48 is the longest whose boundary still fits one line.
Converting .pfx certificates to pem
If you have .pfx certificates you can convert them to .pem using openssl:
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.
Examples
how to add a prefix for the signature
Use the prefix option when calling computeSignature to add a prefix to the signature.
Use the location option when calling computeSignature to move the signature around. Set
reference to an XPath expression that selects a node (default /*, the document element), and
action to one of the following:
append (default) - insert the signature as the last child of the reference node
prepend - insert the signature as the first child of the reference node
before - insert the signature just before the reference node
after - insert the signature just after the reference node
const { SignedXml } = require("xml-crypto");const fs = require("fs");const xml = "<library><book><name>Harry Potter</name></book></library>";const sig = new SignedXml({ privateKey: fs.readFileSync("client.pem"), canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#", signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",});sig.addReference({ xpath: "//*[local-name(.)='book']", digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256", transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],});sig.computeSignature(xml, { location: { reference: "//*[local-name(.)='book']", action: "after" }, // This will place the signature after the book element});
How to add custom Objects to the signature
Use the objects option when creating a SignedXml instance to add custom Objects to the signature.
const { SignedXml } = require("xml-crypto");const fs = require("fs");const xml = "<library><book><name>Harry Potter</name></book></library>";const sig = new SignedXml({ privateKey: fs.readFileSync("client.pem"), canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#", signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", objects: [ { content: "<TestObject>Test data in Object</TestObject>", attributes: { Id: "Object1", MimeType: "text/xml", }, }, ],});// Add a reference to the Object elementsig.addReference({ xpath: "//*[@Id='Object1']", digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256", transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],});sig.computeSignature(xml);fs.writeFileSync("signed.xml", sig.getSignedXml());
Development
The testing framework we use is Mocha with Chai as the assertion framework.