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)); }
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 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()); }
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 Formatter() { SignatureDescription sig = new SignatureDescription(); DSA dsa = DSA.Create(); // Formatter with all properties null AssertExtensions.Throws <ArgumentNullException>("name", () => sig.CreateFormatter(dsa)); // Formatter with invalid FormatterAlgorithm property AsymmetricSignatureFormatter fmt = null; sig.FormatterAlgorithm = "DSA"; Assert.ThrowsAny <Exception>(() => fmt = sig.CreateFormatter(dsa)); // Formatter with valid FormatterAlgorithm property sig.FormatterAlgorithm = "DSASignatureFormatter"; Assert.Throws <NullReferenceException>(() => sig.CreateFormatter(dsa)); // Deformatter with valid DeformatterAlgorithm property sig.KeyAlgorithm = "DSA"; sig.DigestAlgorithm = "SHA1"; sig.FormatterAlgorithm = "DSASignatureFormatter"; Assert.Throws <NullReferenceException>(() => sig.CreateFormatter(dsa)); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.IdentityModel.Tokens.AsymmetricSignatureProvider" /> class used to create and verify signatures. /// </summary> /// <param name="key"> /// The <see cref="T:System.IdentityModel.Tokens.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="T:System.IdentityModel.Tokens.AsymmetricSignatureProvider" /> is required to create signatures then set this to true. /// <para> /// Creating signatures requires that the <see cref="T:System.IdentityModel.Tokens.AsymmetricSecurityKey" /> has access to a private key. /// Verifying signatures (the default), does not require access to the private key. /// </para> /// </param> /// <exception cref="T:System.ArgumentNullException"> /// 'key' is null. /// </exception> /// <exception cref="T:System.ArgumentNullException"> /// 'algorithm' is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// 'algorithm' contains only whitespace. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// willCreateSignatures is true and <see cref="T:System.IdentityModel.Tokens.AsymmetricSecurityKey" />.KeySize is less than <see cref="P:System.IdentityModel.Tokens.SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning" />. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <see cref="T:System.IdentityModel.Tokens.AsymmetricSecurityKey" />.KeySize is less than <see cref="P:System.IdentityModel.Tokens.SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying" />. Note: this is always checked. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetHashAlgorithmForSignature(System.String)" /> throws. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetHashAlgorithmForSignature(System.String)" /> returns null. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetSignatureFormatter(System.String)" /> throws. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetSignatureFormatter(System.String)" /> returns null. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetSignatureDeformatter(System.String)" /> throws. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.IdentityModel.Tokens.AsymmetricSecurityKey.GetSignatureDeformatter(System.String)" /> returns null. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.Security.Cryptography.AsymmetricSignatureFormatter.SetHashAlgorithm(System.String)" /> throws. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// Is thrown if the <see cref="M:System.Security.Cryptography.AsymmetricSignatureDeformatter.SetHashAlgorithm(System.String)" /> throws. /// </exception> public AsymmetricSignatureProvider( AsymmetricSecurityKey key, string algorithm, bool willCreateSignatures = false) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (algorithm == null) { throw new ArgumentNullException(nameof(algorithm)); } if (string.IsNullOrWhiteSpace(algorithm)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "IDX10002: The parameter '{0}' cannot be 'null' or a string containing only whitespace.", nameof(algorithm))); } if (willCreateSignatures && key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning) { throw new ArgumentOutOfRangeException(nameof(key), key.KeySize, string.Format(CultureInfo.InvariantCulture, "IDX10631: The '{0}' for verifying cannot be smaller than '{1}' bits.", key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning)); } if (key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying) { throw new ArgumentOutOfRangeException(nameof(key), key.KeySize, string.Format(CultureInfo.InvariantCulture, "IDX10630: The '{0}' for signing cannot be smaller than '{1}' bits.", key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying)); } try { hash = key.GetHashAlgorithmForSignature(algorithm); } catch (Exception ex) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10618: AsymmetricSecurityKey.GetHashAlgorithmForSignature( '{0}' ) threw an exception.\nAsymmetricSecurityKey: '{1}'\nSignatureAlgorithm: '{0}', check to make sure the SignatureAlgorithm is supported.\nException: '{2}'.", algorithm, key.ToString(), ex), ex); } if (hash == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10611: AsymmetricSecurityKey.GetHashAlgorithmForSignature( '{0}' ) returned null.\nKey: '{1}'\nSignatureAlgorithm: '{0}'", algorithm, key.ToString())); } if (willCreateSignatures) { try { formatter = key.GetSignatureFormatter(algorithm); formatter?.SetHashAlgorithm(hash.GetType().ToString()); } catch (Exception ex) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10614: AsymmetricSecurityKey.GetSignatureFormater( '{0}' ) threw an exception.\nKey: '{1}'\nSignatureAlgorithm: '{0}', check to make sure the SignatureAlgorithm is supported.\nException:'{2}'.\nIf you only need to verify signatures the parameter 'willBeUseForSigning' should be false if the private key is not be available.", algorithm, key.ToString(), ex), ex); } if (formatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10615: AsymmetricSecurityKey.GetSignatureFormater( '{0}' ) returned null.\nKey: '{1}'\nSignatureAlgorithm: '{0}', check to make sure the SignatureAlgorithm is supported.", algorithm, key.ToString())); } } try { deformatter = key.GetSignatureDeformatter(algorithm); deformatter?.SetHashAlgorithm(hash.GetType().ToString()); } catch (Exception ex) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10616: AsymmetricSecurityKey.GetSignatureDeformatter( '{0}' ) threw an exception.\nKey: '{1}'\nSignatureAlgorithm: '{0}, check to make sure the SignatureAlgorithm is supported.'\nException:'{2}'.", algorithm, key.ToString(), ex), ex); } if (deformatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "IDX10617: AsymmetricSecurityKey.GetSignatureDeFormater( '{0}' ) returned null.\nKey: '{1}'\nSignatureAlgorithm: '{0}', check to make sure the SignatureAlgorithm is supported.", algorithm, key.ToString())); } }
protected static void InvalidFormatterArguments(AsymmetricSignatureFormatter formatter) { Assert.Throws<ArgumentNullException>(() => formatter.SetKey(null)); Assert.Throws<ArgumentNullException>(() => formatter.CreateSignature((byte[])null)); Assert.Throws<CryptographicUnexpectedOperationException>(() => formatter.CreateSignature(new byte[] { 0, 1, 2, 3 })); }
/// <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> /// Signs data. /// </summary> /// <param name="value">Data to be signed.</param> /// <returns>Signed data.</returns> /// <exception cref="ArgumentNullException">The argument 'value' is null.</exception> /// <exception cref="ArgumentException">The argument 'value' contains zero bytes.</exception> /// <exception cref="InvalidOperationException">The SigningKey is null.</exception> /// <exception cref="NotSupportedException">The platform does not support the requested algorithm.</exception> /// <exception cref="InvalidOperationException">The SigningKey is null, is not an RSACryptoServiceProvider, or does not contain a private key.</exception> /// <remarks>The SigningKey must include the private key in order to sign.</remarks> public override byte[] Encode(byte[] value) { if (null == value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (0 == value.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID6044)); } RSA signingKey = SigningKey; RSACryptoServiceProvider rsaCryptoServiceProvider = signingKey as RSACryptoServiceProvider; if (null == signingKey || null == rsaCryptoServiceProvider) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6042)); } if (rsaCryptoServiceProvider.PublicOnly) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6046)); } // Compute the signature byte[] signature; using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(HashName)) { try { hash.ComputeHash(value); AsymmetricSignatureFormatter signer = GetSignatureFormatter(signingKey); if (isSha256()) { signature = CryptoHelper.CreateSignatureForSha256(signer, hash); } else { signature = signer.CreateSignature(hash); } } // Not all algorithms are supported on all OS catch (CryptographicException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID6035, HashName, signingKey.GetType().FullName), e)); } } // Get the signature length as a big-endian integer byte[] signatureLength = BitConverter.GetBytes(signature.Length); // Assemble the message ... int currentIndex = 0; byte[] message = new byte[signatureLength.Length + signature.Length + value.Length]; // SignatureLength : 4-byte big endian integer Array.Copy(signatureLength, 0, message, currentIndex, signatureLength.Length); currentIndex += signatureLength.Length; // Signature : Octet stream, length is SignatureLength Array.Copy(signature, 0, message, currentIndex, signature.Length); currentIndex += signature.Length; // CookieValue : Octet stream, remainder of message Array.Copy(value, 0, message, currentIndex, value.Length); return(message); }
public FaultingAsymmetricSecurityKey(AsymmetricSecurityKey key = null, AsymmetricAlgorithm agorithm = null, AsymmetricSignatureDeformatter deformatter = null, AsymmetricSignatureFormatter formatter = null, HashAlgorithm hash = null, bool hasPrivateKey = false) { Key = key; }
internal static byte[] CreateSignatureForSha256(AsymmetricSignatureFormatter formatter, HashAlgorithm hash) { return(formatter.CreateSignature(hash)); }
public void Formatter() { AsymmetricSignatureFormatter fmt = null; // Formatter with all properties null try { fmt = sig.CreateFormatter(dsa); Fail("Expected ArgumentNullException but got none"); } catch (ArgumentNullException) { // this is what we expect } catch (Exception e) { Fail("Expected ArgumentNullException but got: " + e.ToString()); } // Formatter with invalid FormatterAlgorithm property sig.FormatterAlgorithm = "DSA"; try { fmt = sig.CreateFormatter(dsa); Fail("Expected InvalidCastException but got none"); } catch (InvalidCastException) { // this is what we expect } catch (Exception e) { Fail("Expected InvalidCastException but got: " + e.ToString()); } // Formatter with valid FormatterAlgorithm property sig.FormatterAlgorithm = "DSASignatureFormatter"; try { fmt = sig.CreateFormatter(dsa); Fail("Expected NullReferenceException but got none"); } catch (NullReferenceException) { // this is what we expect } catch (Exception e) { Fail("Expected NullReferenceException but got: " + e.ToString()); } // Deformatter with valid DeformatterAlgorithm property sig.KeyAlgorithm = "DSA"; sig.DigestAlgorithm = "SHA1"; sig.FormatterAlgorithm = "DSASignatureFormatter"; try { fmt = sig.CreateFormatter(dsa); Fail("Expected NullReferenceException but got none"); } catch (NullReferenceException) { // this is what we expect } catch (Exception e) { Fail("Expected NullReferenceException but got: " + e.ToString()); } }
protected static void InvalidFormatterArguments(AsymmetricSignatureFormatter formatter) { Assert.Throws <ArgumentNullException>(() => formatter.SetKey(null)); Assert.Throws <ArgumentNullException>(() => formatter.CreateSignature((byte[])null)); Assert.Throws <CryptographicUnexpectedOperationException>(() => formatter.CreateSignature(new byte[] { 0, 1, 2, 3 })); }
/// <summary>Gets the formatter algorithm for the digital signature.</summary> /// <param name="algorithm">The formatter algorithm for the digital signature to get an instance of.</param> /// <returns>An <see cref="T:System.Security.Cryptography.AsymmetricSignatureDeformatter" /> that represents the formatter algorithm for the digital signature.</returns> /// <exception cref="T:System.NotSupportedException">The X.509 certificate specified in the constructor does not have a private key.-or- /// <paramref name="algorithm" /> is <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigDSAUrl" /> and the private 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 private 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 AsymmetricSignatureFormatter GetSignatureFormatter( string algorithm) { if (this.PrivateKey == null) { throw new NotSupportedException("MissingPrivateKey"); } if (string.IsNullOrEmpty(algorithm)) { throw new ArgumentNullException(nameof(algorithm)); } AsymmetricAlgorithm key = X509AsymmetricSecurityKey.LevelUpRsa(this.PrivateKey, algorithm); object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmFromConfig != null) { SignatureDescription signatureDescription = algorithmFromConfig as SignatureDescription; if (signatureDescription != null) { return(signatureDescription.CreateFormatter(key)); } try { AsymmetricSignatureFormatter signatureFormatter = algorithmFromConfig as AsymmetricSignatureFormatter; if (signatureFormatter != null) { signatureFormatter.SetKey(key); return(signatureFormatter); } } catch (InvalidCastException ex) { throw new NotSupportedException("AlgorithmAndPrivateKeyMisMatch", (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") { if (algorithm == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") { RSA rsa = key as RSA; if (rsa == null) { throw new NotSupportedException("PrivateKeyNotRSA"); } return((AsymmetricSignatureFormatter) new RSAPKCS1SignatureFormatter((AsymmetricAlgorithm)rsa)); } throw new NotSupportedException("UnsupportedCryptoAlgorithm"); } RSA privateKey = this.PrivateKey as RSA; if (privateKey == null) { throw new NotSupportedException("PrivateKeyNotRSA"); } return((AsymmetricSignatureFormatter) new RSAPKCS1SignatureFormatter((AsymmetricAlgorithm)privateKey)); } DSA privateKey1 = this.PrivateKey as DSA; if (privateKey1 == null) { throw new NotSupportedException("PrivateKeyNotDSA"); } return((AsymmetricSignatureFormatter) new DSASignatureFormatter((AsymmetricAlgorithm)privateKey1)); }
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-SHA1 if (SignedInfo.SignatureMethod == null) { SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; } } //begin: gost else if (key is Gost3410) { SignedInfo.SignatureMethod = XmlDsigGost3410Url; } else if (key is Gost3410_2012_256) { SignedInfo.SignatureMethod = XmlDsigGost3410_2012_256Url; } else if (key is Gost3410_2012_512) { SignedInfo.SignatureMethod = XmlDsigGost3410_2012_512Url; } //end: gost 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); } byte[] hashvalue = GetC14NDigest(hashAlg); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); SignedXmlDebugLog.LogSigning(this, key, signatureDescription, hashAlg, asymmetricSignatureFormatter); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); }
internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { if (InformationLoggingEnabled) { string data = string.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningAsymmetric"), new object[] { GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name }); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, data); } }
/// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.ComputeSignature"]/*' /> public void ComputeSignature() { BuildDigestedReferences(); // Load the key AsymmetricAlgorithm key; if (SigningKey != null) { key = SigningKey; } else { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed")); } 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 (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")); } // Compute the hash of the SignedInfo object XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement; // Add non default namespaces in scope if (m_namespaces != null) { foreach (XmlNode attrib in m_namespaces) { string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); // Skip the attribute if one with the same qualified name already exists if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty)) { continue; } XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name); nsattrib.Value = ((XmlNode)attrib).Value; signedInfo.SetAttributeNode(nsattrib); } } #if _DEBUG if (debug) { Console.WriteLine("computed signedInfo: "); Console.WriteLine(signedInfo.OuterXml); } #endif TransformChain tc = new TransformChain(); Transform c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod); if (c14nMethodTransform == null) { throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod)); } tc.Add(c14nMethodTransform); string strBaseUri = (m_containingDocument == null ? null : m_containingDocument.BaseURI); XmlResolver resolver = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri)); Stream hashInput = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri); // See if there is a signature description class defined through the Config file SignatureDescription signatureDescription = (SignatureDescription)CryptoConfig.CreateFromName(SignedInfo.SignatureMethod); if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } // calculate the hash HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } byte[] hashValue = hashAlg.ComputeHash(hashInput); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); #if _DEBUG if (debug) { Console.WriteLine("computed hash value: " + Convert.ToBase64String(hashValue)); } #endif }
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm) { if (this.PrivateKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("MissingPrivateKey"))); } 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.CreateFormatter(this.PrivateKey)); } try { AsymmetricSignatureFormatter formatter = algorithmFromConfig as AsymmetricSignatureFormatter; if (formatter != null) { formatter.SetKey(this.PrivateKey); return(formatter); } } catch (InvalidCastException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("AlgorithmAndPrivateKeyMisMatch"), exception)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetSignatureFormatter" }))); } switch (algorithm) { case "http://www.w3.org/2000/09/xmldsig#dsa-sha1": { DSA privateKey = this.PrivateKey as DSA; if (privateKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PrivateKeyNotDSA"))); } return(new DSASignatureFormatter(privateKey)); } case "http://www.w3.org/2000/09/xmldsig#rsa-sha1": { RSA key = this.PrivateKey as RSA; if (key == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PrivateKeyNotRSA"))); } return(new RSAPKCS1SignatureFormatter(key)); } case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256": { RSACryptoServiceProvider provider = this.PrivateKey as RSACryptoServiceProvider; if (provider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PrivateKeyNotRSA"))); } CspParameters parameters = new CspParameters { ProviderType = 0x18, KeyContainerName = provider.CspKeyContainerInfo.KeyContainerName, KeyNumber = (int)provider.CspKeyContainerInfo.KeyNumber }; if (provider.CspKeyContainerInfo.MachineKeyStore) { parameters.Flags = CspProviderFlags.UseMachineKeyStore; } return(new RSAPKCS1SignatureFormatter(new RSACryptoServiceProvider(parameters))); } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedCryptoAlgorithm", new object[] { algorithm }))); }
/// <summary> /// Log the computation of a signature value when signing with an asymmetric algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key used for signing</param> /// <param name="signatureDescription">signature description being used to create the signature</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hash != null, "hash != null"); Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } }
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm) { // One can sign only if the private key is present. if (this.PrivateKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.MissingPrivateKey))); } if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.GetString(SR.EmptyOrNullArgumentString, "algorithm")); } // We support: // XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; // XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; // RsaSha256Signature = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; AsymmetricAlgorithm privateKey = LevelUpRsa(this.PrivateKey, algorithm); object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { SignatureDescription description = algorithmObject as SignatureDescription; if (description != null) { return(description.CreateFormatter(privateKey)); } try { AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter; if (asymmetricSignatureFormatter != null) { asymmetricSignatureFormatter.SetKey(privateKey); return(asymmetricSignatureFormatter); } } catch (InvalidCastException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.AlgorithmAndPrivateKeyMisMatch), e)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureFormatter"))); } switch (algorithm) { case SignedXml.XmlDsigDSAUrl: // Ensure that we have a DSA algorithm object. DSA dsa = (this.PrivateKey as DSA); if (dsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotDSA))); } return(new DSASignatureFormatter(dsa)); case SignedXml.XmlDsigRSASHA1Url: // Ensure that we have an RSA algorithm object. RSA rsa = (this.PrivateKey as RSA); if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotRSA))); } return(new RSAPKCS1SignatureFormatter(rsa)); case SecurityAlgorithms.RsaSha256Signature: // Ensure that we have an RSA algorithm object. RSA rsaSha256 = (privateKey as RSA); if (rsaSha256 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotRSA))); } return(new RSAPKCS1SignatureFormatter(rsaSha256)); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm))); } }
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm) { // One can sign only if the private key is present. if (this.PrivateKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.MissingPrivateKey))); } if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.GetString(SR.EmptyOrNullArgumentString, "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"; object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { SignatureDescription description = algorithmObject as SignatureDescription; if (description != null) { return(description.CreateFormatter(this.PrivateKey)); } try { AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter; if (asymmetricSignatureFormatter != null) { asymmetricSignatureFormatter.SetKey(this.PrivateKey); return(asymmetricSignatureFormatter); } } catch (InvalidCastException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.AlgorithmAndPrivateKeyMisMatch), e)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureFormatter"))); } switch (algorithm) { case SignedXml.XmlDsigDSAUrl: // Ensure that we have a DSA algorithm object. DSA dsa = (this.PrivateKey as DSA); if (dsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotDSA))); } return(new DSASignatureFormatter(dsa)); case SignedXml.XmlDsigRSASHA1Url: // Ensure that we have an RSA algorithm object. RSA rsa = (this.PrivateKey as RSA); if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotRSA))); } return(new RSAPKCS1SignatureFormatter(rsa)); case SecurityAlgorithms.RsaSha256Signature: // Ensure that we have an RSA algorithm object. RSACryptoServiceProvider rsa_prov_full = (this.PrivateKey as RSACryptoServiceProvider); if (rsa_prov_full == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PrivateKeyNotRSA))); } CspParameters csp = new CspParameters(); csp.ProviderType = 24; csp.KeyContainerName = rsa_prov_full.CspKeyContainerInfo.KeyContainerName; csp.KeyNumber = (int)rsa_prov_full.CspKeyContainerInfo.KeyNumber; if (rsa_prov_full.CspKeyContainerInfo.MachineKeyStore) { csp.Flags = CspProviderFlags.UseMachineKeyStore; } csp.Flags |= CspProviderFlags.UseExistingKey; return(new RSAPKCS1SignatureFormatter(new RSACryptoServiceProvider(csp))); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm))); } }