node-saml / xml-crypto

Xml digital signature and encryption library for Node.js
MIT License
198 stars 171 forks source link

Signing root node without childs #136

Open alphanso opened 7 years ago

alphanso commented 7 years ago

Hi,

I am trying to sign a root node with only attributes and without any child nodes. It keeps failing signature verification but if I add a single space then it works. Is it an issue with library or my code. Please help me debug.

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

function main() {
  var xml = '<?xml version="1.0" encoding="UTF-8"?><library> </library>'
  var myXML = '<?xml version="1.0" encoding="UTF-8"?><library></library>'

  sign(xml, "library");
  console.log("\n\n\n\n");
  sign(myXML, "library");
}

function sign (xml) {
  var sig = new SignedXml()
  sig.addReference("/*", ["http://www.w3.org/2000/09/xmldsig#enveloped-signature"], "http://www.w3.org/2000/09/xmldsig#sha1", "", "", "", true);
  sig.signingKey = fs.readFileSync("./private.pem")
  sig.computeSignature(xml)
  var signed = sig.getSignatureXml()
  var withIds = sig.getOriginalXmlWithIds()
  console.log(signed)
  console.log(withIds)
  console.log(sig.getSignedXml())

  verify(signed, withIds);
}

function verify(signed, withIds) {
  var sig = new SignedXml()
  sig.keyInfoProvider = new FileKeyInfo("./public.pem")
  sig.loadSignature(signed)
  var res = sig.checkSignature(withIds)
  console.log(res)
  if (!res) console.log(sig.validationErrors)
  else console.log('Valid Signature')
}

main();

I actually need to encrypt following xml

<?xml version="1.0" encoding="UTF-8"?>
<Node att1="val1" ver="1.0" ts="2017-07-11T21:06:46.128" att2="val2" att3="1dea22d1-f153-4fd2-befa-527ffda2f692"/>
alphanso commented 7 years ago

I have identified the issue https://github.com/yaronn/xml-crypto/blob/master/lib/enveloped-signature.js#L9

We are using xpath in above given line. Once we remove signature then xpath reduce tag to which is not canonicalized form which leads to problem in xml signature as show above.

cjbarth commented 1 year ago

@alphanso , I'm very glad you found and fixed your issue. To help the community benefit from your efforts, would you consider creating a PR with a test suite and your solution?