How can get a xml validated with xml-crypto?

809 Views Asked by At

I am having trouble with xml-crypto, I am generating a signed xml, but this is always failing validation. I would like to understand what I am doing wrong. For me looks like is alright, but i don't know if I have to tell the validation method which algorithm to use, or if is something else.

xml-crypto version: "2.1.3",
node version: v12.13.0
xml-crypto: https://www.npmjs.com/package/xml-crypto

Steps to sign in

function signXml(xml, xpath, key, dest) {
  const sig = new SignedXml();
  sig.signingKey = key;
  sig.addReference(xpath);
  sig.computeSignature(xml);
  fs.writeFileSync(dest, sig.getSignedXml());
}

const xml = fs.readFileSync(`${process.cwd()}/unsigned.xml`).toString();
const key = fs.readFileSync(`${process.cwd()}/certificate/client.pem`);

signXml(
  xml,
  "//*[local-name(.)='book']",
  key,
  'result.xml'
);

Steps do validate

function validateXml(xml, key, xmlpath) {
  const doc = new dom().parseFromString(xmlsource);
  const signature = xpath(doc, xmlpath)[0];
  const sig = new SignedXml();
  sig.keyInfoProvider = new FileKeyInfo(key);
  sig.loadSignature(signature);
  const res = sig.checkSignature(xml);
  if (!res) console.log(sig.validationErrors);
  return res;
}

const xml2Validate = fs.readFileSync(`${process.cwd()}/result.xml`).toString();
const publicKey = `${process.cwd()}/certificate/client_public.pem`;
const xmlpath = "/*/*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']";
validateXml(xml2Validate, publicKey, xmlpath);

After validating, I am getting the following error on sig.validationErrors:

[
  'invalid signature: for uri #_0 calculated digest is p52UvC/9VdoauWLh7zO9275XTX0= but the xml to validate supplies digest WnPzEgQeIj+Kz8pC909+ziC5hmQ='
]

The unsigned.xml

<book>
  <name>
    harry Potter
  </name>
</book>

And the result.xml

<book Id="_0">
  <name>
    harry Potter
  </name>
<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>WnPzEgQeIj+Kz8pC909+ziC5hmQ=</DigestValue></Reference></SignedInfo><SignatureValue>mmXHcK3FYEtnc/vBPtTGhzxA0jsv6dOPmMDpf5i5fzQgmWwC+sm17z3bwTz1Mw01aceqta34QllcVALoWMY7mj1Q5ltr5TrPtf8o6bCl983xQPhm8iPB8cyGl5jF2Vmhw5FaEkkGkFtW3wC4geq0olG9bCGeHYub1JfRGX8E7G4=</SignatureValue></Signature></book>
0

There are 0 best solutions below