private bool CheckDigestedReferences() { ArrayList references = m_signature.SignedInfo.References; for (int i = 0; i < references.Count; ++i) { Reference digestedReference = (Reference)references[i]; if (!ReferenceUsesSafeTransformMethods(digestedReference)) { return(false); } SignedXmlDebugLog.LogVerifyReference(this, digestedReference); byte[] calculatedHash = null; try { calculatedHash = digestedReference.CalculateHashValue(_containingDocument, m_signature.ReferencedItems); } catch (CryptoSignedXmlRecursionException) { SignedXmlDebugLog.LogSignedXmlRecursionLimit(this, digestedReference); return(false); } // Compare both hashes SignedXmlDebugLog.LogVerifyReferenceHash(this, digestedReference, calculatedHash, digestedReference.DigestValue); if (!CryptographicEquals(calculatedHash, digestedReference.DigestValue)) { return(false); } } return(true); }
public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) { SignedXmlDebugLog.LogBeginSignatureVerification(this, _context); signingKey = null; bool bRet = false; AsymmetricAlgorithm key = null; if (!CheckSignatureFormat()) { return(false); } do { key = GetPublicKey(); if (key != null) { bRet = CheckSignature(key); SignedXmlDebugLog.LogVerificationResult(this, key, bRet); } } while (key != null && bRet == false); signingKey = key; return(bRet); }
private byte[] GetC14NDigest(HashAlgorithm hash) { bool isKeyedHashAlgorithm = hash is KeyedHashAlgorithm; if (isKeyedHashAlgorithm || !_bCacheValid || !SignedInfo.CacheValid) { string baseUri = (_containingDocument == null ? null : _containingDocument.BaseURI); XmlResolver resolver = (_bResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument doc = Utils.PreProcessElementInput(SignedInfo.GetXml(), resolver, baseUri); // Add non default namespaces in scope CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); Utils.AddNamespaces(doc.DocumentElement, namespaces); Transform c14nMethodTransform = SignedInfo.CanonicalizationMethodObject; c14nMethodTransform.Resolver = resolver; c14nMethodTransform.BaseURI = baseUri; SignedXmlDebugLog.LogBeginCanonicalization(this, c14nMethodTransform); c14nMethodTransform.LoadInput(doc); SignedXmlDebugLog.LogCanonicalizedOutput(this, c14nMethodTransform); _digestedSignedInfo = c14nMethodTransform.GetDigestedOutput(hash); _bCacheValid = !isKeyedHashAlgorithm; } return(_digestedSignedInfo); }
private bool IsSafeTransform(string transformAlgorithm) { // All canonicalization algorithms are valid transform algorithms. foreach (string safeAlgorithm in SafeCanonicalizationMethods) { if (string.Equals(safeAlgorithm, transformAlgorithm, StringComparison.OrdinalIgnoreCase)) { return(true); } } foreach (string safeAlgorithm in DefaultSafeTransformMethods) { if (string.Equals(safeAlgorithm, transformAlgorithm, StringComparison.OrdinalIgnoreCase)) { return(true); } } SignedXmlDebugLog.LogUnsafeTransformMethod( this, transformAlgorithm, SafeCanonicalizationMethods, DefaultSafeTransformMethods); return(false); }
private bool CheckDigestedReferences() { ArrayList references = m_signature.SignedInfo.References; for (int i = 0; i < references.Count; ++i) { Reference digestedReference = (Reference)references[i]; SignedXmlDebugLog.LogVerifyReference(this, digestedReference); byte[] calculatedHash = digestedReference.CalculateHashValue(m_containingDocument, m_signature.ReferencedItems); // Compare both hashes SignedXmlDebugLog.LogVerifyReferenceHash(this, digestedReference, calculatedHash, digestedReference.DigestValue); if (calculatedHash.Length != digestedReference.DigestValue.Length) { return(false); } byte[] rgb1 = calculatedHash; byte[] rgb2 = digestedReference.DigestValue; for (int j = 0; j < rgb1.Length; ++j) { if (rgb1[j] != rgb2[j]) { return(false); } } } return(true); }
public void ComputeSignature() { SignedXmlDebugLog.LogBeginSignatureComputation(this, _context); BuildDigestedReferences(); // Load the key AsymmetricAlgorithm key = SigningKey; if (key == null) { throw new CryptographicException(SR.Cryptography_Xml_LoadKeyFailed); } // Check the signature algorithm associated with the key so that we can accordingly set the signature method if (SignedInfo.SignatureMethod == null) { if (key is DSA) { SignedInfo.SignatureMethod = XmlDsigDSAUrl; } else if (key is RSA) { // Default to RSA-SHA256 if (SignedInfo.SignatureMethod == null) { SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; } } else { throw new CryptographicException(SR.Cryptography_Xml_CreatedKeyFailed); } } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = CryptoHelpers.CreateFromName <SignatureDescription>(SignedInfo.SignatureMethod); if (signatureDescription == null) { throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } // Updates the HashAlgorithm's state for signing with the signature formatter below. // The return value is not needed. GetC14NDigest(hashAlg); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); SignedXmlDebugLog.LogSigning(this, key, signatureDescription, hashAlg, asymmetricSignatureFormatter); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); }
public void ComputeSignature() { SignedXmlDebugLog.LogBeginSignatureComputation(this, m_context); BuildDigestedReferences(); // Load the key AsymmetricAlgorithm key = SigningKey; if (key == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed")); } // Check the signature algorithm associated with the key so that we can accordingly set the signature method if (SignedInfo.SignatureMethod == null) { if (key is DSA) { SignedInfo.SignatureMethod = XmlDsigDSAUrl; } else if (key is RSA) { // Default to RSA-SHA1 if (SignedInfo.SignatureMethod == null) { SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; } } else { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } byte[] hashvalue = GetC14NDigest(hashAlg); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); SignedXmlDebugLog.LogSigning(this, key, signatureDescription, hashAlg, asymmetricSignatureFormatter); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); }
private bool CheckSignatureFormat() { if (this.m_signatureFormatValidator == null) { return(true); } SignedXmlDebugLog.LogBeginCheckSignatureFormat(this, this.m_signatureFormatValidator); bool result = this.m_signatureFormatValidator(this); SignedXmlDebugLog.LogFormatValidationResult(this, result); return(result); }
private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { if (macAlg == null) { throw new ArgumentNullException(nameof(macAlg)); } SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) { signatureLength = macAlg.HashSize; } else { signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); } // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > macAlg.HashSize) { throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); } if (signatureLength % 8 != 0) { throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); } if (m_signature.SignatureValue == null) { throw new CryptographicException(SR.Cryptography_Xml_SignatureValueRequired); } if (m_signature.SignatureValue.Length != signatureLength / 8) { throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); } // Calculate the hash byte[] hashValue = GetC14NDigest(macAlg); SignedXmlDebugLog.LogVerifySignedInfo(this, macAlg, hashValue, m_signature.SignatureValue); for (int i = 0; i < m_signature.SignatureValue.Length; i++) { if (m_signature.SignatureValue [i] != hashValue [i]) { return(false); } } return(true); }
// Validation function to see if the signature uses a canonicalization algorithm from our list // of approved algorithm URIs. private bool DoesSignatureUseSafeCanonicalizationMethod() { foreach (string safeAlgorithm in SafeCanonicalizationMethods) { if (string.Equals(safeAlgorithm, SignedInfo.CanonicalizationMethod, StringComparison.OrdinalIgnoreCase)) { return(true); } } SignedXmlDebugLog.LogUnsafeCanonicalizationMethod(this, SignedInfo.CanonicalizationMethod, SafeCanonicalizationMethods); return(false); }
public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnly) { if (!CheckSignature(certificate.PublicKey.Key)) { return(false); } if (verifySignatureOnly) { SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return(true); } // Check key usages to make sure it is good for signing. foreach (X509Extension extension in certificate.Extensions) { if (String.Compare(extension.Oid.Value, CAPI.szOID_KEY_USAGE, StringComparison.OrdinalIgnoreCase) == 0) { X509KeyUsageExtension keyUsage = new X509KeyUsageExtension(); keyUsage.CopyFrom(extension); SignedXmlDebugLog.LogVerifyKeyUsage(this, certificate, keyUsage); bool validKeyUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0 || (keyUsage.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0; if (!validKeyUsage) { SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_X509KeyUsage")); return(false); } break; } } // Do the chain verification to make sure the certificate is valid. X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(BuildBagOfCerts()); bool chainVerified = chain.Build(certificate); SignedXmlDebugLog.LogVerifyX509Chain(this, chain, certificate); if (!chainVerified) { SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_X509Chain")); return(false); } SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return(true); }
public void ComputeSignature(KeyedHashAlgorithm macAlg) { if (macAlg == null) { throw new ArgumentNullException(nameof(macAlg)); } HMAC hash = macAlg as HMAC; if (hash == null) { throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) { signatureLength = hash.HashSize; } else { signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); } // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > hash.HashSize) { throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); } if (signatureLength % 8 != 0) { throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); } BuildDigestedReferences(); SignedInfo.SignatureMethod = hash.HashName switch { "SHA1" => SignedXml.XmlDsigHMACSHA1Url, "SHA256" => SignedXml.XmlDsigMoreHMACSHA256Url, "SHA384" => SignedXml.XmlDsigMoreHMACSHA384Url, "SHA512" => SignedXml.XmlDsigMoreHMACSHA512Url, "MD5" => SignedXml.XmlDsigMoreHMACMD5Url, "RIPEMD160" => SignedXml.XmlDsigMoreHMACRIPEMD160Url, _ => throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch), }; byte[] hashValue = GetC14NDigest(hash); SignedXmlDebugLog.LogSigning(this, hash); m_signature.SignatureValue = new byte[signatureLength / 8]; Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8); }
public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnly) { if (!verifySignatureOnly) { // Check key usages to make sure it is good for signing. foreach (X509Extension extension in certificate.Extensions) { if (string.Equals(extension.Oid.Value, "2.5.29.15" /* szOID_KEY_USAGE */, StringComparison.OrdinalIgnoreCase)) { X509KeyUsageExtension keyUsage = new X509KeyUsageExtension(); keyUsage.CopyFrom(extension); SignedXmlDebugLog.LogVerifyKeyUsage(this, certificate, keyUsage); bool validKeyUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0 || (keyUsage.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0; if (!validKeyUsage) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_X509KeyUsage); return(false); } break; } } // Do the chain verification to make sure the certificate is valid. X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(BuildBagOfCerts()); bool chainVerified = chain.Build(certificate); SignedXmlDebugLog.LogVerifyX509Chain(this, chain, certificate); if (!chainVerified) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_X509Chain); return(false); } } using (AsymmetricAlgorithm publicKey = Utils.GetAnyPublicKey(certificate)) { if (!CheckSignature(publicKey)) { return(false); } } SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return(true); }
// If we have a signature format validation callback, check to see if this signature's format (not // the signautre itself) is valid according to the validator. A return value of true indicates that // the signature format is acceptable, false means that the format is not valid. private bool CheckSignatureFormat() { if (_signatureFormatValidator == null) { // No format validator means that we default to accepting the signature. (This is // effectively compatibility mode with v3.5). return(true); } SignedXmlDebugLog.LogBeginCheckSignatureFormat(this, _signatureFormatValidator); bool formatValid = _signatureFormatValidator(this); SignedXmlDebugLog.LogFormatValidationResult(this, formatValid); return(formatValid); }
private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization ArrayList references = SignedInfo.References; // Reset the cache _refProcessed = new bool [references.Count]; _refLevelCache = new int [references.Count]; ReferenceLevelSortOrder sortOrder = new ReferenceLevelSortOrder(); sortOrder.References = references; // Don't alter the order of the references array list ArrayList sortedReferences = new ArrayList(); foreach (Reference reference in references) { sortedReferences.Add(reference); } sortedReferences.Sort(sortOrder); CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); foreach (DataObject obj in m_signature.ObjectList) { nodeList.Add(obj.GetXml()); } foreach (Reference reference in sortedReferences) { if (reference.DigestMethod == null) { reference.DigestMethod = XmlDsigDigestDefault; } SignedXmlDebugLog.LogSigningReference(this, reference); reference.UpdateHashValue(_containingDocument, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) { nodeList.Add(reference.GetXml()); } } }
public void ComputeSignature() { SignedXmlDebugLog.LogBeginSignatureComputation(this, this.m_context); this.BuildDigestedReferences(); AsymmetricAlgorithm signingKey = this.SigningKey; if (signingKey == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed")); } if (this.SignedInfo.SignatureMethod == null) { if (!(signingKey is DSA)) { if (!(signingKey is RSA)) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } if (this.SignedInfo.SignatureMethod == null) { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } } else { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; } } SignatureDescription signatureDescription = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } HashAlgorithm hash = signatureDescription.CreateDigest(); if (hash == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } this.GetC14NDigest(hash); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(signingKey); SignedXmlDebugLog.LogSigning(this, signingKey, signatureDescription, hash, asymmetricSignatureFormatter); this.m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hash); }
private bool CheckSignedInfo(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException("key"); } SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } // Let's see if the key corresponds with the SignatureMethod Type ta = Type.GetType(signatureDescription.KeyAlgorithm); Type tb = key.GetType(); if ((ta != tb) && !ta.IsSubclassOf(tb) && !tb.IsSubclassOf(ta)) { // Signature method key mismatch return(false); } HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } byte[] hashval = GetC14NDigest(hashAlgorithm); AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key); SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hashAlgorithm, asymmetricSignatureDeformatter, hashval, m_signature.SignatureValue); return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue)); }
private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { int hashSize; if (macAlg == null) { throw new ArgumentNullException("macAlg"); } SignedXmlDebugLog.LogBeginCheckSignedInfo(this, this.m_signature.SignedInfo); if (this.m_signature.SignedInfo.SignatureLength == null) { hashSize = macAlg.HashSize; } else { hashSize = Convert.ToInt32(this.m_signature.SignedInfo.SignatureLength, (IFormatProvider)null); } if ((hashSize < 0) || (hashSize > macAlg.HashSize)) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength")); } if ((hashSize % 8) != 0) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2")); } if (this.m_signature.SignatureValue == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureValueRequired")); } if (this.m_signature.SignatureValue.Length != (hashSize / 8)) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength")); } byte[] actualHashValue = this.GetC14NDigest(macAlg); SignedXmlDebugLog.LogVerifySignedInfo(this, macAlg, actualHashValue, this.m_signature.SignatureValue); for (int i = 0; i < this.m_signature.SignatureValue.Length; i++) { if (this.m_signature.SignatureValue[i] != actualHashValue[i]) { return(false); } } return(true); }
public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnly) { if (!this.CheckSignature(certificate.PublicKey.Key)) { return(false); } if (verifySignatureOnly) { SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return(true); } X509ExtensionEnumerator enumerator = certificate.Extensions.GetEnumerator(); while (enumerator.MoveNext()) { X509Extension current = enumerator.Current; if (string.Compare(current.Oid.Value, "2.5.29.15", StringComparison.OrdinalIgnoreCase) == 0) { X509KeyUsageExtension keyUsages = new X509KeyUsageExtension(); keyUsages.CopyFrom(current); SignedXmlDebugLog.LogVerifyKeyUsage(this, certificate, keyUsages); if (((keyUsages.KeyUsages & X509KeyUsageFlags.DigitalSignature) != X509KeyUsageFlags.None) || ((keyUsages.KeyUsages & X509KeyUsageFlags.NonRepudiation) != X509KeyUsageFlags.None)) { break; } SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_X509KeyUsage")); return(false); } } X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(this.BuildBagOfCerts()); bool flag2 = chain.Build(certificate); SignedXmlDebugLog.LogVerifyX509Chain(this, chain, certificate); if (!flag2) { SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_X509Chain")); return(false); } SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return(true); }
public bool CheckSignature(KeyedHashAlgorithm macAlg) { if (!this.CheckSignatureFormat()) { return(false); } if (!this.CheckSignedInfo(macAlg)) { SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_SignedInfo")); return(false); } if (!this.CheckDigestedReferences()) { SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_References")); return(false); } SignedXmlDebugLog.LogVerificationResult(this, macAlg, true); return(true); }
private bool CheckSignedInfo(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); } // Let's see if the key corresponds with the SignatureMethod Type ta = Type.GetType(signatureDescription.KeyAlgorithm); if (!IsKeyTheCorrectAlgorithm(key, ta)) { return(false); } HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) { throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } byte[] hashval = GetC14NDigest(hashAlgorithm); AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key); SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hashAlgorithm, asymmetricSignatureDeformatter, hashval, m_signature.SignatureValue); return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue)); }
private byte[] GetC14NDigest(HashAlgorithm hash) { if (!this.bCacheValid || !this.SignedInfo.CacheValid) { string securityUrl = (this.m_containingDocument == null) ? null : this.m_containingDocument.BaseURI; XmlResolver xmlResolver = this.m_bResolverSet ? this.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(this.SignedInfo.GetXml(), xmlResolver, securityUrl); CanonicalXmlNodeList namespaces = (this.m_context == null) ? null : System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_context); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); System.Security.Cryptography.Xml.Utils.AddNamespaces(document.DocumentElement, namespaces); Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject; canonicalizationMethodObject.Resolver = xmlResolver; canonicalizationMethodObject.BaseURI = securityUrl; SignedXmlDebugLog.LogBeginCanonicalization(this, canonicalizationMethodObject); canonicalizationMethodObject.LoadInput(document); SignedXmlDebugLog.LogCanonicalizedOutput(this, canonicalizationMethodObject); this._digestedSignedInfo = canonicalizationMethodObject.GetDigestedOutput(hash); this.bCacheValid = true; } return(this._digestedSignedInfo); }
public bool CheckSignature(KeyedHashAlgorithm macAlg) { if (!CheckSignatureFormat()) { return(false); } if (!CheckSignedInfo(macAlg)) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_SignedInfo); return(false); } if (!CheckDigestedReferences()) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_References); return(false); } SignedXmlDebugLog.LogVerificationResult(this, macAlg, true); return(true); }
public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) { SignedXmlDebugLog.LogBeginSignatureVerification(this, this.m_context); signingKey = null; bool verified = false; AsymmetricAlgorithm key = null; if (!this.CheckSignatureFormat()) { return(false); } do { key = this.GetPublicKey(); if (key != null) { verified = this.CheckSignature(key); SignedXmlDebugLog.LogVerificationResult(this, key, verified); } }while ((key != null) && !verified); signingKey = key; return(verified); }
public bool CheckSignature(AsymmetricAlgorithm key) { if (!CheckSignatureFormat()) { return(false); } if (!CheckSignedInfo(key)) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_SignedInfo); return(false); } // Now is the time to go through all the references and see if their DigestValues are good if (!CheckDigestedReferences()) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_References); return(false); } SignedXmlDebugLog.LogVerificationResult(this, key, true); return(true); }
private void BuildDigestedReferences() { ArrayList references = this.SignedInfo.References; this.m_refProcessed = new bool[references.Count]; this.m_refLevelCache = new int[references.Count]; ReferenceLevelSortOrder comparer = new ReferenceLevelSortOrder { References = references }; ArrayList list2 = new ArrayList(); foreach (Reference reference in references) { list2.Add(reference); } list2.Sort(comparer); CanonicalXmlNodeList refList = new CanonicalXmlNodeList(); foreach (DataObject obj2 in this.m_signature.ObjectList) { refList.Add(obj2.GetXml()); } foreach (Reference reference2 in list2) { if (reference2.DigestMethod == null) { reference2.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; } SignedXmlDebugLog.LogSigningReference(this, reference2); reference2.UpdateHashValue(this.m_containingDocument, refList); if (reference2.Id != null) { refList.Add(reference2.GetXml()); } } }
// What we want to do is pump the input throug the TransformChain and then // hash the output of the chain document is the document context for resolving relative references internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm _hashAlgorithm = CryptoHelpers.CreateFromName <HashAlgorithm>(_digestMethod); if (_hashAlgorithm == null) { throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; byte[] hashval = null; try { switch (_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) if (_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (_uri.Length == 0) { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process if (document == null) { throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // Normalize the containing document resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (_uri[0] == '#') { // If we get here, then we are constructing a Reference to an embedded DataObject // referenced by an Id = attribute. Go find the relevant object bool discardComments = true; string idref = Utils.GetIdFromLocalUri(_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) { throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // We should not discard comments here!!! resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = SignedXml.GetIdElement(document, idref); if (elem != null) { _namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); } if (elem == null) { // Go throw the referenced items passed in if (refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (_signedXml._context != null) { _namespaces = Utils.GetPropagatedAttributes(_signedXml._context); } break; } } } } if (elem == null) { throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); } XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, _namespaces); resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); hashval = _hashAlgorithm.ComputeHash(hashInputStream); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(hashval); }
public void ComputeSignature(KeyedHashAlgorithm macAlg) { int hashSize; if (macAlg == null) { throw new ArgumentNullException("macAlg"); } HMAC hash = macAlg as HMAC; if (hash == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch")); } if (this.m_signature.SignedInfo.SignatureLength == null) { hashSize = hash.HashSize; } else { hashSize = Convert.ToInt32(this.m_signature.SignedInfo.SignatureLength, (IFormatProvider)null); } if ((hashSize < 0) || (hashSize > hash.HashSize)) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength")); } if ((hashSize % 8) != 0) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2")); } this.BuildDigestedReferences(); switch (hash.HashName) { case "SHA1": this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"; break; case "SHA256": this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; break; case "SHA384": this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; break; case "SHA512": this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; break; case "MD5": this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-md5"; break; case "RIPEMD160": this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; break; default: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch")); } byte[] src = this.GetC14NDigest(hash); SignedXmlDebugLog.LogSigning(this, hash); this.m_signature.SignatureValue = new byte[hashSize / 8]; Buffer.BlockCopy(src, 0, this.m_signature.SignatureValue, 0, hashSize / 8); }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { this.m_hashAlgorithm = CryptoConfig.CreateFromName(this.m_digestMethod) as HashAlgorithm; if (this.m_hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } string securityUrl = (document == null) ? (Environment.CurrentDirectory + @"\") : document.BaseURI; Stream data = null; WebRequest request = null; WebResponse response = null; Stream input = null; XmlResolver resolver = null; byte[] buffer = null; try { switch (this.m_refTargetType) { case System.Security.Cryptography.Xml.ReferenceTargetType.Stream: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream)this.m_refTarget, resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.XmlElement: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessElementInput((XmlElement)this.m_refTarget, resolver, securityUrl), resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.UriReference: if (this.m_uri != null) { break; } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream)null, resolver, securityUrl); goto Label_048A; default: goto Label_0474; } if (this.m_uri.Length == 0) { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document2 = System.Security.Cryptography.Xml.Utils.DiscardComments(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl)); data = this.TransformChain.TransformToOctetStream(document2, resolver, securityUrl); goto Label_048A; } if (this.m_uri[0] == '#') { bool discardComments = true; string idFromLocalUri = System.Security.Cryptography.Xml.Utils.GetIdFromLocalUri(this.m_uri, out discardComments); if (idFromLocalUri == "xpointer(/)") { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl), resolver, securityUrl); } else { XmlElement idElement = this.SignedXml.GetIdElement(document, idFromLocalUri); if (idElement != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(idElement.ParentNode as XmlElement); } if ((idElement == null) && (refList != null)) { foreach (XmlNode node in refList) { XmlElement element = node as XmlElement; if (((element != null) && System.Security.Cryptography.Xml.Utils.HasAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#")) && System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#").Equals(idFromLocalUri)) { idElement = element; if (this.m_signedXml.m_context != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_signedXml.m_context); } break; } } } if (idElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); } XmlDocument document3 = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(idElement, resolver, securityUrl); System.Security.Cryptography.Xml.Utils.AddNamespaces(document3.DocumentElement, this.m_namespaces); resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); if (discardComments) { XmlDocument document4 = System.Security.Cryptography.Xml.Utils.DiscardComments(document3); data = this.TransformChain.TransformToOctetStream(document4, resolver, securityUrl); } else { data = this.TransformChain.TransformToOctetStream(document3, resolver, securityUrl); } } goto Label_048A; } System.Uri relativeUri = new System.Uri(this.m_uri, UriKind.RelativeOrAbsolute); if (!relativeUri.IsAbsoluteUri) { relativeUri = new System.Uri(new System.Uri(securityUrl), relativeUri); } request = WebRequest.Create(relativeUri); if (request != null) { response = request.GetResponse(); if (response != null) { input = response.GetResponseStream(); if (input != null) { resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(input, resolver, this.m_uri); goto Label_048A; } } } Label_0474: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), this.m_uri); Label_048A: data = SignedXmlDebugLog.LogReferenceData(this, data); buffer = this.m_hashAlgorithm.ComputeHash(data); } finally { if (data != null) { data.Close(); } if (response != null) { response.Close(); } if (input != null) { input.Close(); } } return(buffer); }
public void ComputeSignature(KeyedHashAlgorithm macAlg) { if (macAlg == null) { throw new ArgumentNullException("macAlg"); } HMAC hash = macAlg as HMAC; if (hash == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch")); } int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) { signatureLength = hash.HashSize; } else { signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); } // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > hash.HashSize) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength")); } if (signatureLength % 8 != 0) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2")); } BuildDigestedReferences(); switch (hash.HashName) { case "SHA1": SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url; break; case "SHA256": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA256Url; break; case "SHA384": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA384Url; break; case "SHA512": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA512Url; break; case "MD5": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACMD5Url; break; case "RIPEMD160": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACRIPEMD160Url; break; default: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch")); } byte[] hashValue = GetC14NDigest(hash); SignedXmlDebugLog.LogSigning(this, hash); m_signature.SignatureValue = new byte[signatureLength / 8]; Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8); }