public LicenseDetails ValidateLicenseXml(string xml) { var doc = new XmlDocument(); using (TextReader reader = new StringReader(xml)) { try { doc.Load(reader); } catch { throw new InvalidLicenseXmlException(); } // Validate the xml's signature var signedXml = new SignedXml(doc); var nodeList = doc.GetElementsByTagName("Signature"); if (nodeList.Count == 0) throw new LicenseSignatureMissingException(); signedXml.LoadXml((XmlElement) nodeList[0]); if (!signedXml.CheckSignature(_key)) throw new LicenseSignatureMismatchException(); } // Deserialize the xml var deserializer = new XmlSerializer(typeof(LicenseDetails)); using (TextReader reader = new StringReader(xml)) return (LicenseDetails) deserializer.Deserialize(reader); }
public void VerifyXml(string xml) { var doc = LoadXmlDoc(xml); using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#"); var signedXml = new SignedXml(doc); var signature = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr); if (signature == null) { throw new Exception("Xml is invalid as it has no XML signature"); } signedXml.LoadXml(signature); if (!signedXml.CheckSignature(rsa)) { throw new Exception("Xml is invalid as it failed signature check."); } } }
/// <summary> /// Verifies the digital signature. /// </summary> /// <param name="digitalSignature"> The XML Digital Signature.</param> /// <param name="publicKey"> The RSA public key.</param> /// <returns> Returns true if valid, else false.</returns> public static bool VerifyDigitalSignature(XmlTextReader digitalSignature, RSA publicKey) { bool valid = false; try { // Load license file into XmlDocument XmlDocument doc = new XmlDocument(); doc.Load(digitalSignature); // Load Signature Element SignedXml verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); // Validate license. if ( verifier.CheckSignature(publicKey) ) { valid = true; } else { valid = false; } } catch { valid = false; } return valid; }
// Verify the signature of an XML file against an asymmetric // algorithm and return the result. public static Boolean VerifyXml(XmlDocument Doc, RSA Key) { // Check arguments. if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(Doc); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = Doc.GetElementsByTagName("Signature"); // Throw an exception if no signature was found. if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } //One Sig per document if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } // Load the first <signature> node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); }
public bool IsValid() { XmlNamespaceManager manager = new XmlNamespaceManager(XmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = XmlDoc.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(XmlDoc); signedXml.LoadXml((XmlElement)nodeList[0]); return signedXml.CheckSignature(DecrypingCertificate, true); }
public void Constructor_XmlDocument () { XmlDocument doc = new XmlDocument (); doc.LoadXml (signature); XmlNodeList xnl = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement xel = (XmlElement) xnl [0]; SignedXml sx = new SignedXml (doc); sx.LoadXml (doc.DocumentElement); Assert.IsTrue (sx.CheckSignature (), "CheckSignature"); }
public static Boolean CheckSignedXmlDocument(Stream sourceXmlFile) { // Carico il documento XML XmlDocument doc = new XmlDocument(); doc.Load(sourceXmlFile); // Verifico la firma SignedXml sigs = new SignedXml(doc); XmlNodeList sigElems = doc.GetElementsByTagName("Signature"); sigs.LoadXml((XmlElement)sigElems[0]); return (sigs.CheckSignature()); }
public static bool XmlIsValid(XmlDocument signedXml, AsymmetricAlgorithm key) { var nsm = new XmlNamespaceManager(new NameTable()); nsm.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); var signatureGenerator = new SignedXml(signedXml); var signatureNode = signedXml .SelectSingleNode("//dsig:Signature", nsm); signatureGenerator.LoadXml((XmlElement)signatureNode); return signatureGenerator.CheckSignature(key); }
public bool IsValid(KeyInfo keyInfo) { SignedXml xml = new SignedXml(_doc); XmlNodeList nodeList = _doc.GetElementsByTagName("Signature"); xml.LoadXml((XmlElement)nodeList[0]); xml.KeyInfo = keyInfo; xml.Resolver = null; return xml.CheckSignature(); }
static void Main(string[] args) { var xml = "<xml><a ID=\"foo\"><content>foo-content</content><Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\" /></a><a ID=\"bar\"><content>bar-content</content><Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\" /></a></xml>"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); var key = new RSACryptoServiceProvider(); var sign = new SignedXml(xmlDocument); var reference2 = new Reference("#bar"); reference2.AddTransform(new XmlDsigEnvelopedSignatureTransform()); sign.AddReference(reference2); sign.SigningKey = key; sign.ComputeSignature(); var barNode = (XmlElement)xmlDocument.SelectSingleNode("//*[@ID=\"bar\"]"); barNode.AppendChild(xmlDocument.ImportNode(sign.GetXml(), true)); var barSignature = barNode.ChildNodes.OfType<XmlElement>() .Single(x => x.LocalName == "Signature" && x.HasChildNodes); WriteLine("== Xml document =="); WriteLine(xmlDocument.OuterXml); WriteLine(); var verify = new SignedXml(xmlDocument); verify.LoadXml(barSignature); WriteLine("Check Signature: " + verify.CheckSignature(key)); WriteLine(); WriteLine("Reloading SignedXml and fixing signature index..."); verify.LoadXml(barSignature); FixSignatureIndex(verify, barSignature); WriteLine("Check Signature: " + verify.CheckSignature(key)); ReadLine(); }
public bool IsResponseValid(XmlDocument xDoc) { XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = xDoc.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(xDoc); signedXml.LoadXml((XmlElement)nodeList[0]); X509Certificate2 cSigningCertificate = new X509Certificate2(); cSigningCertificate.Import(HttpContext.Current.Server.MapPath(".") + @"\Certificates\SignCertFromCentrify.cer"); return signedXml.CheckSignature(cSigningCertificate, true); }
public bool IsValid() { bool status = false; XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.LoadXml((XmlElement)nodeList[0]); status = signedXml.CheckSignature(certificateHelper.cert, true); if (!status) return false; return status; }
public void XmlDocumentExtensions_Sign() { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml("<root><content>Some Content</content></root>"); xmlDoc.Sign(TestCert); var signature = xmlDoc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl]; var signedXml = new SignedXml(xmlDoc); signedXml.LoadXml(signature); signedXml.CheckSignature(TestCert, true).Should().BeTrue(); }
public void XmlDocumentExtensions_Sign() { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml("<root ID=\"rootElementId\"><content>Some Content</content></root>"); xmlDoc.Sign(TestCert); var signature = xmlDoc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl]; signature["SignedInfo", SignedXml.XmlDsigNamespaceUrl] ["Reference", SignedXml.XmlDsigNamespaceUrl].Attributes["URI"].Value .Should().Be("#rootElementId"); var signedXml = new SignedXml(xmlDoc); signedXml.LoadXml(signature); signedXml.CheckSignature(TestCert, true).Should().BeTrue(); }
public void GeneratedXmlIsCorrectlySigned() { var key = new RSACryptoServiceProvider(); var generator = new LicenseGenerator(key); var rawXml = generator.GenerateSignedXml(new LicenseDetails()); var doc = new XmlDocument(); TextReader reader = new StringReader(rawXml); doc.Load(reader); var signedXml = new SignedXml(doc); var nodeList = doc.GetElementsByTagName("Signature"); signedXml.LoadXml((XmlElement)nodeList[0]); var result = signedXml.CheckSignature(key); Assert.IsTrue(result, "Verification of xml signature failed"); }
public bool IsValid() { _log.Debug("Checking Saml response."); XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(xmlDoc); foreach (XmlNode node in nodeList) { signedXml.LoadXml((XmlElement)node); if (!signedXml.CheckSignature(_certificate.cert, true)) { _log.Error("Certificate validaiton failed."); return false; } } return IsValidEmail(GetNameID()); }
/// <summary> /// Verify /// </summary> /// <param name="input">The input.</param> /// <param name="serial">The serial.</param> /// <returns></returns> public override bool Verify(Stream input, string serial = null) { var result = false; var xmlDoc = new XmlDocument { PreserveWhitespace = true }; xmlDoc.Load(input); var signedXml = new SignedXml(xmlDoc); var nodeList = xmlDoc.GetElementsByTagName("Signature"); if (nodeList.Count > 0) { foreach (var node in nodeList) { signedXml.LoadXml((XmlElement)node); result = signedXml.CheckSignature(); } } return result; }
public static bool VerifySignature(XmlReader reader, out X509Certificate2 certificate) { XmlDocument document = new XmlDocument(); document.PreserveWhitespace = false; document.Load(reader); SignedXml signedXml = new SignedXml(document); XmlNodeList nodeList = document.GetElementsByTagName("Signature"); certificate = null; if (nodeList.Count == 1) { signedXml.LoadXml((XmlElement)nodeList[0]); certificate = signedXml.KeyInfo.OfType<KeyInfoX509Data>().SelectMany(c => c.Certificates.OfType<X509Certificate2>()).FirstOrDefault(); return signedXml.CheckSignature(); } return false; }
public static bool ValidateSignature(IClientLicense license, ICryptoKey publicKey) { var namespaceManager = new XmlNamespaceManager(license.Content.NameTable); namespaceManager.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#"); var signature = (XmlElement)license.Content.SelectSingleNode("//sig:Signature", namespaceManager); if (signature == null) { return false; } var signedXml = new SignedXml(license.Content); signedXml.LoadXml(signature); using (var publicKeyProvider = new RsaPublicKeyProvider()) { return signedXml.CheckSignature(publicKeyProvider.Create(publicKey)); } }
public static bool Check(byte[] modulus, byte[] exponent, XmlDocument xml) { Contract.Requires(modulus != null); Contract.Requires(exponent != null); Contract.Requires(xml != null); var signedXml = new SignedXml(xml); XmlNodeList nodeList = xml.GetElementsByTagName("Signature"); if (nodeList.Count == 0) return false; signedXml.LoadXml((XmlElement)nodeList[0]); using (var rsaKey = new RSACryptoServiceProvider()) { rsaKey.ImportParameters( new RSAParameters { Modulus = modulus, Exponent = exponent }); return signedXml.CheckSignature(rsaKey); } }
//------------------------------------------------------------------------------------------- public static Boolean VerifyXml(XmlDocument Doc, RSA Key) { if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); SignedXml signedXml = new SignedXml(Doc); XmlNodeList nodeList = Doc.GetElementsByTagName("Signature"); if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } else if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } signedXml.LoadXml((XmlElement)nodeList[0]); return signedXml.CheckSignature(Key); }
public bool Execute() { Console.Out.WriteLine("Validating xml signature"); Console.Out.WriteLine("xml file = {0}", _xmlFile); Console.Out.WriteLine("signature file = {0}", _signatureFile); var doc = new XmlDocument {PreserveWhitespace = true}; doc.Load(_xmlFile); var signature = new XmlDocument {PreserveWhitespace = true}; signature.Load(_signatureFile); var signedXml = new SignedXml(doc); signedXml.LoadXml(signature.DocumentElement); var checkSignature = signedXml.CheckSignature(); Console.Out.WriteLine("signature is {0}", checkSignature ? "valid" : "invalid!!"); return true; }
internal bool VerifyLicense(XmlDocument document, string publicKeyString) { bool valid = false; try { // // Load license file into XmlDocument // XmlDocument doc = new XmlDocument(); // doc.Load(signedLicense); // // Get the public key from instance // Stream publicKey // = type.Assembly.GetManifestResourceStream(type.Assembly.GetName().Name + ".LicensePK.gpub"); // Read in the public key RSA signingKey = new RSACryptoServiceProvider(); signingKey.FromXmlString(publicKeyString); //keyPair.Close(); // Load Signature Element SignedXml verifier = new SignedXml(document); verifier.LoadXml(document.GetElementsByTagName("Signature")[0] as XmlElement); // Validate license. if ( verifier.CheckSignature(signingKey) ) { valid = true; } else { valid = false; } } catch { valid = false; } return valid; }
// This assumes signing cert is embedded in the signature private void readSignaturesAndCertificates(SamlResponse response) { var element = find(Signature, "http://www.w3.org/2000/09/xmldsig#"); if (element == null) { response.Signed = SignatureStatus.NotSigned; return; } var signedXml = new SignedXml(_document); signedXml.LoadXml(element); response.Signed = signedXml.CheckSignature() ? SignatureStatus.Signed : SignatureStatus.InvalidSignature; response.Certificates = signedXml .KeyInfo.OfType<KeyInfoX509Data>() .SelectMany(x => { return x.Certificates.OfType<X509Certificate2>() .Select(cert => new X509CertificateWrapper(cert)); }); }
private static void CheckSignedXml() { X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.cer"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(".\\certificates\\samlresponse_sample.XML"); XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable); ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); ns.AddNamespace("x", "http://www.w3.org/2000/09/xmldsig#"); XmlElement signatureElem = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("//x:Signature", ns); //SignedXml signedXml = new SignedXml((XmlElement)xmlDoc.DocumentElement); SignedXml signedXml = new SignedXml((XmlElement)signatureElem.ParentNode); signedXml.LoadXml(signatureElem); Console.WriteLine(signedXml.CheckSignature(certificate, true)); }
public static bool VerifySignature(string xml) { if (xml == null) throw new ArgumentNullException("xml"); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); // If there's no signature => return that we are "valid" XmlNode signatureNode = findSignatureElement(doc); if (signatureNode == null) return true; SignedXml signedXml = new SignedXml(doc); signedXml.LoadXml((XmlElement)signatureNode); //var x509Certificates = signedXml.KeyInfo.OfType<KeyInfoX509Data>(); //var certificate = x509Certificates.SelectMany(cert => cert.Certificates.Cast<X509Certificate2>()).FirstOrDefault(); //if (certificate == null) throw new InvalidOperationException("Signature does not contain a X509 certificate public key to verify the signature"); //return signedXml.CheckSignature(certificate, true); return signedXml.CheckSignature(); }
private bool TryGetValidDocument(string licensePublicKey, XmlDocument doc) { using (var rsa = Encryptor.Current.CreateAsymmetrical()) { rsa.FromXmlString(licensePublicKey); var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#"); var signedXml = new SignedXml(doc); var sig = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr); if (sig == null) { Logger.Warn("Could not find this signature node on license:\r\n{0}", License); return false; } signedXml.LoadXml(sig); return signedXml.CheckSignature(rsa.Algorithm); } }
[Category ("NotWorking")] // bug #79483 public void SignedXML_CRLF_Invalid () { X509Certificate2 cert = new X509Certificate2 (_pkcs12, "mono"); XmlDocument doc = new XmlDocument (); doc.LoadXml (string.Format (CultureInfo.InvariantCulture, "<person>{0}" + " <birthplace>Brussels</birthplace>{0}" + "<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=\"\">" + "<Transforms>" + "<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" />" + "</Transforms>" + "<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" />" + "<DigestValue>IKbfdK2/DMfXyezCf5QggVCXfk8=</DigestValue>" + "</Reference>" + "</SignedInfo>" + "<SignatureValue>" + "JuSd68PyARsZqGKSo5xX5yYHDuu6whHEhoXqxxFmGeEdvkKY2bgroWJ1ZTGHGr" + "VI7mtG3h0w1ibOKdltm9j4lZaZWo87CAJiJ2syeLbMyIVSw6OyZEsiFF/VqLKK" + "4T4AO6q7HYsC55zJrOvL1j9IIr8zBnJfvBdKckf0lczYbXc=" + "</SignatureValue>" + "<KeyInfo>" + "<X509Data>" + "<X509Certificate>" + "MIIBozCCAQygAwIBAgIQH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K+xhFhiYD5Q1NiGhD4oDIVJPwKmZH4L3YP96iSh6RdtO27V05ET/X5" + "yWMKdeIsq6r9jXXv7NaWTmvNfMLKLNgEBCJ00+wN0u4xHUC7yCJc0KNQ3fjDLU" + "AT1oaVjWI=" + "</X509Certificate>" + "</X509Data>" + "</KeyInfo>" + "</Signature>" + "</person>", "\r\n")); SignedXml signedXml = new SignedXml (doc); XmlNodeList nodeList = doc.GetElementsByTagName ("Signature"); signedXml.LoadXml ((XmlElement) nodeList [0]); Assert.IsTrue (!signedXml.CheckSignature (), "#2"); }
public void CheckSignatureEmpty () { SignedXml sx = new SignedXml (); Assert.IsTrue (!sx.CheckSignature ()); }
public void CheckSignatureEmptySafe () { SignedXml sx; KeyInfoClause kic; KeyInfo ki; // empty keyinfo passes... sx = new SignedXml (); sx.KeyInfo = new KeyInfo (); Assert.IsTrue (!sx.CheckSignature ()); // with empty KeyInfoName kic = new KeyInfoName (); ki = new KeyInfo (); ki.AddClause (kic); sx.KeyInfo = ki; Assert.IsTrue (!sx.CheckSignature ()); }