public void Formatter() { AsymmetricSignatureFormatter fmt = null; // Formatter with all properties null try { fmt = sig.CreateFormatter(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()); } // Formatter with invalid FormatterAlgorithm property sig.FormatterAlgorithm = "DSA"; try { fmt = sig.CreateFormatter(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()); } // Formatter with valid FormatterAlgorithm property sig.FormatterAlgorithm = "DSASignatureFormatter"; try { fmt = sig.CreateFormatter(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.FormatterAlgorithm = "DSASignatureFormatter"; try { fmt = sig.CreateFormatter(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 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 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 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); }
/// <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 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); }
// Create a signature formatter for DSA encryption. public static AsymmetricSignatureFormatter CreateDSAFormatter(DSA dsa) { // Create a DSA signature formatter for encryption. SignatureDescription signatureDescription = new SignatureDescription(); signatureDescription.FormatterAlgorithm = "System.Security.Cryptography.DSASignatureFormatter"; AsymmetricSignatureFormatter asymmetricFormatter = signatureDescription.CreateFormatter(dsa); Console.WriteLine("\nCreated formatter : " + asymmetricFormatter.ToString()); return(asymmetricFormatter); }
public void ComputeSignature(string prefix) { this.BuildDigestedReferences(); AsymmetricAlgorithm signingKey = this.SigningKey; if (signingKey == null) { throw new CryptographicException("Cryptography_Xml_LoadKeyFailed"); } if (this.SignedInfo.SignatureMethod == null) { // SignatureMethodが未設定で、SigningKeyの種類によるデフォルト値を設定 if (signingKey is DSA) { // "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; this.SignedInfo.SignatureMethod = XmlDsigDSAUrl; } else if (signingKey is RSA) { // "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; this.SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; // "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; //this.SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; // "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; //this.SignedInfo.SignatureMethod = XmlDsigRSASHA384Url; // "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; //this.SignedInfo.SignatureMethod = XmlDsigRSASHA512Url; } else { throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed"); } } SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; if (description == null) { throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hash = description.CreateDigest(); if (hash == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } this.GetC14NDigest(hash, prefix); this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash); this.prefix = prefix; }
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)); }
public override AsymmetricSignatureFormatter GetSignatureFormatter(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.CreateFormatter(rsa)); } try { AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter; if (asymmetricSignatureFormatter != null) { asymmetricSignatureFormatter.SetKey(rsa); return(asymmetricSignatureFormatter); } } 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, nameof(GetSignatureFormatter)))); } switch (algorithm) { case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: // Ensure that we have an RSA algorithm object. return(new RSAPKCS1SignatureFormatter(this.rsa)); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation, algorithm, "GetSignatureFormatter"))); } }
public void ComputeSignature(string prefix) { this.BuildDigestedReferences(); AsymmetricAlgorithm signingKey = this.SigningKey; if (signingKey == null) { throw new CryptographicException("Cryptography_Xml_LoadKeyFailed"); } if (this.SignedInfo.SignatureMethod == null) { if (!(signingKey is DSA)) { if (!(signingKey is RSA)) { throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed"); } if (this.SignedInfo.SignatureMethod == null) { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } } else { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; } } SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; if (description == null) { throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hash = description.CreateDigest(); if (hash == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } this.GetC14NDigest(hash, prefix); this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash); }
public void ComputeSignature() { DigestReferences(); 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 SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; } else { throw new CryptographicException(SR.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(SR.Cryptography_Xml_SignatureDescriptionNotCreated); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } byte[] hashvalue = hashAlg.ComputeHash(SignedInfoTransformed()); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); }
public void ComputeSignature() { SignedXmlDebugLog.LogBeginSignatureComputation(this, this.m_context); this.BuildDigestedReferences(); AsymmetricAlgorithm signingKey = this.SigningKey; if (signingKey == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed")); } if (this.SignedInfo.SignatureMethod == null) { if (!(signingKey is DSA)) { if (!(signingKey is RSA)) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } if (this.SignedInfo.SignatureMethod == null) { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } } else { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; } } SignatureDescription signatureDescription = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } HashAlgorithm hash = signatureDescription.CreateDigest(); if (hash == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } this.GetC14NDigest(hash); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(signingKey); SignedXmlDebugLog.LogSigning(this, signingKey, signatureDescription, hash, asymmetricSignatureFormatter); this.m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hash); }
public void ComputeSignature(string prefix) { BuildDigestedReferences(); AsymmetricAlgorithm signingKey = SigningKey; if (signingKey == null) { throw new CryptographicException("Cryptography_Xml_LoadKeyFailed"); } if (SignedInfo.SignatureMethod == null) { if (!(signingKey is DSA)) { if (!(signingKey is RSA)) { throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed"); } if (SignedInfo.SignatureMethod == null) { SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; } } else { SignedInfo.SignatureMethod = XmlDsigDSAUrl; } } SignatureDescription description = CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (description == null) { throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hash = description.CreateDigest(); if (hash == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } GetC14NDigest(hash, prefix); m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash); }
public void ComputeSignature() { if (key != null) { // required before hashing DigestReferences(); SignatureDescription sd = GetSignatureDescription(signature.SignedInfo.SignatureMethod); // the hard part - C14Ning the KeyInfo byte[] hash = Hash(sd.DigestAlgorithm); AsymmetricSignatureFormatter signer = null; // in need for a CryptoConfig factory if (key is DSA) { signer = new DSASignatureFormatter(key); } else if (key is RSA) { signer = sd.CreateFormatter(key); //new RSAPKCS1SignatureFormatter(key); } if (signer != null) { if (sd.DigestAlgorithm == typeof(SHA1CryptoServiceProvider).FullName || sd.DigestAlgorithm == typeof(SHA1Cng).FullName) { signer.SetHashAlgorithm("SHA1"); } else if (sd.DigestAlgorithm == typeof(SHA256Managed).FullName || sd.DigestAlgorithm == typeof(SHA256Cng).FullName) { signer.SetHashAlgorithm("SHA256"); } else if (sd.DigestAlgorithm == typeof(SHA512Managed).FullName || sd.DigestAlgorithm == typeof(SHA512Cng).FullName) { signer.SetHashAlgorithm("SHA512"); } signature.SignatureValue = signer.CreateSignature(hash); } } }
private string SignHashOnServer(byte[] hash) { var certificate = CertificateHelper.GetCertificateByThumbprint(TestIntegrationClientServer.CERTIFICATE_THUMBPRINT); Assert.IsNotNull(certificate); var gost = (Gost3410CryptoServiceProvider)certificate.PrivateKey; var secureString = new SecureString(); foreach (var ch in TestIntegrationClientServer.PRIVATE_KEY_PASSWORD) { secureString.AppendChar(ch); } #pragma warning disable 612 SignatureDescription signDescr = (SignatureDescription)CryptoConfig.CreateFromName(CPSignedXml.XmlDsigGost3410UrlObsolete); #pragma warning restore 612 var base64String = Convert.ToBase64String(signDescr.CreateFormatter(gost).CreateSignature(hash)); return(base64String); }
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm) { string str; 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.rsa)); } try { AsymmetricSignatureFormatter formatter = algorithmFromConfig as AsymmetricSignatureFormatter; if (formatter != null) { formatter.SetKey(this.rsa); return(formatter); } } catch (InvalidCastException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("AlgorithmAndKeyMisMatch"), exception)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetSignatureFormatter" }))); } if (((str = algorithm) == null) || ((str != "http://www.w3.org/2000/09/xmldsig#rsa-sha1") && (str != "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetSignatureFormatter" }))); } return(new RSAPKCS1SignatureFormatter(this.rsa)); }
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 void Formatter() { SignatureDescription sig = new SignatureDescription(); DSA dsa = DSA.Create(); // Formatter with all properties null Assert.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)); }
public AsymmetricSignatureFormatter CreateFormatter() { return(SignatureDescription.CreateFormatter(Certificate.GetRSAPrivateKey())); }
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 }))); }
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))); } }
/// <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)); }
/// <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 static XmlDocument SignXmlFileSmev3(XmlDocument doc, X509Certificate2 certificate, string signingNodeId, bool assignDs, bool isAck = false, bool isSidebyside = false) { XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable); nsm.AddNamespace("ns", "urn://x-artefacts-smev-gov-ru/services/message-exchange/types/1.1"); nsm.AddNamespace("ns1", "urn://x-artefacts-smev-gov-ru/services/message-exchange/types/basic/1.1"); nsm.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); SignedXml sxml = new SignedXml(doc) { SigningKey = certificate.PrivateKey }; //=====================================================================================REFERENCE TRASFORMS Reference reference = new Reference { Uri = "#" + signingNodeId, #pragma warning disable 612 //Расчет хеш-суммы ГОСТ Р 34.11-94 http://www.w3.org/2001/04/xmldsig-more#gostr3411 DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete #pragma warning disable 612 }; XmlDsigExcC14NTransform excC14n = new XmlDsigExcC14NTransform(); reference.AddTransform(excC14n); XmlDsigSmevTransform smevTransform = new XmlDsigSmevTransform(); reference.AddTransform(smevTransform); if (isAck) { XmlDsigEnvelopedSignatureTransform enveloped = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(enveloped); } sxml.AddReference(reference); //=========================================================================================CREATE SIGNATURE sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; //Формирование подписи ГОСТ Р 34.10-2001 http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411 sxml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data X509KeyInfo = new KeyInfoX509Data(certificate); keyInfo.AddClause(X509KeyInfo); sxml.KeyInfo = keyInfo; sxml.ComputeSignature(); XmlElement signature = sxml.GetXml(); //==================================================================================================add ds: if (assignDs) { _assignNsPrefix(signature, "ds"); XmlElement xmlSignedInfo = signature.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = false; document.LoadXml(xmlSignedInfo.OuterXml); //create new canonicalization object based on original one Transform canonicalizationMethodObject = sxml.SignedInfo.CanonicalizationMethodObject; canonicalizationMethodObject.LoadInput(document); //get new hshing object based on original one SignatureDescription description = CryptoConfig.CreateFromName(sxml.SignedInfo.SignatureMethod) as SignatureDescription; if (description == null) { throw new CryptographicException( $"Не удалось создать объект SignatureDescription по имени [{sxml.SignedInfo.SignatureMethod}]"); } HashAlgorithm hash = description.CreateDigest(); if (hash == null) { throw new CryptographicException( $"Не удалось создать объект HashAlgorithm из SignatureDescription по имени [{sxml.SignedInfo.SignatureMethod}]"); } //compute new SignedInfo digest value byte[] hashVal = canonicalizationMethodObject.GetDigestedOutput(hash); //compute new signature XmlElement xmlSignatureValue = signature.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement; xmlSignatureValue.InnerText = Convert.ToBase64String(description.CreateFormatter(sxml.SigningKey).CreateSignature(hashVal)); } //=============================================================================APPEND SIGNATURE TO DOCUMENT if (!isSidebyside) { doc.GetElementsByTagName("CallerInformationSystemSignature", "urn://x-artefacts-smev-gov-ru/services/message-exchange/types/1.1")[0].InnerXml = ""; doc.GetElementsByTagName("CallerInformationSystemSignature", "urn://x-artefacts-smev-gov-ru/services/message-exchange/types/1.1")[0].AppendChild(signature); } else { getNodeWithAttributeValue(doc.ChildNodes, signingNodeId)?.ParentNode?.AppendChild(signature); } return(doc); }
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))); } }