private static bool CheckSignedInfo(SignedXml signedXml, AsymmetricAlgorithm key) { //Copied from reflected System.Security.Cryptography.Xml.SignedXml SignatureDescription signatureDescription = CryptoConfig.CreateFromName(signedXml.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetString("Cryptography_Xml_SignatureDescriptionNotCreated")); } Type type = Type.GetType(signatureDescription.KeyAlgorithm); Type type2 = key.GetType(); if (type != type2 && !type.IsSubclassOf(type2) && !type2.IsSubclassOf(type)) { return(false); } HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetString("Cryptography_Xml_CreateHashAlgorithmFailed")); } //Except this. The SignedXml class creates and cananicalizes a Signature element without any prefix, rather than using the element from the document provided byte[] c14NDigest = GetC14NDigest(signedXml, hashAlgorithm); AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key); return(asymmetricSignatureDeformatter.VerifySignature(c14NDigest, signedXml.Signature.SignatureValue)); }
public void ValidateCreateDeformatter() { AsymmetricSignatureDeformatter deformatter = CreateDeformatter(GostECDsa256.Create()); Assert.NotNull(deformatter); Assert.True(deformatter is GostECDsa256SignatureDeformatter); }
public static void DSADemo() { // Create a digital signature based on RSA encryption. SignatureDescription rsaSignature = CreateRSAPKCS1Signature(); ShowProperties(rsaSignature); // Create a digital signature based on DSA encryption. SignatureDescription dsaSignature = CreateDSASignature(); ShowProperties(dsaSignature); // Create a HashAlgorithm using the digest algorithm of the signature. HashAlgorithm hashAlgorithm = dsaSignature.CreateDigest(); Console.WriteLine("\nHash algorithm for the DigestAlgorithm property:" + " " + hashAlgorithm.ToString()); // Create an AsymmetricSignatureFormatter instance using the DSA key. DSA dsa = DSA.Create(); AsymmetricSignatureFormatter asymmetricFormatter = CreateDSAFormatter(dsa); // Create an AsymmetricSignatureDeformatter instance using the // DSA key. AsymmetricSignatureDeformatter asymmetricDeformatter = CreateDSADeformatter(dsa); Console.WriteLine("This sample completed successfully; " + "press Enter to exit."); Console.ReadLine(); }
private bool CheckSignedInfo(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException("key"); } SignedXmlDebugLog.LogBeginCheckSignedInfo(this, this.m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoConfig.CreateFromName(this.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } Type c = Type.GetType(signatureDescription.KeyAlgorithm); Type type = key.GetType(); if (((c != type) && !c.IsSubclassOf(type)) && !type.IsSubclassOf(c)) { return(false); } HashAlgorithm hash = signatureDescription.CreateDigest(); if (hash == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } byte[] actualHashValue = this.GetC14NDigest(hash); AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key); SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hash, asymmetricSignatureDeformatter, actualHashValue, this.m_signature.SignatureValue); return(asymmetricSignatureDeformatter.VerifySignature(actualHashValue, this.m_signature.SignatureValue)); }
public void RSAPKCS1SHA256RoundTripTest() { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048)) { RSAPKCS1SHA256SignatureDescription sd = new RSAPKCS1SHA256SignatureDescription(); using (HashAlgorithm digestAlgorithm = sd.CreateDigest()) { // Create some data to sign RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] data = new byte[1025]; rng.GetBytes(data); byte[] hash = digestAlgorithm.ComputeHash(data); // Sign the data AsymmetricSignatureFormatter formatter = sd.CreateFormatter(rsa); byte[] signature = formatter.CreateSignature(hash); Assert.IsNotNull(signature, "Failed to create a signature"); // Verify the signature AsymmetricSignatureDeformatter deformatter = sd.CreateDeformatter(rsa); Assert.IsTrue(deformatter.VerifySignature(hash, signature), "Failed to verify signature"); } } }
/// <summary> /// Valida la firma electronica utilizando una clave externa /// </summary> /// <param name="key">Clave publica asociada a la firma electrónica</param> /// <returns>true si la firma se valido correctamente</returns> public bool CheckSignature(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException("key"); } bool result = CheckReferenceIntegrity(); if (result) { SignatureDescription sd = GetSignatureDescription(signature.SignedInfo.SignatureMethod); byte[] hash = Hash(sd.DigestAlgorithm); AsymmetricSignatureDeformatter verifier = sd.CreateDeformatter(key); //(AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(sd.DeformatterAlgorithm); if (verifier != null) { //verifier.SetHashAlgorithm(sd.DigestAlgorithm); //verifier.SetKey(key); result = verifier.VerifySignature(hash, signature.SignatureValue); } else { result = false; } } return(result); }
public virtual AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { AsymmetricSignatureDeformatter item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm); item.SetKey(key); return(item); }
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { AsymmetricSignatureDeformatter item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm); item.setKey(key); item.SetHashAlgorithm(_hashAlgorithm); return(item); }
/// <summary> /// Creates signature deformatter /// </summary> /// <param name="key"></param> /// <returns></returns> public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(base.DeformatterAlgorithm); asymmetricSignatureDeformatter.SetKey(key); asymmetricSignatureDeformatter.SetHashAlgorithm("SHA256"); return(asymmetricSignatureDeformatter); }
private static void VerifySignatureWithHashAlgorithm(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm) { byte[] signature = formatter.CreateSignature(hashAlgorithm); Assert.True(deformatter.VerifySignature(hashAlgorithm, signature)); signature[signature.Length - 1] ^= 0xff; Assert.False(deformatter.VerifySignature(hashAlgorithm, signature)); }
public AsymmetricSignatureDeformatter CreateDeformatter(string signatureAlgorithm = null) { UpdateSignatureAlgorithm(signatureAlgorithm); Deformatter = Key.GetSignatureDeformatter(SignatureAlgorithm); CreateHashAlgorithm(); Deformatter.SetHashAlgorithm(HashAlgorithm.GetType().ToString()); return(Deformatter); }
protected static void VerifySignature(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm, string hashAlgorithmName) { formatter.SetHashAlgorithm(hashAlgorithmName); deformatter.SetHashAlgorithm(hashAlgorithmName); byte[] hash = hashAlgorithm.ComputeHash(HelloBytes); VerifySignatureWithHashBytes(formatter, deformatter, hash); VerifySignatureWithHashAlgorithm(formatter, deformatter, hashAlgorithm); }
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, System.IdentityModel.SR.GetString("EmptyOrNullArgumentString", new object[] { "algorithm" })); } object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmFromConfig != null) { SignatureDescription description = algorithmFromConfig as SignatureDescription; if (description != null) { return(description.CreateDeformatter(this.PublicKey.Key)); } try { AsymmetricSignatureDeformatter deformatter = algorithmFromConfig as AsymmetricSignatureDeformatter; if (deformatter != null) { deformatter.SetKey(this.PublicKey.Key); return(deformatter); } } catch (InvalidCastException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("AlgorithmAndPublicKeyMisMatch"), exception)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetSignatureDeformatter" }))); } switch (algorithm) { case "http://www.w3.org/2000/09/xmldsig#dsa-sha1": { DSA key = this.PublicKey.Key as DSA; if (key == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PublicKeyNotDSA"))); } return(new DSASignatureDeformatter(key)); } case "http://www.w3.org/2000/09/xmldsig#rsa-sha1": case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256": { RSA rsa = this.PublicKey.Key as RSA; if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PublicKeyNotRSA"))); } return(new RSAPKCS1SignatureDeformatter(rsa)); } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedCryptoAlgorithm", new object[] { algorithm }))); }
public void Deformatter() { AsymmetricSignatureDeformatter def = null; // Deformatter with all properties null try { def = sig.CreateDeformatter(dsa); Assert.Fail("Expected ArgumentNullException but got none"); } catch (ArgumentNullException) { // this is what we expect } catch (Exception e) { Assert.Fail("Expected ArgumentNullException but got: " + e.ToString()); } // Deformatter with invalid DeformatterAlgorithm property sig.DeformatterAlgorithm = "DSA"; try { def = sig.CreateDeformatter(dsa); Assert.Fail("Expected InvalidCastException but got none"); } catch (InvalidCastException) { // this is what we expect } catch (Exception e) { Assert.Fail("Expected InvalidCastException but got: " + e.ToString()); } // Deformatter with valid DeformatterAlgorithm property sig.DeformatterAlgorithm = "DSASignatureDeformatter"; try { def = sig.CreateDeformatter(dsa); Assert.Fail("Expected NullReferenceException but got none"); } catch (NullReferenceException) { // this is what we expect } catch (Exception e) { Assert.Fail("Expected NullReferenceException but got: " + e.ToString()); } // Deformatter with valid DeformatterAlgorithm property sig.KeyAlgorithm = "DSA"; sig.DigestAlgorithm = "SHA1"; sig.DeformatterAlgorithm = "DSASignatureDeformatter"; try { def = sig.CreateDeformatter(dsa); Assert.Fail("Expected NullReferenceException but got none"); } catch (NullReferenceException) { // this is what we expect } catch (Exception e) { Assert.Fail("Expected NullReferenceException but got: " + e.ToString()); } }
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { AsymmetricSignatureDeformatter signatureDeformatter = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(this.DeformatterAlgorithm); AsymmetricAlgorithm key1 = key; signatureDeformatter.SetKey(key1); string strName = "SHA1"; signatureDeformatter.SetHashAlgorithm(strName); return(signatureDeformatter); }
/// <summary>Gets the de-formatter algorithm for the digital signature.</summary> /// <param name="algorithm">The de-formatter algorithm for the digital signature to get an instance of.</param> /// <returns>An <see cref="T:System.Security.Cryptography.AsymmetricSignatureDeformatter" /> that represents the de-formatter algorithm for the digital signature.</returns> /// <exception cref="T:System.NotSupportedException"> /// <paramref name="algorithm" /> is <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigDSAUrl" /> and the public key for the X.509 certificate specified in the constructor is not of type <see cref="T:System.Security.Cryptography.DSA" />.-or- /// <paramref name="algorithm" /> is <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigRSASHA1Url" /> or <see cref="F:System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256Signature" /> and the public key for the X.509 certificate specified in the constructor is not of type <see cref="T:System.Security.Cryptography.RSA" />.-or- /// <paramref name="algorithm" /> is not supported. The supported algorithms are <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigDSAUrl" />, /// <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigRSASHA1Url" />, and <see cref="F:System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256Signature" />.</exception> public override AsymmetricSignatureDeformatter GetSignatureDeformatter( string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw new ArgumentNullException(nameof(algorithm)); } object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmFromConfig != null) { SignatureDescription signatureDescription = algorithmFromConfig as SignatureDescription; if (signatureDescription != null) { return(signatureDescription.CreateDeformatter(this.PublicKey)); } try { AsymmetricSignatureDeformatter signatureDeformatter = algorithmFromConfig as AsymmetricSignatureDeformatter; if (signatureDeformatter != null) { signatureDeformatter.SetKey(this.PublicKey); return(signatureDeformatter); } } catch (InvalidCastException ex) { throw new NotSupportedException("AlgorithmAndPublicKeyMisMatch", (Exception)ex); } throw new CryptographicException("UnsupportedAlgorithmForCryptoOperation"); } if (algorithm != "http://www.w3.org/2000/09/xmldsig#dsa-sha1") { if (algorithm == "http://www.w3.org/2000/09/xmldsig#rsa-sha1" || algorithm == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") { RSA publicKey = this.PublicKey as RSA; if (publicKey == null) { throw new NotSupportedException("PublicKeyNotRSA"); } return((AsymmetricSignatureDeformatter) new ADSD.Crypto.RSAPKCS1SignatureDeformatter((AsymmetricAlgorithm)publicKey)); } throw new NotSupportedException("UnsupportedCryptoAlgorithm"); } DSA publicKey1 = this.PublicKey as DSA; if (publicKey1 == null) { throw new NotSupportedException("PublicKeyNotDSA"); } return((AsymmetricSignatureDeformatter) new DSASignatureDeformatter((AsymmetricAlgorithm)publicKey1)); }
// Create a signature deformatter for DSA decryption. public static AsymmetricSignatureDeformatter CreateDSADeformatter(DSA dsa) { // Create a DSA signature deformatter to verify the signature. SignatureDescription signatureDescription = new SignatureDescription(); signatureDescription.DeformatterAlgorithm = "System.Security.Cryptography.DSASignatureDeformatter"; AsymmetricSignatureDeformatter asymmetricDeformatter = signatureDescription.CreateDeformatter(dsa); Console.WriteLine("\nCreated deformatter : " + asymmetricDeformatter.ToString()); return(asymmetricDeformatter); }
public bool VerifySign(string data, string sign) { HashAlgorithm ha = (HashAlgorithm) new SHA1CryptoServiceProvider(); ha.Initialize(); byte[] buf = Convert.FromBase64String(sign); byte[] hash = ha.ComputeHash(_encoding.GetBytes(data)); AsymmetricSignatureDeformatter df = (AsymmetricSignatureDeformatter) new RSAPKCS1SignatureDeformatter(rsaCryptoServiceProvider); df.SetHashAlgorithm(HashAlgorithmName); return(df.VerifySignature(hash, buf)); }
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, algorithm)); } object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { SignatureDescription description = algorithmObject as SignatureDescription; if (description != null) { return(description.CreateDeformatter(this.rsa)); } try { AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter; if (asymmetricSignatureDeformatter != null) { asymmetricSignatureDeformatter.SetKey(this.rsa); return(asymmetricSignatureDeformatter); } } catch (InvalidCastException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.AlgorithmAndKeyMisMatch, algorithm), e)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureDeformatter"))); } switch (algorithm) { case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: return(new RSAPKCS1SignatureDeformatter(rsa)); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureDeformatter"))); } }
public void VerifySignature(string providedSignature) { this.SetSignatureValue(providedSignature); AsymmetricAlgorithm privateKey; SignatureDescription description; HashAlgorithm hash; this.ComputeHash(out privateKey, out description, out hash); AsymmetricSignatureDeformatter deformatter = description.CreateDeformatter(privateKey); if (!deformatter.VerifySignature(hash, this.signatureValue)) { throw new CompactSignatureSecurityException("Signature verification failed"); } }
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)); }
public virtual AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { if (_DeformatterAlgorithm == null) { throw new ArgumentNullException("DeformatterAlgorithm"); } // this should throw the InvalidCastException if we have an invalid class // (but not if the class doesn't exist - as null is valid for AsymmetricSignatureDeformatter) AsymmetricSignatureDeformatter def = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(_DeformatterAlgorithm); if (_KeyAlgorithm == null) { throw new NullReferenceException("KeyAlgorithm"); } def.SetKey(key); return(def); }
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 void VerifySignature(HashAlgorithm hash, AsymmetricSignatureDeformatter deformatter, string signatureMethod) { bool flag; this.Signature.SignedInfo.ComputeHash(hash); if (System.IdentityModel.SecurityUtils.RequiresFipsCompliance && (signatureMethod == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")) { deformatter.SetHashAlgorithm("SHA256"); flag = deformatter.VerifySignature(hash.Hash, this.GetSignatureValue()); } else { flag = deformatter.VerifySignature(hash, this.GetSignatureValue()); } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("SignatureVerificationFailed"))); } }
public void RSAPKCS1SHA256SignatureCreateTest() { RSAPKCS1SHA256SignatureDescription sd = new RSAPKCS1SHA256SignatureDescription(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // We should be using the PKCS1 signature deformatter AsymmetricSignatureDeformatter deformatter = sd.CreateDeformatter(rsa); Assert.IsInstanceOfType(deformatter, typeof(RSAPKCS1SignatureDeformatter)); // We should be using the PKCS1 signature formatter AsymmetricSignatureFormatter formatter = sd.CreateFormatter(rsa); Assert.IsInstanceOfType(formatter, typeof(RSAPKCS1SignatureFormatter)); } // We should be using SHA256Managed for hashing using (HashAlgorithm digestAlgorithm = sd.CreateDigest()) { Assert.IsInstanceOfType(digestAlgorithm, typeof(SHA256Managed)); } }
/// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } }
// Is the signature (over SignedInfo) valid ? private bool CheckSignatureWithKey(AsymmetricAlgorithm key) { if (key == null) { return(false); } SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName(m_signature.SignedInfo.SignatureMethod); if (sd == null) { return(false); } AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(sd.DeformatterAlgorithm); if (verifier == null) { return(false); } try { verifier.SetKey(key); verifier.SetHashAlgorithm(sd.DigestAlgorithm); HashAlgorithm hash = GetHash(sd.DigestAlgorithm, true); // get the hash of the C14N SignedInfo element MemoryStream ms = (MemoryStream)SignedInfoTransformed(); byte[] digest = hash.ComputeHash(ms); return(verifier.VerifySignature(digest, m_signature.SignatureValue)); } catch { // e.g. SignatureMethod != AsymmetricAlgorithm type return(false); } }
public void StartSignatureVerification(SecurityKey verificationKey) { string signatureMethod = this.Signature.SignedInfo.SignatureMethod; SymmetricSecurityKey key = verificationKey as SymmetricSecurityKey; if (key != null) { using (KeyedHashAlgorithm algorithm = key.GetKeyedHashAlgorithm(signatureMethod)) { if (algorithm == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnableToCreateKeyedHashAlgorithmFromSymmetricCrypto", new object[] { signatureMethod, key }))); } this.VerifySignature(algorithm); return; } } AsymmetricSecurityKey key2 = verificationKey as AsymmetricSecurityKey; if (key2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("UnknownICryptoType", new object[] { verificationKey }))); } using (HashAlgorithm algorithm2 = key2.GetHashAlgorithmForSignature(signatureMethod)) { if (algorithm2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnableToCreateHashAlgorithmFromAsymmetricCrypto", new object[] { signatureMethod, key2 }))); } AsymmetricSignatureDeformatter signatureDeformatter = key2.GetSignatureDeformatter(signatureMethod); if (signatureDeformatter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnableToCreateSignatureDeformatterFromAsymmetricCrypto", new object[] { signatureMethod, key2 }))); } this.VerifySignature(algorithm2, signatureDeformatter, signatureMethod); } }
void RSASignatureDescriptionCore(string name, string expectedDigestAlgorithm, string expectedSelectedDigestAlgorithm) { // internal class - we cannot create one without CryptoConfig SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName(name); Assert.AreEqual(expectedDigestAlgorithm, sd.DigestAlgorithm); Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureDeformatter", sd.DeformatterAlgorithm); Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureFormatter", sd.FormatterAlgorithm); Assert.AreEqual("System.Security.Cryptography.RSA", sd.KeyAlgorithm); HashAlgorithm hash = sd.CreateDigest(); Assert.AreEqual(expectedSelectedDigestAlgorithm, hash.ToString()); Assert.AreEqual("System.Security.Cryptography.RSA", sd.KeyAlgorithm); AsymmetricSignatureDeformatter asd = sd.CreateDeformatter(rsa); Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureDeformatter", asd.ToString()); AsymmetricSignatureFormatter asf = sd.CreateFormatter(rsa); Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureFormatter", asf.ToString()); }
public void DSASignatureDescription() { // internal class - we cannot create one without CryptoConfig SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName("http://www.w3.org/2000/09/xmldsig#dsa-sha1"); Assert.AreEqual("System.Security.Cryptography.SHA1CryptoServiceProvider", sd.DigestAlgorithm); Assert.AreEqual("System.Security.Cryptography.DSASignatureDeformatter", sd.DeformatterAlgorithm); Assert.AreEqual("System.Security.Cryptography.DSASignatureFormatter", sd.FormatterAlgorithm); Assert.AreEqual("System.Security.Cryptography.DSACryptoServiceProvider", sd.KeyAlgorithm); HashAlgorithm hash = sd.CreateDigest(); Assert.AreEqual("System.Security.Cryptography.SHA1CryptoServiceProvider", hash.ToString()); Assert.AreEqual(dsa.ToString(), sd.KeyAlgorithm); AsymmetricSignatureDeformatter asd = sd.CreateDeformatter(dsa); Assert.AreEqual("System.Security.Cryptography.DSASignatureDeformatter", asd.ToString()); AsymmetricSignatureFormatter asf = sd.CreateFormatter(dsa); Assert.AreEqual("System.Security.Cryptography.DSASignatureFormatter", asf.ToString()); }
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm) { // We support one of the two algoritms, but not both. // XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; // XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.GetString(SR.EmptyOrNullArgumentString, "algorithm")); } object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { SignatureDescription description = algorithmObject as SignatureDescription; if (description != null) { return(description.CreateDeformatter(this.PublicKey)); } try { AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter; if (asymmetricSignatureDeformatter != null) { asymmetricSignatureDeformatter.SetKey(this.PublicKey); return(asymmetricSignatureDeformatter); } } catch (InvalidCastException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.AlgorithmAndPublicKeyMisMatch), e)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureDeformatter"))); } switch (algorithm) { case SignedXml.XmlDsigDSAUrl: // Ensure that we have a DSA algorithm object. DSA dsa = (this.PublicKey as DSA); if (dsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PublicKeyNotDSA))); } return(new DSASignatureDeformatter(dsa)); case SignedXml.XmlDsigRSASHA1Url: case SecurityAlgorithms.RsaSha256Signature: // Ensure that we have an RSA algorithm object. RSA rsa = (this.PublicKey as RSA); if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PublicKeyNotRSA))); } return(new RSAPKCS1SignatureDeformatter(rsa)); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm))); } }
protected static void InvalidDeformatterArguments(AsymmetricSignatureDeformatter deformatter) { Assert.Throws<ArgumentNullException>(() => deformatter.SetKey(null)); Assert.Throws<ArgumentNullException>(() => deformatter.VerifySignature((byte[])null, new byte[] { 0, 1, 2 })); Assert.Throws<CryptographicUnexpectedOperationException>(() => deformatter.VerifySignature(new byte[] { 0, 1, 2 }, new byte[] { 0, 1, 2 })); }
/// <summary> /// Initializes a new instance of the <see cref="AsymmetricSignatureProvider"/> class used to create and verify signatures. /// </summary> /// <param name="key"> /// The <see cref="AsymmetricSecurityKey"/> that will be used for cryptographic operations. /// </param> /// <param name="algorithm"> /// The signature algorithm to apply. /// </param> /// <param name="willCreateSignatures"> /// If this <see cref="AsymmetricSignatureProvider"/> is required to create signatures then set this to true. /// <para> /// Creating signatures requires that the <see cref="AsymmetricSecurityKey"/> has access to a private key. /// Verifying signatures (the default), does not require access to the private key. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// 'key' is null. /// </exception> /// <exception cref="ArgumentNullException"> /// 'algorithm' is null. /// </exception> /// <exception cref="ArgumentException"> /// 'algorithm' contains only whitespace. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// willCreateSignatures is true and <see cref="AsymmetricSecurityKey"/>.KeySize is less than <see cref="SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <see cref="AsymmetricSecurityKey"/>.KeySize is less than <see cref="SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying"/>. Note: this is always checked. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetHashAlgorithmForSignature"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetHashAlgorithmForSignature"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureFormatter"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureFormatter"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureDeformatter"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureDeformatter"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSignatureFormatter.SetHashAlgorithm"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSignatureDeformatter.SetHashAlgorithm"/> throws. /// </exception> public AsymmetricSignatureProvider(AsymmetricSecurityKey key, string algorithm, bool willCreateSignatures = false) { if (key == null) { throw new ArgumentNullException("key"); } if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (string.IsNullOrWhiteSpace(algorithm)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "algorithm")); } if (willCreateSignatures) { if (key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10631, key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning)); } } if (key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10630, key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying)); } this.key = key; try { this.hash = this.key.GetHashAlgorithmForSignature(algorithm); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10618, algorithm, this.key.ToString(), ex), ex); } if (this.hash == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10611, algorithm, this.key.ToString())); } if (willCreateSignatures) { try { this.formatter = this.key.GetSignatureFormatter(algorithm); this.formatter.SetHashAlgorithm(this.hash.GetType().ToString()); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10614, algorithm, this.key.ToString(), ex), ex); } if (this.formatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10615, algorithm, this.key.ToString())); } } try { this.deformatter = this.key.GetSignatureDeformatter(algorithm); this.deformatter.SetHashAlgorithm(this.hash.GetType().ToString()); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10616, algorithm, this.key.ToString(), ex), ex); } if (this.deformatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10617, algorithm, this.key.ToString())); } }
/// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } }