// Create a SignatureDescription for RSA encryption. private static SignatureDescription CreateRSAPKCS1Signature() { //<Snippet1> SignatureDescription signatureDescription = new SignatureDescription(); //</Snippet1> // Set the key algorithm property for RSA encryption. //<Snippet7> signatureDescription.KeyAlgorithm = "System.Security.Cryptography.RSACryptoServiceProvider"; //</Snippet7> // Set the digest algorithm for RSA encryption using the // SHA1 provider. //<Snippet6> signatureDescription.DigestAlgorithm = "System.Security.Cryptography.SHA1CryptoServiceProvider"; //</Snippet6> // Set the formatter algorithm with the RSAPKCS1 formatter. //<Snippet9> signatureDescription.FormatterAlgorithm = "System.Security.Cryptography.RSAPKCS1SignatureFormatter"; //</Snippet9> // Set the formatter algorithm with the RSAPKCS1 deformatter. //<Snippet8> signatureDescription.DeformatterAlgorithm = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter"; //</Snippet8> return(signatureDescription); }
internal new void ComputeSignature() { // BuildDigestedReferences(); var methodInfo = typeof(SignedXml).GetMethod("BuildDigestedReferences", BindingFlags.Instance | BindingFlags.NonPublic); methodInfo.Invoke(this, null); SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; // 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("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } // byte[] hashvalue = GetC14NDigest(hashAlg); var methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic); var hashvalue = (byte[])methodInfo2.Invoke(this, new object[] { hashAlg }); m_signature.SignatureValue = CreateSignature(hashvalue).GetAwaiter().GetResult(); }
// Create a SignatureDescription using a constructed SecurityElement for // DSA encryption. private static SignatureDescription CreateDSASignature() { //<Snippet3> SecurityElement securityElement = new SecurityElement("DSASignature"); // Create new security elements for the four algorithms. securityElement.AddChild(new SecurityElement( "Key", "System.Security.Cryptography.DSACryptoServiceProvider")); securityElement.AddChild(new SecurityElement( "Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider")); securityElement.AddChild(new SecurityElement( "Formatter", "System.Security.Cryptography.DSASignatureFormatter")); securityElement.AddChild(new SecurityElement( "Deformatter", "System.Security.Cryptography.DSASignatureDeformatter")); SignatureDescription signatureDescription = new SignatureDescription(securityElement); //</Snippet3> return(signatureDescription); }
internal static bool IsAsymmetricAlgorithm(string algorithm) { object algorithmFromConfig = null; string str; try { algorithmFromConfig = GetAlgorithmFromConfig(algorithm); } catch (InvalidOperationException) { algorithmFromConfig = null; } if (algorithmFromConfig != null) { AsymmetricAlgorithm algorithm2 = algorithmFromConfig as AsymmetricAlgorithm; SignatureDescription description = algorithmFromConfig as SignatureDescription; if ((algorithm2 == null) && (description == null)) { return(false); } return(true); } if (((str = algorithm) == null) || ((!(str == "http://www.w3.org/2000/09/xmldsig#dsa-sha1") && !(str == "http://www.w3.org/2000/09/xmldsig#rsa-sha1")) && ((!(str == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") && !(str == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p")) && !(str == "http://www.w3.org/2001/04/xmlenc#rsa-1_5")))) { return(false); } return(true); }
private async Task <bool> CheckSignedInfo() { SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } //byte[] hashval = GetC14NDigest(hashAlgorithm); var methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic); var hashvalue = (byte[])methodInfo2.Invoke(this, new object[] { hashAlgorithm }); var result = await keyClient.VerifyAsync(keyvaultUri, keyIdentifier, keyVersion, Microsoft.Azure.KeyVault.WebKey.JsonWebKeySignatureAlgorithm.RS256, hashvalue, m_signature.SignatureValue); return((bool)result.Value); }
internal new void ComputeSignature() { var customerSigner = new CustomSigner(); CryptoConfig.AddAlgorithm(typeof(cli_exakvdocsign.RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); var methodInfo = typeof(SignedXml).GetMethod("BuildDigestedReferences", BindingFlags.Instance | BindingFlags.NonPublic); methodInfo.Invoke(this, null); SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; //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("Cryptography_Xml_SignatureDescriptionNotCreated"); } var hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } var methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic); var hashvalue = (byte[])methodInfo2.Invoke(this, new object[] { hashAlg }); m_signature.SignatureValue = customerSigner.Sign(hashvalue);; }
public void Constructor_Default() { // empty constructor SignatureDescription sig = new SignatureDescription(); AssertNotNull("SignatureDescription()", sig); }
public static Boolean Test() { Boolean bRes = true; SecurityElement el = new SecurityElement("whatever"); // el.Text = "<Key>RSA</Key><Digest>SHA1</Digest><Formatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Formatter><Deformatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Deformatter>"; SecurityElement el_key = new SecurityElement("Key"); el_key.Text = "RSA"; SecurityElement el_digest = new SecurityElement("Digest"); el_digest.Text = "SHA1"; SecurityElement el_form = new SecurityElement("Formatter"); el_form.Text = "System.Security.Cryptography.RSAPKCS1SignatureFormatter"; SecurityElement el_deform = new SecurityElement("Deformatter"); el_deform.Text = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter"; el.AddChild(el_key); el.AddChild(el_digest); el.AddChild(el_form); el.AddChild(el_deform); SignatureDescription sd_empty = new SignatureDescription(); SignatureDescription sd = new SignatureDescription(el); Console.WriteLine(sd.CreateDigest()); Console.WriteLine(sd.CreateFormatter(RSA.Create())); Console.WriteLine(sd.CreateDeformatter(RSA.Create())); return bRes; }
public byte[] ComputeDigest() { BuildDigestedReferences(); // Check the signature algorithm if (SignedInfo.SignatureMethod == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = GostCryptoConfig.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")); } return(GetC14NDigest(hashAlg)); }
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 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 Properties() { const string invalid = "invalid"; SignatureDescription sig = new SignatureDescription(); sig.DeformatterAlgorithm = invalid; Assert.NotNull(sig.DeformatterAlgorithm); Assert.Equal(invalid, sig.DeformatterAlgorithm); sig.DeformatterAlgorithm = null; Assert.Null(sig.DeformatterAlgorithm); sig.DigestAlgorithm = invalid; Assert.NotNull(sig.DigestAlgorithm); Assert.Equal(invalid, sig.DigestAlgorithm); sig.DigestAlgorithm = null; Assert.Null(sig.DigestAlgorithm); sig.FormatterAlgorithm = invalid; Assert.NotNull(sig.FormatterAlgorithm); Assert.Equal(invalid, sig.FormatterAlgorithm); sig.FormatterAlgorithm = null; Assert.Null(sig.FormatterAlgorithm); sig.KeyAlgorithm = invalid; Assert.NotNull(sig.KeyAlgorithm); Assert.Equal(invalid, sig.KeyAlgorithm); sig.KeyAlgorithm = null; Assert.Null(sig.KeyAlgorithm); }
/// <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 override HashAlgorithm GetHashAlgorithmForSignature(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.CreateDigest()); } HashAlgorithm algorithm2 = algorithmFromConfig as HashAlgorithm; if (algorithm2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedCryptoAlgorithm", new object[] { algorithm }))); } return(algorithm2); } switch (algorithm) { case "http://www.w3.org/2000/09/xmldsig#rsa-sha1": return(CryptoHelper.NewSha1HashAlgorithm()); case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256": return(CryptoHelper.NewSha256HashAlgorithm()); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetHashAlgorithmForSignature" }))); }
public static Boolean Test() { Boolean bRes = true; SecurityElement el = new SecurityElement("whatever"); // el.Text = "<Key>RSA</Key><Digest>SHA1</Digest><Formatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Formatter><Deformatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Deformatter>"; SecurityElement el_key = new SecurityElement("Key"); el_key.Text = "RSA"; SecurityElement el_digest = new SecurityElement("Digest"); el_digest.Text = "SHA1"; SecurityElement el_form = new SecurityElement("Formatter"); el_form.Text = "System.Security.Cryptography.RSAPKCS1SignatureFormatter"; SecurityElement el_deform = new SecurityElement("Deformatter"); el_deform.Text = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter"; el.AddChild(el_key); el.AddChild(el_digest); el.AddChild(el_form); el.AddChild(el_deform); SignatureDescription sd_empty = new SignatureDescription(); SignatureDescription sd = new SignatureDescription(el); Console.WriteLine(sd.CreateDigest()); Console.WriteLine(sd.CreateFormatter(RSA.Create())); Console.WriteLine(sd.CreateDeformatter(RSA.Create())); return(bRes); }
/// <summary>Gets a cryptographic algorithm that generates a hash for a digital signature.</summary> /// <param name="algorithm">The hash algorithm.</param> /// <returns>A <see cref="T:System.Security.Cryptography.HashAlgorithm" /> that generates hashes for digital signatures.</returns> /// <exception cref="T:System.NotSupportedException"> /// <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 HashAlgorithm GetHashAlgorithmForSignature(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.CreateDigest()); } HashAlgorithm hashAlgorithm = algorithmFromConfig as HashAlgorithm; if (hashAlgorithm != null) { return(hashAlgorithm); } throw new CryptographicException("UnsupportedAlgorithmForCryptoOperation"); } if (algorithm == "http://www.w3.org/2000/09/xmldsig#dsa-sha1" || algorithm == "http://www.w3.org/2000/09/xmldsig#rsa-sha1") { return(CryptoHelper.NewSha1HashAlgorithm()); } if (algorithm == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") { return(CryptoHelper.NewSha256HashAlgorithm()); } throw new NotSupportedException("UnsupportedCryptoAlgorithm"); }
/// <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); } }
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)); }
private void SignXml(string inputFile, string outputFile) { try { Licensing.ShowDemoMessage(); DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate); XmlDocument xmlDocument = new XmlDocument() { PreserveWhitespace = this.RemoveWhitespaces }; xmlDocument.Load(inputFile); SignedXml signedXml = new SignedXml(xmlDocument); RSACryptoServiceProvider rSACryptoServiceProvider = null; try { string xmlString = this.DigitalSignatureCertificate.PrivateKey.ToXmlString(true); rSACryptoServiceProvider = new RSACryptoServiceProvider(new CspParameters(24)) { PersistKeyInCsp = false }; rSACryptoServiceProvider.FromXmlString(xmlString); signedXml.SigningKey = rSACryptoServiceProvider; } catch { rSACryptoServiceProvider = this.DigitalSignatureCertificate.PrivateKey as RSACryptoServiceProvider; signedXml.SigningKey = rSACryptoServiceProvider; } signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; if (this.IncludeKeyInfo || this.IncludeSignatureCertificate) { KeyInfo keyInfos = new KeyInfo(); if (this.IncludeKeyInfo) { keyInfos.AddClause(new RSAKeyValue(rSACryptoServiceProvider)); } if (this.IncludeSignatureCertificate) { keyInfos.AddClause(new KeyInfoX509Data(this.DigitalSignatureCertificate.GetRawCertData())); } signedXml.KeyInfo = keyInfos; } Reference reference = new Reference(); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.Uri = ""; reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.AddReference(reference); signedXml.ComputeSignature(); SignatureDescription signatureDescription = new SignatureDescription(); XmlElement xml = signedXml.GetXml(); xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xml, true)); xmlDocument.Save(outputFile); } catch { throw; } }
public void Constructor_SecurityElement_Empty() { // (empty) SecurityElement constructor SecurityElement se = new SecurityElement("xml"); SignatureDescription sig = new SignatureDescription(se); AssertNotNull("SignatureDescription(SecurityElement)", sig); }
public void Constructor_Default() { SignatureDescription sig = new SignatureDescription(); Assert.Null(sig.KeyAlgorithm); Assert.Null(sig.DigestAlgorithm); Assert.Null(sig.FormatterAlgorithm); Assert.Null(sig.DeformatterAlgorithm); }
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); } }
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 Constructor_SecurityElement_Empty() { SecurityElement se = new SecurityElement("xml"); SignatureDescription sig = new SignatureDescription(se); Assert.Null(sig.KeyAlgorithm); Assert.Null(sig.DigestAlgorithm); Assert.Null(sig.FormatterAlgorithm); Assert.Null(sig.DeformatterAlgorithm); }
/// <summary> /// /// </summary> /// <param name="prefix"></param> public void ComputeSignature(string prefix) { this.BuildDigestedReferences(); SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; HashAlgorithm hash = description.CreateDigest(); GetDigest(hash, prefix); this.m_signature.SignatureValue = description.CreateFormatter(this.SigningKey).CreateSignature(hash); }
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 }))); }
void ComputeHash(out AsymmetricAlgorithm privateKey, out SignatureDescription description, out HashAlgorithm hash) { privateKey = this.Certificate.PrivateKey; description = CryptoConfig.CreateFromName(this.SHA1SignatureName) as SignatureDescription; if (description == null) { throw new CompactSignatureSecurityException(string.Format( CultureInfo.CurrentCulture, "Error creating SignatureDescription from the signature name {0}", this.SHA1SignatureName)); } hash = description.CreateDigest(); if (hash == null) { throw new CompactSignatureSecurityException(string.Format( CultureInfo.CurrentCulture, "Error creating HashAlgorithm from the signature name {0}", this.SHA1SignatureName)); } HashStream hashStream = this.TakeHashStream(hash); // Create the references StringBuilder sb = new StringBuilder(); if (!String.IsNullOrEmpty(this.InclusivePrefixesList)) { for (int i = 0; i < this.references.Count; i++) { sb.Append(string.Format(SignatureProcessor.ExtendedSignatureReferenceWithPrefixes, this.references[i].Id, this.InclusivePrefixesList, Convert.ToBase64String(this.references[i].Digest))); } } else { for (int i = 0; i < this.references.Count; i++) { sb.Append(string.Format(SignatureProcessor.ExtendedSignatureReferenceNoPrefixes, this.references[i].Id, Convert.ToBase64String(this.references[i].Digest))); } } string expandedSignature = string.Format( ExpandedSignatureScheleton, // Replace the references sb.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(expandedSignature); hashStream.Write(bytes, 0, bytes.Length); hashStream.FlushHash(); }
internal static HashAlgorithm CreateHashForAsymmetricSignature(string signatureMethod) { object algorithmObject = CryptoAlgorithms.GetAlgorithmFromConfig(signatureMethod); if (algorithmObject != null) { HashAlgorithm hashAlgorithm; SignatureDescription signatureDescription = algorithmObject as SignatureDescription; if (signatureDescription != null) { hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm != null) { return(hashAlgorithm); } } hashAlgorithm = algorithmObject as HashAlgorithm; if (hashAlgorithm != null) { return(hashAlgorithm); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidAsymmetricSignature, signatureMethod))); } switch (signatureMethod) { case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.DsaSha1Signature: if (SecurityUtilsEx.RequiresFipsCompliance) { return(new SHA1CryptoServiceProvider()); } else { return(new SHA1Managed()); } case SecurityAlgorithms.RsaSha256Signature: if (SecurityUtilsEx.RequiresFipsCompliance) { return(new SHA256CryptoServiceProvider()); } else { return(new SHA256Managed()); } default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnsupportedCryptoAlgorithm, signatureMethod))); } }
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); }
/// <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 void Constructor_SecurityElement_RSA() { SecurityElement se = new SecurityElement("RSASignature"); se.AddChild(new SecurityElement("Key", "System.Security.Cryptography.RSACryptoServiceProvider")); se.AddChild(new SecurityElement("Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider")); se.AddChild(new SecurityElement("Formatter", "System.Security.Cryptography.RSAPKCS1SignatureFormatter")); se.AddChild(new SecurityElement("Deformatter", "System.Security.Cryptography.RSAPKCS1SignatureDeformatter")); SignatureDescription sig = new SignatureDescription(se); Assert.Equal("System.Security.Cryptography.RSACryptoServiceProvider", sig.KeyAlgorithm); Assert.Equal("System.Security.Cryptography.SHA1CryptoServiceProvider", sig.DigestAlgorithm); Assert.Equal("System.Security.Cryptography.RSAPKCS1SignatureFormatter", sig.FormatterAlgorithm); Assert.Equal("System.Security.Cryptography.RSAPKCS1SignatureDeformatter", sig.DeformatterAlgorithm); }
public void Deformatter() { AsymmetricSignatureDeformatter def; SignatureDescription sig = new SignatureDescription(); DSA dsa = DSA.Create(); // Deformatter with all properties null Assert.Throws<ArgumentNullException>("name", () => sig.CreateDeformatter(dsa)); // Deformatter with invalid DeformatterAlgorithm property sig.DeformatterAlgorithm = "DSA"; Assert.ThrowsAny<Exception>(() => def = sig.CreateDeformatter(dsa)); // Deformatter with valid DeformatterAlgorithm property sig.DeformatterAlgorithm = "DSASignatureDeformatter"; Assert.Throws<NullReferenceException>(() => def = sig.CreateDeformatter(dsa)); // Deformatter with valid DeformatterAlgorithm property sig.KeyAlgorithm = "DSA"; sig.DigestAlgorithm = "SHA1"; sig.DeformatterAlgorithm = "DSASignatureDeformatter"; Assert.Throws<NullReferenceException>(() => def = sig.CreateDeformatter(dsa)); }
/// <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); } }
public void Digest() { bool rightClass = false; HashAlgorithm hash = null; SignatureDescription sig = new SignatureDescription(); // null hash Assert.Throws<ArgumentNullException>("name", () => hash = sig.CreateDigest()); sig.DigestAlgorithm = "SHA1"; hash = sig.CreateDigest(); Assert.NotNull(hash); rightClass = (hash.ToString().IndexOf(sig.DigestAlgorithm) > 0); Assert.True(rightClass, "CreateDigest(SHA1)"); sig.DigestAlgorithm = "MD5"; hash = sig.CreateDigest(); Assert.NotNull(hash); rightClass = (hash.ToString().IndexOf(sig.DigestAlgorithm) > 0); Assert.True(rightClass, "CreateDigest(MD5)"); sig.DigestAlgorithm = "SHA256"; hash = sig.CreateDigest(); Assert.NotNull(hash); rightClass = (hash.ToString().IndexOf(sig.DigestAlgorithm) > 0); Assert.True(rightClass, "CreateDigest(SHA256)"); sig.DigestAlgorithm = "SHA384"; hash = sig.CreateDigest(); Assert.NotNull(hash); rightClass = (hash.ToString().IndexOf(sig.DigestAlgorithm) > 0); Assert.True(rightClass, "CreateDigest(SHA384)"); sig.DigestAlgorithm = "SHA512"; hash = sig.CreateDigest(); Assert.NotNull(hash); rightClass = (hash.ToString().IndexOf(sig.DigestAlgorithm) > 0); Assert.True(rightClass, "CreateDigest(SHA512)"); sig.DigestAlgorithm = "bad"; hash = sig.CreateDigest(); Assert.Null(hash); }