Skip to content

Instantly share code, notes, and snippets.

@yaronn
Created March 26, 2015 22:19
Show Gist options
  • Save yaronn/f30f3d8a06cafc5224aa to your computer and use it in GitHub Desktop.
Save yaronn/f30f3d8a06cafc5224aa to your computer and use it in GitHub Desktop.
//sign
var SignedXml = require('xml-crypto').SignedXml
, fs = require('fs');
var xml = fs.readFileSync("./x.xml").toString();
var sig = new SignedXml();
sig.addReference("//*[local-name(.)='EntityDescriptor']", ["http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#"], "http://www.w3.org/2000/09/xmldsig#sha1", "", "", "", true)
sig.signingKey = fs.readFileSync("./client.pem");
sig.computeSignature(xml);
fs.writeFileSync("signed.xml", sig.getSignedXml());
//validate
var select = require('xml-crypto').xpath
, dom = require('xmldom-fork-fixed').DOMParser
, SignedXml = require('xml-crypto').SignedXml
, FileKeyInfo = require('xml-crypto').FileKeyInfo
, fs = require('fs');
function validateXml(xml, key){
var doc = new dom({ignoreWhiteSpace: true}).parseFromString(xml);
xml = doc.toString();
//console.log(xml);
//fs.writeFileSync("signed_bad.xml", xml);
var signature = select(doc, "/*/*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0]
//console.log(signature);
var sig = new SignedXml();
sig.keyInfoProvider = new FileKeyInfo(key);
sig.loadSignature(signature.toString());
var res = sig.checkSignature(xml);
if (!res) console.log(sig.validationErrors);
return res;
}
var signedXml = fs.readFileSync("./signed.xml").toString()
console.log("validating signature...")
if (validateXml(signedXml, "./client_public.pem"))
console.log("signature is valid")
else
console.log("signature not valid")
//xml
<?xml version="1.0"?><EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" entityID="http://111.111.11.111:8000" Id="_0"><SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"><KeyDescriptor><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIIDrzCCAp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pH7ndT95R5XEfX1HepwfSYqc5oK+ISpwGQdIxchm3KKhr1BMW4i9OlIGCd75tQr2VVZnlSkKfS6zuFAHpn7ffJrS15OnucImnebJSXnTVeKzVI1/mkO0HJYkOQUMSMqzbZNYpXJxYM9DBwl5UETFbzeV7ua57K+XfVvpiqWiTGw=</ds:X509Certificate></ds:X509Data></ds:KeyInfo><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/></KeyDescriptor><NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</NameIDFormat><AssertionConsumerService index="1" isDefault="true" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="http://111.111.11.111:8000/saml/callback"/></SPSSODescriptor></EntityDescriptor>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment