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); }
/// <summary> /// Gets the signature from an XmlDocument. /// </summary> /// <param name="xmlDocument">The source XmlDocument.</param> /// <returns>A SignedXml object representing the signature.</returns> private static SignedXml ExtractSignature(XmlDocument xmlDocument) { var signedXml = new SignedXml(xmlDocument); XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); signedXml.LoadXml((XmlElement)nodeList[0]); return signedXml; }
// 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 void LoadXmlMalformed1 () { SignedXml s = new SignedXml (); XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root/>"); s.LoadXml (doc.DocumentElement); }
/// <summary> /// Checks if an xml element is signed by the given certificate, through /// a contained enveloped signature. /// </summary> /// <param name="xmlElement">Xml Element that should be signed</param> /// <param name="signingKeys">Signing keys to test, one should validate.</param> /// <param name="validateCertificate">Should the certificate be validated too?</param> /// <returns>True on correct signature, false on missing signature</returns> /// <exception cref="InvalidSignatureException">If the data has /// been tampered with or is not valid according to the SAML spec.</exception> public static bool IsSignedByAny( this XmlElement xmlElement, IEnumerable<SecurityKeyIdentifierClause> signingKeys, bool validateCertificate) { if (xmlElement == null) { throw new ArgumentNullException(nameof(xmlElement)); } var signedXml = new SignedXml(xmlElement); var signatureElement = xmlElement["Signature", SignedXml.XmlDsigNamespaceUrl]; if (signatureElement == null) { return false; } signedXml.LoadXml(signatureElement); ValidateSignedInfo(signedXml, xmlElement); VerifySignature(signingKeys, signedXml, signatureElement, validateCertificate); return true; }
public void LoadXmlMalformed2 () { SignedXml s = new SignedXml (); XmlDocument doc = new XmlDocument (); doc.LoadXml ("<ds:Signature xmlns:ds='http://www.w3.org/2000/09/xmldsig#'><foo/><bar/></ds:Signature>"); s.LoadXml (doc.DocumentElement); }
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; }
/// <summary> /// Creates a chain of X509Certificates given the provided XML-DSig. /// </summary> /// <param name="xmlDoc">XML-Dsig used to create the chain.</param> /// <returns>Chain of X509Certificates</returns> public static List<X509Certificate2> CertificateChain(string xmlDoc) { if (xmlDoc == null) { throw new ArgumentException("xmlDoc was null"); } var xml = XmlUtil.LoadXml(xmlDoc); var xmlNamespaces = new XmlNamespaceManager(xml.NameTable); xmlNamespaces.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); var sigElement = (XmlElement)xml.SelectSingleNode("//ds:Signature[1]", xmlNamespaces); var signature = new SignedXml(xml); signature.LoadXml(sigElement); var certificates = new List<X509Certificate2>(); foreach (var clause in signature.KeyInfo) { if (!(clause is KeyInfoX509Data)) continue; foreach (var x509Cert in ((KeyInfoX509Data)clause).Certificates) { certificates.Add((X509Certificate2)x509Cert); } } return certificates; }
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 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 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 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"); }
/// <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 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()); }
public static void GetTiffInfo(string XmlSigFileName) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // Load the passed XML file into the document. xmlDocument.Load(XmlSigFileName); // Create a new SignedXMl object. SignedXml signedXml = new SignedXml(); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. IEnumerator enumerator = signedXml.KeyInfo.GetEnumerator(); X509Certificate2 cert = new X509Certificate2(); while (enumerator.MoveNext()) { if (enumerator.Current is KeyInfoX509Data) { var current = (KeyInfoX509Data)enumerator.Current; if (current.Certificates.Count != 0) { cert = (X509Certificate2) current.Certificates[0]; break; } } } Console.WriteLine("Emisor: " + cert.Issuer); Console.WriteLine("Subject: " + cert.Subject); Console.WriteLine("Serial: " + cert.SerialNumber); Console.WriteLine("Thumbprint: " + cert.Thumbprint); Console.WriteLine("Valido desde: " + cert.NotBefore); Console.WriteLine("VĂ¡lido hasta: " + cert.NotAfter); }
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; }
/// <summary>Determines whether saml response is valid.</summary> public bool IsValid() { if (!_isInitialized) return false; bool status = false; var manager = new XmlNamespaceManager(_xmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = _xmlDoc.SelectNodes("//ds:Signature", manager); if (nodeList == null) return false; var signedXml = new SignedXml(_xmlDoc); foreach (XmlNode node in nodeList) { signedXml.LoadXml((XmlElement)node); status = signedXml.CheckSignature(_certificate, true); if (!status) return false; } return status; }
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; }