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(); }
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]); return signedXml.CheckSignature(certificate.cert, true); }
private bool CheckSignature(string xml, string publicKey) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(xml); SignedXml signedXml = new SignedXml(xmlDoc); XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature"); signedXml.LoadXml((XmlElement)nodeList[0]); var keyRSA = new RSACryptoServiceProvider(); keyRSA.FromXmlString(publicKey); if (publicKey != null) { return(signedXml.CheckSignature(keyRSA)); } return(false); }
/// <summary> /// Validates the X509 certificate signature. /// </summary> /// <param name="xmlDoc">The XML document.</param> /// <param name="options">The options.</param> /// <returns></returns> public bool ValidateX509CertificateSignature(XmlDocument xmlDoc, Saml2Options options) { XmlNodeList XMLSignatures = xmlDoc.GetElementsByTagName(Saml2Constants.Parameters.Signature, Saml2Constants.Namespaces.DsNamespace); if ((options.RequireMessageSigned || options.WantAssertionsSigned) && XMLSignatures.Count == 0) { return(false); } var signedXmlDoc = new SignedXml(xmlDoc); signedXmlDoc.LoadXml((XmlElement)XMLSignatures[0]); //IDP might have multiple signing certs. Get the correct one and check it. KeyInfoX509Data x509data = signedXmlDoc.Signature.KeyInfo.OfType <KeyInfoX509Data>().First(); X509Certificate2 cert = (X509Certificate2)x509data.Certificates[0]; string serialNumber = cert.SerialNumber; var k = signedXmlDoc.Signature; return(signedXmlDoc.CheckSignature(GetIdentityProviderCertficate(options, serialNumber), options.VerifySignatureOnly)); }
/// <summary> /// Verifies the signature of the assertion contained in the document given as parameter. /// </summary> private static bool VerifySignature(XmlDocument assertion) { SignedXml signedXml = new SignedXml(assertion.DocumentElement); XmlNodeList nodeList = assertion.GetElementsByTagName(Signature.ELEMENT_NAME, Saml20Constants.XMLDSIG); signedXml.LoadXml((XmlElement)nodeList[0]); Assert.IsNotNull(signedXml.Signature); // Check the signature and return the result. /* * AsymmetricAlgorithm key; * bool useEmbeddedKey = signedXml.CheckSignatureReturningKey(out key); * if (!useEmbeddedKey) * return false; * * return signedXml.CheckSignature(key); */ return(signedXml.CheckSignature()); }
/// <summary> /// verified the xml signature with the help of x.509 certificate. /// </summary> /// <param name="xmlDoc">XML document to be verified</param> /// <param name="key"> Certificate's subject</param> /// <returns>true or false</returns> public static bool IsXmlSignValid(XmlDocument xmlDoc, string key) { CryptoConfig.AddAlgorithm(typeof(Security.Cryptography.RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams); // loading the key string csp.FromXmlString(key); xmlDoc.PreserveWhitespace = true; SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; signedXml.SigningKey = csp; // Create a reference to be signed. Reference reference = new Reference(string.Empty); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(false); reference.AddTransform(env); signedXml.AddReference(reference); // Find the "Signature" node and create a new XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature"); // Load the first <signature> node. signedXml.LoadXml((XmlElement)nodeList[0]); return(signedXml.CheckSignature(csp)); }
/// <summary>Überprüft die Signatur der Serverresponse.</summary> private void verifyAttachedSignature(byte[] responseData) { var document = new XmlDocument { PreserveWhitespace = true }; using (var msResponseData = new MemoryStream(responseData)) { using (var reader = new StreamReader(msResponseData, Encoding.UTF8)) document.Load(reader); } var cspParams = new CspParameters { KeyContainerName = "XML_DSIG_RSA_KEY" }; var rsaKey = new RSACryptoServiceProvider(cspParams); rsaKey.FromXmlString( "<RSAKeyValue><Modulus>ww0BFd1ejrwZDCXbRVop9soKLx+LMYlhwNFZEnu41Ahew+bZq/MwW2ENduFe6dDYNl9oqNMbxXZrW6wg9htw7ctFgjorxbmMW4Z4XW2DgKGqZsGJD8AxI6r6y/4jGINLaF/dJDW5kJD9JLkY4L8OSHaVDtFnbBK+50eyrHBGVl7/zSAueW4TVNz5tosPoery2UfhR+162KdJ63vN+E9hkMNTuS91dCQGp3BPGZSuvsMXFtgMSC1D0WbZMQJzesuR2OaKE80cX4miKH+BNte1TVg+kkKfTYBePNprF+cJwJkWaf0Ie5eP2wMNPRDa4fLuYiFnhLJdlQcCcIToFSfk8w==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"); var signedXml = new SignedXml(document); XmlNodeList nodeList = document.GetElementsByTagName("Signature"); if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } signedXml.LoadXml((XmlElement)nodeList[0]); if (!signedXml.CheckSignature(rsaKey)) { throw new Exception("Die Signatur ist ungültig."); } }
private static bool CheckSignature(XmlElement signedRootElement, AsymmetricAlgorithm idpKey, X509Certificate2 certificate) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(signedRootElement.OuterXml); var signature = xmlDocument.GetElementsByTagName("ds:Signature")[0] as XmlElement; if (signature == null) { return(false); } var signedXml = new SignedXml(xmlDocument); signedXml.LoadXml(signature); var signedRootElementId = "#" + signedRootElement.GetAttribute("ID"); var reference = signedXml.SignedInfo.References.Cast <Reference>().FirstOrDefault(); if (signedXml.SignedInfo.References.Count != 1 || reference.Uri != signedRootElementId) { return(false); } foreach (Transform transform in reference.TransformChain) { if (!allowedTransforms.Contains(transform.Algorithm)) { return(false); } } return(signedXml.CheckSignature(idpKey)); }
private static bool smethod_1(Stream A_0, int A_1) { int num = 11; long position = A_0.Position; A_0.Position = 0L; XmlDocument document = new XmlDocument { PreserveWhitespace = true }; document.Load(A_0); XmlNodeList elementsByTagName = document.GetElementsByTagName(BookmarkStart.b("戰娲刴夶堸伺䠼䴾⑀", 11)); if (elementsByTagName.Count <= 0) { return(false); } SignedXml xml = new SignedXml(); xml.LoadXml((XmlElement)elementsByTagName[A_1]); int index = 0; while (index < xml.SignedInfo.References.Count) { Reference reference = (Reference)xml.SignedInfo.References[index]; if (!reference.Uri.StartsWith(BookmarkStart.b("ሰ", num))) { xml.SignedInfo.References.RemoveAt(index); } else { index++; } } A_0.Position = position; return(xml.CheckSignature()); }
/// <summary> /// Verify the signature of an XML file against an asymmetric algorithm and return the result. /// </summary> /// <param name="doc">signed XML document</param> /// <param name="certificate">certificate</param> /// <returns>boolean, true if signature is valid, false otherwise</returns> public static bool Verify(XmlDocument doc, X509Certificate2 certificate) { // Check arguments. if (doc == null) { throw new ArgumentNullException("doc"); } if (certificate == null) { throw new ArgumentNullException("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."); } // This example only supports one signature for the entire XML document. // Throw an exception if more than one signature was found. 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(certificate, true)); }
public static SamlResponseResult ValidateAndGetUserIDResponseDoc(XmlDocument xmlDoc) { SamlResponseResult result = new SamlResponseResult(); xmlDoc.NullCheck("xmlDoc"); string userID = string.Empty; 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); if (signatureElem != null) { XmlElement assertionNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Assertion", ns); if (assertionNode != null) { SignedXml signedXml = new SignedXml(assertionNode); signedXml.LoadXml(signatureElem); X509Certificate2 certificate = GetEmbededPublicCertificate(); result.ValidateResult = signedXml.CheckSignature(certificate, true); result.UserID = assertionNode.GetSingleNodeText("saml:Subject/saml:NameID", ns); result.ReturnUrl = assertionNode.GetSingleNodeText("saml:AttributeStatement/saml:Attribute[@Name='source']/saml:AttributeValue", ns); } } return(result); }
// 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"); } // Add the namespace. XmlNamespaceManager nsmgr = new XmlNamespaceManager(Doc.NameTable); nsmgr.AddNamespace("ss", "http://www.w3.org/2000/09/xmldsig#"); XmlNode root = Doc.DocumentElement; XmlNodeList nodeList = root.SelectNodes("/*/ss:Signature", nsmgr); // fail if no signature was found. if (nodeList.Count != 1) { return(false); } // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(Doc); // Load the first <signature> node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return(signedXml.CheckSignature(Key)); }
// 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."); } // This example only supports one signature for // the entire XML document. Throw an exception // if more than one signature was found. if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } // Load the first node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return(signedXml.CheckSignature(Key)); }
static void Symmetric(string filename, byte[] key) { string shortName = Path.GetFileName(filename); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; XmlTextReader xtr = new XmlTextReader(GetReader(filename)); XmlValidatingReader xvr = new XmlValidatingReader(xtr); xtr.Normalization = true; doc.Load(xvr); try { XmlNodeList nodeList = doc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement signature = (XmlElement)nodeList [0]; SignedXml s = new SignedXml(); s.LoadXml(signature); HMACSHA1 mac = new HMACSHA1(key); if (s.CheckSignature(mac)) { Console.WriteLine("valid {0}", shortName); valid++; } else { Console.WriteLine("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine("EXCEPTION " + shortName + " " + ex); error++; } }
// 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) { return(false); } if (nodeList.Count >= 2) { return(false); } // Load the first node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return(signedXml.CheckSignature(Key)); }
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 bool VerifyXmlDocument(string publicKey, string licenseContent) { RSA key = RSA.Create(); key.FromXmlString(publicKey); XmlDocument doc = new XmlDocument(); doc.LoadXml(licenseContent); SignedXml sxml = new SignedXml(doc); try { // Find signature node XmlNode sig = doc.GetElementsByTagName("Signature")[0]; sxml.LoadXml((XmlElement)sig); } catch (Exception ex) { // Not signed! return(false); } return(sxml.CheckSignature(key)); }
private bool VerifyXmlFile(string LicenseXml) { try { XmlDocument xmlDocument = new XmlDocument(); LicenseXml = LicenseXml.Replace("<", "<").Replace(">", ">"); // Load the passed XML file into the document. xmlDocument.LoadXml(LicenseXml); _traceWriterLog.Info("Loaded XML Successfully"); SignedXml signedXml = new SignedXml(xmlDocument); XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. var Key = GetRSAKeyUsingPublicKey(); return(signedXml.CheckSignature(Key)); } catch (System.Exception) { throw; } }
private 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."); } 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 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> /// 验证 XML 文档的数字签名 /// </summary> /// <param name="Doc"></param> /// <param name="Key"></param> /// <returns></returns> public static Boolean VerifyXml(XmlDocument Doc, RSA Key) { // Check arguments. if (Doc == null) { throw new ArgumentException("Doc"); } if (Key == null) { throw new ArgumentException("Key"); } // 创建一个新的 SignedXml 对象,并将 XmlDocument 对象传递给它。 SignedXml signedXml = new SignedXml(Doc); // 找到 <signature> 元素,并创建新的 XmlNodeList 对象。 XmlNodeList nodeList = Doc.GetElementsByTagName("Signature"); // 如果没有签名,那么抛异常. if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } // 如果有多个签名,那么也抛异常. if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } // 将第一个 <signature> 元素的 XML 加载到 SignedXml 对象中。 signedXml.LoadXml((XmlElement)nodeList[0]); // 使用 CheckSignature 方法和 RSA 公钥检查签名。 此方法将返回指示成功或失败的布尔值。 return(signedXml.CheckSignature(Key)); }
protected override SecurityToken VerifySignature(SignedXml signedXml, bool isPrimarySignature, SecurityHeaderTokenResolver resolver, object signatureTarget, string id) { SecurityKeyIdentifier securityKeyIdentifier = null; string keyInfoString = signedXml.Signature.KeyInfo.GetXml().OuterXml; using (var strReader = new StringReader(keyInfoString)) { XmlReader xmlReader = XmlReader.Create(strReader); securityKeyIdentifier = StandardsManager.SecurityTokenSerializer.ReadKeyIdentifier(xmlReader); } if (securityKeyIdentifier == null) { throw new Exception("SecurityKeyIdentifier is missing"); } SecurityToken token = ResolveSignatureToken(securityKeyIdentifier, resolver, isPrimarySignature); if (isPrimarySignature) { RecordSignatureToken(token); } ReadOnlyCollection <SecurityKey> keys = token.SecurityKeys; SecurityKey securityKey = (keys != null && keys.Count > 0) ? keys[0] : null; if (securityKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.Format(SR.UnableToCreateICryptoFromTokenForSignatureVerification, token))); } // signedXml.SigningKey = securityKey; // signedXml.StartSignatureVerification(securityKey); // StandardSignedInfo signedInfo = (StandardSignedInfo)signedXml.Signature.SignedInfo; // ValidateDigestsOfTargetsInSecurityHeader(signedInfo, this.Timestamp, isPrimarySignature, signatureTarget, id); if (!isPrimarySignature) { //TODO securityKey is AsymmetricSecurityKey //if ((!this.RequireMessageProtection) && (securityKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None)) //{ // // For Transport Security using Asymmetric Keys verify that // // the 'To' header is signed. // int headerIndex = this.Message.Headers.FindHeader(XD.AddressingDictionary.To.Value, this.Message.Version.Addressing.Namespace); // if (headerIndex == -1) // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageMissingToHeader))); // XmlDictionaryReader toHeaderReader = this.Message.Headers.GetReaderAtHeader(headerIndex); // id = toHeaderReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); // // DevDiv:938534 - We added a flag that allow unsigned headers. If this is set, we do not throw an Exception but move on to CompleteSignatureVerification() // if (LocalAppContextSwitches.AllowUnsignedToHeader) // { // // The lack of an id indicates that the sender did not wish to sign the header. We can safely assume that null indicates this header is not signed. // // If id is not null, then we need to validate the Digest and ensure signature is valid. The exception is thrown deeper in the System.IdentityModel stack. // if (id != null) // { // signedXml.EnsureDigestValidityIfIdMatches(id, toHeaderReader); // } // } // else // { // // default behavior for all platforms // if (id == null) // { // // // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnsignedToHeaderInTransportSecuredMessage))); // } // signedXml.EnsureDigestValidity(id, toHeaderReader); // } //} // signedXml.CompleteSignatureVerification(); SecurityAlgorithmSuite suite = AlgorithmSuite; AlgorithmSuite.EnsureAcceptableSignatureKeySize(securityKey, token); AlgorithmSuite.EnsureAcceptableSignatureAlgorithm(securityKey, signedXml.Signature.SignedInfo.SignatureMethod); string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm; suite.GetSignatureAlgorithmAndKey(token, out string signatureAlgorithm, out SecurityKey signatureKey, out XmlDictionaryString signatureAlgorithmDictionaryString); GetSigningAlgorithm(signatureKey, signatureAlgorithm, out _signingKey, out AsymmetricAlgorithm asymmetricAlgorithm); if (_signingKey != null) { if (!signedXml.CheckSignature(_signingKey)) { throw new Exception("Signature not valid."); } } else { if (!signedXml.CheckSignature(asymmetricAlgorithm)) { throw new Exception("Signature not valid."); } } } // this.pendingSignature = signedXml; //if (TD.SignatureVerificationSuccessIsEnabled()) //{ // TD.SignatureVerificationSuccess(this.EventTraceActivity); //} return(token); }
static void Symmetric (string filename, byte[] key) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.Load (xvr); try { XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement signature = (XmlElement) nodeList [0]; SignedXml s = new SignedXml (); s.LoadXml (signature); HMACSHA1 mac = new HMACSHA1 (key); if (s.CheckSignature (mac)) { Console.WriteLine ("valid {0}", shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }
private X509Certificate2 FindMatchedCertificate(SignedXml signedXml, IEnumerable <X509Certificate2> candidates) { return(candidates.FirstOrDefault(candidate => signedXml.CheckSignature(candidate, true))); }
static bool ValidateXml(XmlDocument receipt, X509Certificate2 certificate) { // Create the signed XML object. SignedXml sxml = new SignedXml(receipt); // Get the XML Signature node and load it into the signed XML object. XmlNode dsig = receipt.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0]; if (dsig == null) { // If signature is not found return false System.Console.WriteLine("Signature not found."); return false; } sxml.LoadXml((XmlElement)dsig); // Check the signature bool isValid = sxml.CheckSignature(certificate, true); FieldInfo field = sxml.GetType().GetField("m_signature", BindingFlags.NonPublic | BindingFlags.Instance); var sig = (Signature)field.GetValue(sxml); var _ref = (Reference)sig.SignedInfo.References[0]; //var pre = Type.GetType("System.Security.Cryptography.Xml.Utils").GetMethod("PreProcessDocumentInput"); //pre.Invoke(null, new[] { }); var enveloped = (XmlDsigEnvelopedSignatureTransform)_ref.TransformChain[0]; enveloped.LoadInput(receipt); var outputstream = enveloped.GetOutput(); var securityUrl = receipt.BaseURI; var resolver = new XmlSecureResolver(new XmlUrlResolver(), securityUrl); //TransformToOctetStream(Stream input, XmlResolver resolver, string baseUri) MethodInfo trans = _ref.TransformChain.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)[2]; var stream = trans.Invoke(_ref.TransformChain, new object[] {receipt, resolver, securityUrl}); var canontype = sig.GetType().Assembly.GetType("System.Security.Cryptography.Xml.CanonicalXml"); var foo = Activator.CreateInstance(canontype, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] {receipt, resolver}, null); MethodInfo method = _ref.GetType().GetMethod("CalculateHashValue", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo refs = sig.GetType().GetField("m_referencedItems", BindingFlags.NonPublic | BindingFlags.Instance); var refs1 = refs.GetValue(sig); var res = method.Invoke(_ref, new [] {receipt, refs1}); var str = Convert.ToBase64String((byte[])res); return isValid; }
// See: https://msdn.microsoft.com/en-us/library/ms148731(v=vs.110).aspx // See also: https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-verify-the-digital-signatures-of-xml-documents // The code differs from the MSDN sample as it checks certificates against the root store instead. private bool IsSigned(string path, out X509Certificate2 signingCertificate) { signingCertificate = null; var xmlDoc = new XmlDocument() { PreserveWhitespace = true }; xmlDoc.Load(path); XmlNodeList signatureNodes = xmlDoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl); Log.WriteMessage(LogVerbosity.Diagnostic, SignCheckResources.XmlSignatureNodes, signatureNodes.Count); if (signatureNodes.Count == 0) { return(false); } var signedXml = new SignedXml(xmlDoc); signedXml.LoadXml((XmlElement)signatureNodes[0]); if (signedXml.Signature.KeyInfo.OfType <KeyInfoX509Data>().Count() == 0) { return(false); } ArrayList certificates = signedXml.Signature.KeyInfo.OfType <KeyInfoX509Data>().First().Certificates; foreach (X509Certificate2 certificate in certificates) { if (signedXml.CheckSignature(certificate, verifySignatureOnly: true)) { using (var rootStore = new X509Store(StoreName.Root)) { rootStore.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); using (var chain = new X509Chain(useMachineContext: true)) { chain.Build(certificate); int numberOfChainElements = chain.ChainElements.Count; X509ChainElement rootChainElement = null; X500DistinguishedName subjectDistinguishedName = certificate.SubjectName; // Locate the last element in the chain as that should be the root, otherwise use the certificate we have // and try to match that against a root certificate. if (numberOfChainElements > 0) { rootChainElement = chain.ChainElements[numberOfChainElements - 1]; subjectDistinguishedName = rootChainElement.Certificate.SubjectName; } X509Certificate2Collection rootCertificates = rootStore.Certificates; X509Certificate2Collection matchingRootCertificates = rootCertificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectDistinguishedName.Name, validOnly: true); if (matchingRootCertificates.Count > 0) { signingCertificate = matchingRootCertificates[0]; } return(true); } } } } return(false); }
/// <summary> /// 0 indicate expired, -1 indicate regist version /// </summary> /// <param name="licenseFile"></param> /// <returns></returns> internal static DateInfo GetLeftDay(string licenseFile) { // Get the XML content from the embedded XML public key. Stream s = null; string xmlkey = xmlKey; DateInfo dateInfo = new DateInfo(); dateInfo.leftDays = 0; // Create an RSA crypto service provider from the embedded // XML document resource (the public key). CspParameters parms = new CspParameters(1); // PROV_RSA_FULL parms.Flags = CspProviderFlags.UseMachineKeyStore; // Use Machine store foreach (var key in GetKeys(1)) { parms.KeyContainerName = key; } parms.KeyNumber = 2; // AT_SIGNATURE RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parms); // Load the signed XML license file. XmlDocument xmldoc = new XmlDocument(); Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { return(dateInfo); } FileStream licenseStream = File.Open(licenseFile, FileMode.Open); if (licenseStream == null) { return(dateInfo); } byte[] licenseData = new byte[licenseStream.Length]; licenseStream.Read(licenseData, 0, licenseData.Length); string encryptString = Encoding.ASCII.GetString(licenseData); foreach (var key in GetKeys(0)) { foreach (var key1 in DecryptDES(encryptString, key)) { encryptString = key1; } } StringReader sr = new StringReader(encryptString); xmldoc.Load(sr); licenseStream.Close(); // Create the signed XML object. SignedXml sxml = new SignedXml(xmldoc); try { // Get the XML Signature node and load it into the signed XML object. XmlNode dsig = xmldoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0]; sxml.LoadXml((XmlElement)dsig); } catch { Console.Error.WriteLine("Error: no signature found."); return(dateInfo); } // Verify the signature. if (sxml.CheckSignature(csp)) { XmlNode cpuNode = xmldoc.GetElementsByTagName("CPUID")[0]; string currentCPUInfo = string.Empty; foreach (var key in GetKeys(2)) { foreach (var key1 in EncryptDES(Hardware.GetCpuID(), key)) { currentCPUInfo = key1; } } foreach (string value in getMd5(currentCPUInfo)) { if (cpuNode.InnerText == value.Trim()) { dateInfo.leftDays = -1; return(dateInfo); } } } XmlNode trialDaysNode = xmldoc.GetElementsByTagName("TrialDays")[0]; XmlNode startDateNode = xmldoc.GetElementsByTagName("StartDate")[0]; dateInfo.startDate = Convert.ToDateTime(startDateNode.InnerText); dateInfo.leftDays = Convert.ToInt32(trialDaysNode.InnerText); return(dateInfo); }
public void XmlDsigXPathWithNamespacesTransformExplicitNamespaceRoundTripTest() { RSACryptoServiceProvider key = new RSACryptoServiceProvider(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(RawXml); SignedXml signer = new SignedXml(doc); Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); Dictionary <string, string> explicitNamespaces = new Dictionary <string, string>(); explicitNamespaces["clrsec"] = "http://www.codeplex.com/clrsecurity"; reference.AddTransform(new XmlDsigXPathWithNamespacesTransform("ancestor-or-self::node()[@clrsec:sign='true']", explicitNamespaces)); signer.AddReference(reference); signer.SigningKey = key; signer.ComputeSignature(); XmlElement signature = signer.GetXml(); doc.DocumentElement.AppendChild(signature); // Now try to verify - this will use the built in XPath transform to do the verification, since // we have to modify machine.config to use custom transforms. SignedXml verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // We should also be able to verify the signature after modifying the unsignedNode node, // since the XPath should have excluded it. XmlElement unsigned = doc.GetElementsByTagName("unsignedNode")[0] as XmlElement; XmlAttribute unsignedAttr = doc.CreateAttribute("state"); unsignedAttr.Value = "unsigned"; unsigned.Attributes.Append(unsignedAttr); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // Modifying the signedNode should also be allowed, since it is not using a clrsec:sign attribute XmlElement signed = doc.GetElementsByTagName("signedNode")[0] as XmlElement; XmlAttribute unsignedAttr2 = doc.CreateAttribute("state"); unsignedAttr2.Value = "unsigned"; unsigned.Attributes.Append(unsignedAttr2); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // However, we should not be able to modify the signedNode node XmlElement signedNamespace = doc.GetElementsByTagName("signedNamespaceNode", "http://www.codeplex.com/clrsecurity")[0] as XmlElement; XmlAttribute signedAttr = doc.CreateAttribute("state"); signedAttr.Value = "signed"; signedNamespace.Attributes.Append(signedAttr); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsFalse(verifier.CheckSignature(key)); }
/// <summary> /// Verifies the signature contained in the passed signed xml /// </summary> /// <param name="signedXml">The signed xml to verify</param> /// <param name="cert">The certificate to check against</param> /// <returns>true if the signature is verified, false otherwise</returns> private bool VerifySignature(SignedXml signedXml, X509Certificate2 cert) { return(signedXml.CheckSignature(cert, true)); }
private static AuthRequestSubset GetSPMetadataByFileName(string spMetaDataFilePath) { if (!File.Exists(spMetaDataFilePath)) { throw new Exception($"spMetaDataFilePath={spMetaDataFilePath} does not exist"); } { //const string METADATA = "urn:oasis:names:tc:SAML:2.0:metadata"; const string XMLDSIG = "http://www.w3.org/2000/09/xmldsig#"; const string METADATA = "urn:oasis:names:tc:SAML:2.0:metadata"; XmlDocument doc = new XmlDocument(); // load document { doc.PreserveWhitespace = true; doc.Load(spMetaDataFilePath); if (!doc.PreserveWhitespace) { throw new InvalidOperationException( "The XmlDocument must have its \"PreserveWhitespace\" property set to true when a signed document is loaded."); } } // get service provider id string spId; { XmlNodeList nodeList = doc.GetElementsByTagName("EntityDescriptor", METADATA); if (nodeList.Count == 0) { throw new Exception($"EntityDescriptor in ${spMetaDataFilePath} not found"); } XmlNode entityDescriptorNode = nodeList[0]; spId = entityDescriptorNode.Attributes["entityID"]?.InnerText; //spId = BusinessLogicUtil.GetMd5HashedSPEntityId(spId); } // Get the signedXml SignedXml signedXml; { signedXml = new SignedXml(doc.DocumentElement); XmlNodeList nodeList = doc.GetElementsByTagName("Signature", XMLDSIG); if (nodeList.Count == 0) { throw new InvalidOperationException("The XmlDocument does not contain a signature."); } signedXml.LoadXml((XmlElement)nodeList[0]); } // Get the public key required to verify the signing X509Certificate2 x509Certificate; { XmlNodeList nodeList = doc.GetElementsByTagName("X509Certificate"); if (nodeList.Count == 0) { throw new Exception($"X509Certificate in ${spMetaDataFilePath} not found"); } XmlNode x509CertificateNode = nodeList[0]; string encodedX509Certificate = x509CertificateNode.InnerText; byte[] bytes = Convert.FromBase64String(encodedX509Certificate); x509Certificate = new X509Certificate2(bytes); } // verify signatury AsymmetricAlgorithm key = x509Certificate.PublicKey.Key; if (!signedXml.CheckSignature(key)) { throw new Exception("Signing verification failed"); } return(new AuthRequestSubset(spId, x509Certificate)); } }
/// <summary> /// Verify any XAdES (-BES, -T) signature. /// </summary> /// <remarks> /// Requires the XAdES QualifyingProperties and not the signature, it will resolve the signature itself. /// </remarks> /// <param name="doc">The document for which the </param> /// <param name="xadesProps">The XAdES 1.4.1 QualifyingProperties xml-element</param> /// <returns>The (useful) information of the signature and xades properties</returns> /// <exception cref="ArgumentNullException">When the xades props param is null</exception> /// <exception cref="InvalidXadesException">When the XAdES isn't correctly formatted</exception> /// <exception cref="XadesValidationException">When the signature isn't valid</exception> /// <exception cref="NotSupportedException">When a XAdES or the signature contains unsupported sections</exception> public SignatureInfo Verify(XmlDocument doc, XmlElement xadesProps) { XadesForm form = XadesForm.XadesBes; if (doc == null) { throw new ArgumentNullException("doc", "The doc argument can't be null"); } if (xadesProps == null) { throw new ArgumentNullException("xadesProps", "The xades props argument can't be null"); } //check if we get a valid xades-props //TODO:support QualifyingPropertiesReference if (xadesProps.LocalName != "QualifyingProperties" || xadesProps.NamespaceURI != Extra.XadesTools.NS) { throw new InvalidXadesException("The provider xades properties aren't actually xades properties"); } //Get the corresponding signature of the xades props String targetRef; if (xadesProps.Attributes["Target"] == null) { throw new InvalidXadesException("the XAdES Properties has no Target attribute defined"); } targetRef = xadesProps.Attributes["Target"].Value; if (targetRef == null || !targetRef.StartsWith("#")) { throw new InvalidXadesException("the XAdES Properties has an invalid Target attribute value"); } var signatureNode = (XmlElement)xadesProps.OwnerDocument.SelectSingleNode("//ds:Signature[@Id='" + targetRef.Substring(1) + "']", nsMgr); if (signatureNode == null) { throw new InvalidXadesException("The signature referenced by the XAdES Properties was not found (Target-attribute)"); } //Load the signature var signature = new SignedXml(doc); signature.LoadXml(signatureNode); signature.SafeCanonicalizationMethods.Add(OptionalDeflateTransform.AlgorithmUri); //check if the signature contains a reference to the xades signed props. var xadesRef = new Reference(); var signedPropsIdAttr = (XmlAttribute)xadesProps.SelectSingleNode("./xades:SignedProperties/@Id", nsMgr); if (signedPropsIdAttr == null) { throw new InvalidXadesException("The xades Signed Properties do not have an Id which should be referenced in the signature"); } var xadesRefNode = (XmlElement)signatureNode.SelectSingleNode("./ds:SignedInfo/ds:Reference[@Type='http://uri.etsi.org/01903#SignedProperties']", nsMgr); if (xadesRefNode == null) { throw new InvalidXadesException("The signature referenced by the XAdES Properties does not contain a reference element of te type 'http://uri.etsi.org/01903#SignedProperties'"); } xadesRef.LoadXml(xadesRefNode); if (xadesRef.Uri != ("#" + signedPropsIdAttr.Value)) { throw new InvalidXadesException("The Signed Properties references does not reference the signed properties"); } //Check for illegal transforms in the reference to the xades signed props foreach (Transform t in xadesRef.TransformChain) { if (t.GetType() != typeof(XmlDsigC14NTransform) && t.GetType() != typeof(XmlDsigExcC14NTransform)) { throw new InvalidXadesException(String.Format("The signed property reference does contain a transform that isn't allowed {0}", t.Algorithm)); } } //Get the provided certificates X509Certificate2Collection includedCerts = new X509Certificate2Collection(); IEnumerator keyInfo = signature.Signature.KeyInfo.GetEnumerator(); while (keyInfo.MoveNext()) { KeyInfoClause clause = (KeyInfoClause)keyInfo.Current; if (clause.GetType() == typeof(KeyInfoX509Data)) { KeyInfoX509Data x509 = (KeyInfoX509Data)clause; includedCerts.AddRange((X509Certificate2[])x509.Certificates.ToArray(typeof(X509Certificate2))); } else { throw new NotSupportedException("Only X509Data is supported"); } } if (includedCerts == null || includedCerts.Count == 0) { throw new InvalidXadesException("No certificates where found in the the signature key info"); } //Check if any of the verified certificates is used for the signature bool valid = false; X509Certificate2 signingCert = null; X509Certificate2Enumerator vce = includedCerts.GetEnumerator(); while (!valid && vce.MoveNext()) { signingCert = vce.Current; AsymmetricAlgorithm key = (AsymmetricAlgorithm)signingCert.GetRSAPublicKey() ?? signingCert.GetECDsaPublicKey(); valid = signature.CheckSignature(key); } if (!valid) { throw new XadesValidationException("The signature is invalid"); } //Verify the manifests if present. List <ManifestResult> manifestResults = new List <ManifestResult>(); if (VerifyManifest) { XmlNodeList manifestNodes = signatureNode.SelectNodes("./ds:Object/ds:Manifest", nsMgr); foreach (XmlNode manifestNode in manifestNodes) { if (manifestNode.Attributes["Id"] == null) { throw new NotSupportedException("The Xades library only supports manifests with and Id"); } int manifestRefIndex = 0; String manifestId = manifestNode.Attributes["Id"].Value; XmlNodeList manifestRefNodes = manifestNode.SelectNodes("./ds:Reference", nsMgr); foreach (XmlNode manifestRefNode in manifestRefNodes) { Reference manifestRef = new Reference(); manifestRef.LoadXml((XmlElement)manifestRefNode); byte[] orgValue = manifestRef.DigestValue; SignedXml signatureTmp = new SignedXml(doc); signatureTmp.AddReference(manifestRef); try { signatureTmp.ComputeSignature(new HMACMD5()); //we don't need the signature, so it can be as weak as it wants. } catch (CryptographicException ce) { throw new InvalidXadesException("The the reference " + manifestRefIndex + " of manifest " + manifestNode.Attributes["Id"].Value + " can't be validated", ce); } ManifestResultStatus status; if (orgValue.SequenceEqual(manifestRef.DigestValue)) { status = ManifestResultStatus.Valid; } else { status = ManifestResultStatus.Invalid; } String xpath = String.Format("//ds:Signature[@Id='{0}']/ds:Object/ds:Manifest[@Id='{1}']/ds:Reference[{2}]", targetRef.Substring(1), manifestId, ++manifestRefIndex); manifestResults.Add(new ManifestResult(xpath, status)); } } } //Signing time retrieval DateTimeOffset?signingTime = null; XmlNode signingTimeTxtNode = xadesProps.SelectSingleNode("./xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningTime/text()", nsMgr); if (signingTimeTxtNode != null) { DateTimeOffset signingTimeValue; if (!DateTimeOffset.TryParse(signingTimeTxtNode.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out signingTimeValue)) { throw new InvalidXadesException("Signing time provided in the xades information isn't valid"); } signingTime = signingTimeValue; } //TODO:check for EPES. //check time-stamp XmlNodeList timestamps = xadesProps.SelectNodes("./xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp", nsMgr); if (timestamps != null && timestamps.Count > 0) { form = form | XadesForm.XadesT; foreach (XmlNode timestamp in timestamps) { XmlNode timestampC14NAlgoNode = timestamp.SelectSingleNode("./ds:CanonicalizationMethod/@Algorithm", nsMgr); if (timestampC14NAlgoNode == null) { new InvalidXadesException("Canonicalization method missing in the signature timestamp"); } var signatureValue = (XmlElement)signatureNode.SelectSingleNode("./ds:SignatureValue", nsMgr); if (signatureValue == null) { throw new InvalidXadesException("Can't find the signature value for the signature timestamp"); } var timestampC14NAlgo = (Transform)CryptoConfig.CreateFromName(timestampC14NAlgoNode.Value); if (timestampC14NAlgo == null || timestampC14NAlgo.GetType() != typeof(XmlDsigC14NTransform) && timestampC14NAlgo.GetType() != typeof(XmlDsigExcC14NTransform)) { throw new InvalidXadesException(String.Format("The signature timestamp has a canonicalization method that isn't allowed {0}", timestampC14NAlgoNode.Value)); } //Serialize because the C14N overloads which accepts lists is totally wrong (it C14N's the document) MemoryStream stream = new MemoryStream(); using (var writer = XmlWriter.Create(stream)) { signatureValue.WriteTo(writer); } stream.Seek(0, SeekOrigin.Begin); //Canonicalize the signature value timestampC14NAlgo.LoadInput(stream); var canonicalized = (Stream)timestampC14NAlgo.GetOutput(typeof(Stream)); XmlNode timestampValueTxtNode = timestamp.SelectSingleNode("./xades:EncapsulatedTimeStamp/text()", nsMgr); if (timestampValueTxtNode != null) { //Get the timestamp token TimeStampToken tst = Convert.FromBase64String(timestampValueTxtNode.Value).ToTimeStampToken(); if (!tst.IsMatch(canonicalized)) { throw new XadesValidationException("The timestamp doesn't match the signature value"); } //verify the time-stamp Timestamp ts = tst.Validate(ExtraStore); if (ts.TimestampStatus.Count(x => x.Status != X509ChainStatusFlags.NoError) > 0) { throw new XadesValidationException(String.Format("The timestamp TSA has an invalid status {0}: {1}", ts.TimestampStatus[0].Status, ts.TimestampStatus[0].StatusInformation)); } foreach (ChainElement chainE in ts.CertificateChain.ChainElements) { if (chainE.ChainElementStatus.Count(x => x.Status != X509ChainStatusFlags.NoError) > 0) { throw new XadesValidationException(String.Format("The timestamp TSA chain contains an invalid certificate '{0}' ({1}: {2})", chainE.Certificate.Subject, chainE.ChainElementStatus[0].Status, chainE.ChainElementStatus[0].StatusInformation)); } } //check the timestamp token against the signing time. DateTime tsTime = ts.Time; if (signingTime != null) { DateTime signingTimeUtc = signingTime.Value.UtcDateTime; if (Math.Abs((tsTime - signingTimeUtc).TotalSeconds) > TimestampGracePeriod.TotalSeconds) { throw new XadesValidationException("The signature timestamp it to old with regards to the signing time"); } } else { signingTime = tsTime; } } else { //TODO:support xml timestamps throw new NotSupportedException("Only Encapsulated timestamps are supported"); } } } //check check the chain Chain chain = signingCert.BuildChain(signingTime == null ? DateTime.UtcNow : signingTime.Value.UtcDateTime, includedCerts); if (chain.ChainStatus.Count(x => x.Status != X509ChainStatusFlags.NoError) > 0) { throw new XadesValidationException(String.Format("The signing certificate chain is invalid ({0}: {1})", chain.ChainStatus[0].Status, chain.ChainStatus[0].StatusInformation)); } //Select the correct certificate based on the xades-bes info XmlNodeList signedCerts = xadesProps.SelectNodes("./xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert", nsMgr); //TODO:Support the fact that it is also legal to sign the KeyInfo (G.2.2.1) if (signedCerts.Count == 0) { throw new InvalidXadesException("No signing certificates provided in the xades information"); } //Find certs via signed info, checking with hash. X509Certificate2Collection unsignedChainCerts = new X509Certificate2Collection(chain.ChainElements.Select(c => c.Certificate).ToArray()); foreach (XmlNode signedCert in signedCerts) { XmlNode issuerTxtNode = signedCert.SelectSingleNode("./xades:IssuerSerial/ds:X509IssuerName/text()", nsMgr); if (issuerTxtNode == null) { throw new InvalidXadesException("Xades information does not contain an issuer name for the signing certificate"); } XmlNode serialNumberTxtNode = signedCert.SelectSingleNode("./xades:IssuerSerial/ds:X509SerialNumber/text()", nsMgr); if (serialNumberTxtNode == null) { throw new InvalidXadesException("Xades information does not contain an serial number for the signing certificate"); } X509Certificate2Collection certsSameIssuer = unsignedChainCerts.Find(X509FindType.FindByIssuerDistinguishedName, issuerTxtNode.Value, false); if (certsSameIssuer.Count == 0) { throw new InvalidXadesException(String.Format("Xades provided signed certificate {0} ({1}) can't be found in the chain", serialNumberTxtNode.Value, issuerTxtNode.Value)); } X509Certificate2Collection exactCerts = certsSameIssuer.Find(X509FindType.FindBySerialNumber, serialNumberTxtNode.Value, false); if (exactCerts.Count == 0) { throw new InvalidXadesException(String.Format("Xades provided signed certificate {0} ({1}) can't be found in the chain", serialNumberTxtNode.Value, issuerTxtNode.Value)); } if (exactCerts.Count > 1) { throw new InvalidXadesException(String.Format("Xades provided signed certificate {0} ({1}) can be found more then once in the chain", serialNumberTxtNode.Value, issuerTxtNode.Value)); } XmlNode digestMethodTxtNode = signedCert.SelectSingleNode("./xades:CertDigest/ds:DigestMethod/@Algorithm", nsMgr); if (digestMethodTxtNode == null) { throw new InvalidXadesException("Xades information does not contain the digest method for the signing certificate"); } XmlNode digestValueTxtNode = signedCert.SelectSingleNode("./xades:CertDigest/ds:DigestValue/text()", nsMgr); if (digestValueTxtNode == null) { throw new InvalidXadesException("Xades information does not contain the digest value for the signing certificate"); } HashAlgorithm algo; try { algo = (HashAlgorithm)CryptoConfig.CreateFromName(digestMethodTxtNode.Value); } catch (Exception e) { throw new InvalidXadesException("The provided digest method of the signing certificate in xades isn't valid or isn't supported", e); } String digestValueReal = Convert.ToBase64String(algo.ComputeHash(exactCerts[0].GetRawCertData())); if (digestValueTxtNode.Value != digestValueReal) { throw new XadesValidationException("The certificate of the key info isn't correct according to the certificate info in xades"); } unsignedChainCerts.Remove(exactCerts[0]); } //has the end cert being signed? if (unsignedChainCerts.Contains(signingCert)) { throw new XadesValidationException(String.Format("Signing certificate not part of the signature")); } //TODO::add some kind of warning or option to test for all. return(new SignatureInfo(form, signingCert, signingTime, manifestResults.ToArray())); }
private static Class522 smethod_2( Class522 licenseInfo, Assembly assembly, Attribute0 productAttribute, Enum15 requiredEdition) { string xmlString = "<RSAKeyValue><Modulus>5tmp6YoXLdKEUTC0PvXQmgM9V+jtb2LBV/6nCO8l/4StX9muFDQRSrtJAEH8sXcHu5Fgr7Y00oddMMSwfjXgiAG0b4WMhfF3s2/Cpw9MqFJXVnoeMr8dKHCr2Dp6cue6yCb3rIwjbRCYavYCHFmywBhrfztx6m125PD6TuDYDN0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider(new CspParameters() { Flags = CspProviderFlags.UseMachineKeyStore }); cryptoServiceProvider.FromXmlString(xmlString); XmlDocument license = License.GetLicense(); SignedXml signedXml = new SignedXml(license); try { XmlNode xmlNode = license.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#")[0]; signedXml.LoadXml((XmlElement)xmlNode); } catch (Exception ex) { licenseInfo.Message = "Error: no signature found."; licenseInfo.Exception = ex; return(licenseInfo); } if (signedXml.CheckSignature((AsymmetricAlgorithm)cryptoServiceProvider)) { XmlNodeList elementsByTagName1 = license.GetElementsByTagName("product"); XmlNode xmlNode1 = (XmlNode)null; foreach (XmlNode xmlNode2 in elementsByTagName1) { if (xmlNode2.Attributes["name"].Value == licenseInfo.ProductName) { xmlNode1 = xmlNode2; break; } } if (xmlNode1 == null) { licenseInfo.Message = "Wrong license."; return(licenseInfo); } Version version1 = assembly.GetName().Version; string[] strArray = xmlNode1.Attributes["version"].Value.Split('.'); Version version2 = new Version(strArray[0] == "*" ? (int)byte.MaxValue : int.Parse(strArray[0], (IFormatProvider)CultureInfo.InvariantCulture), strArray[1] == "*" ? (int)byte.MaxValue : int.Parse(strArray[1], (IFormatProvider)CultureInfo.InvariantCulture), strArray[2] == "*" ? (int)byte.MaxValue : int.Parse(strArray[2], (IFormatProvider)CultureInfo.InvariantCulture)); if (version1.CompareTo(version2) > 0) { licenseInfo.Message = "Wrong license version."; return(licenseInfo); } Enum15 enum15 = Enum15.const_0; switch (xmlNode1.Attributes["edition"].Value) { case "basic": enum15 = Enum15.const_1; break; case "standard": enum15 = Enum15.const_2; break; case "professional": enum15 = Enum15.const_3; break; } if (requiredEdition > enum15) { licenseInfo.Message = "Insufficient license edition."; return(licenseInfo); } if (DateTime.Parse(xmlNode1.Attributes["expirationDate"].Value, (IFormatProvider)CultureInfo.InvariantCulture) < productAttribute.ReleaseDate) { licenseInfo.Message = "The license is not valid for this release of " + licenseInfo.ProductName + ", renew your license."; return(licenseInfo); } string str = xmlNode1.Attributes["type"].Value; if (str == "runtime") { licenseInfo.LicensedEdition = enum15; XmlNodeList elementsByTagName2 = license.GetElementsByTagName("licensee"); licenseInfo.Licensee = elementsByTagName2[0].InnerText; return(licenseInfo); } if (str == "trial") { licenseInfo.IsTrial = true; DateTime firstUsedDate; DateTime lastUsedDate; if (Class809.smethod_4(productAttribute, out firstUsedDate, out lastUsedDate)) { DateTime t1 = firstUsedDate.AddDays(31.0); DateTime utcNow = DateTime.UtcNow; if (lastUsedDate.Ticks > utcNow.Ticks) { licenseInfo.Message = "Licence check error."; return(licenseInfo); } Class809.smethod_5(productAttribute, firstUsedDate, utcNow); if (DateTime.Compare(t1, utcNow) >= 0) { licenseInfo.TrialDaysLeft = Math.Max(0, t1.Subtract(utcNow).Days); licenseInfo.LicensedEdition = enum15; return(licenseInfo); } licenseInfo.Message = "Trial period of 30 days expired."; return(licenseInfo); } licenseInfo.TrialDaysLeft = 30; Class809.smethod_5(productAttribute, DateTime.UtcNow, DateTime.UtcNow); licenseInfo.LicensedEdition = enum15; return(licenseInfo); } licenseInfo.Message = "Wrong license type."; return(licenseInfo); } licenseInfo.Message = "Invalid license."; return(licenseInfo); }
// Třída ověří všechny podpisy v dokumentu public bool Verify(XmlDocument doc) { // definice mapování prefixů na jmenné prostory XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); // příznak validnosti podpisu bool validates = false; // vybereme všechny podpisy v dokumentu XmlNodeList signatures = doc.SelectNodes("/*/dsig:Signature", manager); // pokud by v dokumentu nebylani jeden podpis, nemůže být podpis validní if (signatures.Count > 0) validates = true; // postupné ověření všech nalezených podpisů for (int i = 0; i < signatures.Count; i++) { // načtení XML reprezentace podpisu XmlElement signatureElement = (XmlElement)signatures.Item(i); // načtení dokumentu do objektu pro práci s podpisy SignedXml signedDoc = new SignedXml(doc); // nastavení elementu, ve kterém se má kontrolovat podpis signedDoc.LoadXml(signatureElement); // kontrola podpisu if (!signedDoc.CheckSignature()) validates = false; } return validates; }
public static bool eval_a(string A_0, int A_1) { if (true) { } switch (0) { case 0: { IL_16: A_1 = 2; A_0 += eval_bw.eval_a(0); XmlDocument xmlDocument = new XmlDocument(); string text = ""; bool result; try { while (true) { xmlDocument.Load(A_0); SignedXml signedXml = new SignedXml(xmlDocument); XmlNode xmlNode = xmlDocument.GetElementsByTagName(eval_bw.a(), "http://www.w3.org/2000/09/xmldsig#")[0]; signedXml.LoadXml((XmlElement)xmlNode); int num = 7; while (true) { string text2; XmlNode xmlNode2; int num2; TimeSpan timeSpan; switch (num) { case 0: text2 = eval_bw.eval_a(A_1); xmlNode2 = xmlDocument.GetElementsByTagName(text2)[0]; num = 9; continue; case 1: goto IL_162; case 2: goto IL_167; case 3: if (num2 > 0) { num = 4; continue; } goto IL_1E6; case 4: result = true; num = 1; continue; case 5: if (A_1 == 0) { num = 2; continue; } goto IL_1E6; case 6: if (timeSpan.Hours > 22) { num = 10; continue; } goto IL_E4; case 7: if (signedXml.CheckSignature(global::eval_s.bc)) { num = 0; continue; } goto IL_1E6; case 8: goto IL_E4; case 9: if (A_1 != 2) { num = 11; continue; } goto IL_167; case 10: num2++; num = 8; continue; case 11: num = 5; continue; case 12: goto IL_1F2; } break; IL_E4: num = 3; continue; IL_167: text = text2 + " " + xmlNode2.InnerText; DateTime d = DateTime.Parse(text); DateTime now = DateTime.Now; timeSpan = d - now; num2 = timeSpan.Days; num = 6; continue; IL_1E6: num = 12; } } IL_162: return result; IL_1F2: goto IL_35; } catch { goto IL_35; } return result; IL_35: MessageBox.Show(A_0 + " " + text); File.Delete(A_0); return false; } } goto IL_16; }
// Verify the signature of an XML file against an asymetric // algorithm and return the result. public static Boolean VerifyXmlFile(String Name, RSA Key) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // Load the passed XML file into the document. xmlDocument.Load(Name); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(xmlDocument); // 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. return signedXml.CheckSignature(Key); }
// 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."); } // This example only supports one signature for // the entire XML document. Throw an exception // if more than one signature was found. 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 static void TestDummySignatureAlgorithm() { string objectToConstruct = typeof(DummyClass).AssemblyQualifiedName; string xml = $@"<?xml version=""1.0"" encoding=""UTF-8""?> <a><b xmlns:ns1=""http://www.contoso.com/"">X<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315""/><SignatureMethod Algorithm=""{objectToConstruct}""/><Reference URI=""""><Transforms><Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature""/><Transform Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315""/></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""/><DigestValue>ZVZLYkc1BAx+YtaqeYlxanb2cGI=</DigestValue></Reference></SignedInfo><SignatureValue>Kx8xs0of766gimu5girTqiTR5xoiWjN4XMx8uzDDhG70bIqpSzlhh6IA3iI54R5mpqCCPWrJJp85ps4jpQk8RGHe4KMejstbY6YXCfs7LtRPzkNzcoZB3vDbr3ijUSrbMk+0wTaZeyeYs8Z6cOicDIVN6bN6yC/Se5fbzTTCSmg=</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>ww2w+NbXwY/GRBZfFcXqrAM2X+P1NQoU+QEvgLO1izMTB8kvx1i/bodBvHTrKMwAMGEO4kVATA1f1Vf5/lVnbqiCLMJPVRZU6rWKjOGD28T/VRaIGywTV+mC0HvMbe4DlEd3dBwJZLIMUNvOPsj5Ua+l9IS4EoszFNAg6F5Lsyk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo></Signature></b></a>"; var xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(xml); var signatureNode = (XmlElement)xmlDoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0]; SignedXml signedXml = new SignedXml(xmlDoc); signedXml.LoadXml(signatureNode); Assert.Throws <System.Security.Cryptography.CryptographicException>(() => signedXml.CheckSignature()); }
public VerifierResponse VerifyXmlSignature( SignatureType mode, XmlDocument message, string certificateFilePath = null, string certificateThumb = null, string nodeId = null, bool isVerifyCertificateChain = false) { SignedXml signedXml = new SignedXml(message); Signer.Smev2SignedXml smev2SignedXml = null; X509Certificate2 cert = null; bool isCerFile; if ((isCerFile = !string.IsNullOrEmpty(certificateFilePath)) || !string.IsNullOrEmpty(certificateThumb)) { //means we are testing signature on external certificate if (isCerFile) { cert = new X509Certificate2(); try { cert.Import(certificateFilePath); } catch (Exception e) { throw ExceptionFactory.GetException( ExceptionType.CertificateImportException, certificateFilePath, e.Message); } } else { //throws if not found ICertificateProcessor cp = new CertificateProcessor(); cert = cp.SearchCertificateByThumbprint(certificateThumb); } } XmlNodeList signaturesInDoc = message.GetElementsByTagName( "Signature", SignedXml.XmlDsigNamespaceUrl ); var signatures = signaturesInDoc .Cast <XmlElement>() .ToDictionary( (elt) => { XNamespace ns = elt.GetXElement().Name.Namespace; return(elt.GetXElement().Descendants(ns + "Reference").First().Attributes("URI").First() .Value.Replace("#", "")); }, (elt => elt) ); if (!string.IsNullOrEmpty(nodeId) && !signatures.ContainsKey(nodeId)) { throw ExceptionFactory.GetException(ExceptionType.ReferencedSignatureNotFound, nodeId); } if (signaturesInDoc.Count == 0) { throw ExceptionFactory.GetException(ExceptionType.NoSignaturesFound); } switch (mode) { case SignatureType.Smev2BaseDetached: smev2SignedXml = new Signer.Smev2SignedXml(message); try { smev2SignedXml.LoadXml( !string.IsNullOrEmpty(nodeId) ? signatures[nodeId] : signatures["body"]); } catch (Exception e) { throw ExceptionFactory.GetException(ExceptionType.CertificateContentCorrupted, e.Message); } XmlNodeList referenceList = smev2SignedXml.KeyInfo .GetXml() .GetElementsByTagName("Reference", Signer.WsSecurityWsseNamespaceUrl); if (referenceList.Count == 0) { throw ExceptionFactory.GetException(ExceptionType.Smev2CertificateReferenceNotFound); } string binaryTokenReference = ((XmlElement)referenceList[0]).GetAttribute("URI"); if (string.IsNullOrEmpty(binaryTokenReference) || binaryTokenReference[0] != '#') { throw ExceptionFactory.GetException(ExceptionType.Smev2MalformedCertificateReference); } XmlElement binaryTokenElement = smev2SignedXml.GetIdElement( message, binaryTokenReference.Substring(1)); if (binaryTokenElement == null) { throw ExceptionFactory.GetException( ExceptionType.Smev2CertificateNotFound, binaryTokenReference.Substring(1)); } try { cert = new X509Certificate2(Convert.FromBase64String(binaryTokenElement.InnerText)); } catch (Exception e) { throw ExceptionFactory.GetException(ExceptionType.Smev2CertificateCorrupted, e.Message); } break; case SignatureType.Smev2ChargeEnveloped: if (signaturesInDoc.Count > 1) { throw ExceptionFactory.GetException( ExceptionType.ChargeTooManySignaturesFound, signaturesInDoc.Count); } if (!ChargeStructureOk(message)) { throw ExceptionFactory.GetException(ExceptionType.ChargeMalformedDocument); } try { signedXml.LoadXml(signatures.First().Value); } catch (Exception e) { throw ExceptionFactory.GetException(ExceptionType.CertificateContentCorrupted, e.Message); } break; case SignatureType.Smev2SidebysideDetached: case SignatureType.Smev3BaseDetached: case SignatureType.Smev3SidebysideDetached: try { XmlDsigSmevTransform smevTransform = new XmlDsigSmevTransform(); signedXml.SafeCanonicalizationMethods.Add(smevTransform.Algorithm); signedXml.LoadXml( !string.IsNullOrEmpty(nodeId) ? signatures[nodeId] : signatures.First().Value); } catch (Exception e) { throw ExceptionFactory.GetException(ExceptionType.CertificateContentCorrupted, e.Message); } break; case SignatureType.Pkcs7String: case SignatureType.Pkcs7StringAllCert: case SignatureType.Pkcs7StringNoCert: case SignatureType.SigDetached: case SignatureType.SigDetachedAllCert: case SignatureType.SigDetachedNoCert: throw new NotSupportedException( $"Detached signature verification is not supported by this method. Use {nameof(VerifyDetachedSignature)} method instead."); case SignatureType.Unknown: case SignatureType.Smev3Ack: case SignatureType.Rsa2048Sha256String: case SignatureType.RsaSha256String: throw ExceptionFactory.GetException(ExceptionType.UnsupportedSignatureType, mode); default: throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } var isSignatureValid = smev2SignedXml?.CheckSignature(cert.PublicKey.Key) ?? (cert == null ? signedXml.CheckSignature() : signedXml.CheckSignature(cert, true) ); var isCertificateChainValid = cert?.Verify() ?? true; StringBuilder verificationMessage = new StringBuilder(); if (!isSignatureValid) { verificationMessage.AppendLine("Signature is invalid"); } if (!isCertificateChainValid) { verificationMessage.AppendLine("Certificate chain is invalid"); } var verifierResponse = new VerifierResponse() { IsCertificateChainValid = isCertificateChainValid, IsSignatureMathematicallyValid = isSignatureValid, IsSignatureSigningDateValid = true, // we do not check this for this type of signature Message = verificationMessage.ToString() }; return(verifierResponse); }