为什么我收到“指定的无效算法”exception

这是我的代码。

X509Certificate pXCert = new X509Certificate2(@"keyStore.p12", "password"); RSACryptoServiceProvider csp = (RSACryptoServiceProvider)pXCert.PrivateKey; string id = CryptoConfig.MapNameToOID("SHA256"); return csp.SignData(File.ReadAllBytes(filePath), id); 

在最后一行,我得到了例外:

System.Security.Cryptography.CryptographicException“指定的算法无效。”

我究竟做错了什么?

更新:

id = 2.16.840.1.101.3.4.2.1

.NET代码或您提供的CSP代码没有问题。

您的问题是CSP不支持SHA 256.您可以在此处获取更多信息

请注意,我使用SHA512,但SHA256将使用以下示例:

“无效的算法指定”让我永远想出来,我几乎尝试了一切。 向Gonzalo Gallotti发布道具,发布了帮助我的代码链接。 我评论了我的代码以显示每个步骤正在做什么。 注意:如果没有在代码示例下面发布的正确生成的证书,此代码将无法运行:

 public void GetCertificate() { // Get the Machine Cert Store var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); string alg = CryptoConfig.MapNameToOID("SHA512"); // Open the cert store store.Open(OpenFlags.ReadWrite); // Loop through each certificate within the store foreach (X509Certificate2 myCert in store.Certificates) { // Get the certificate we are looking for if (myCert.IssuerName.Name.Contains("CN=YourSite")) { // Check if the certificate has a private key if (myCert.HasPrivateKey) { // Get your custom signature as a string string mySignature = GetSignatureString(); // Convert signature to byte array byte[] originalData = Encoding.UTF8.GetBytes(mySignature); // Create RSA provider from private key RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider)myCert.PrivateKey; // Sign the signature with SHA512 byte[] signedSignature = signedSignature = rsaProvider.SignData(originalData, alg); if (rsaProvider.VerifyData(originalData, alg, signedSignature)) { // Signature is verified Do Stuff } else { throw new Exception("The data does not match the signature."); } } } } } 

接下来 – 证书必须是SHA512并使用具有SHA512function的CSP(加密服务提供程序)。 以下是CSP及其function的列表。 如果您寻找SHA512,您将找到“Microsoft增强型RSA和AES加密提供商”。 默认情况下,生成证书不会使用此function(至少在Windows中),因此您必须在创建证书时指定它。

创建私钥和证书 – 此步骤将询问您问题,州,地区等。

 openssl req -x509 -nodes -sha512 -newkey rsa:2048 -keyout 512key.pem -out 512cert.pem -days 3650 

使用Microsoft增强RSA和AES加密提供程序创建要导入证书存储区的PFX文件:

 openssl pkcs12 –export –in 512cert.pem –inkey 512key.pem –CSP “Microsoft Enhanced RSA and AES Cryptographic Provider” –out 512pfx.pfx 

有类似的问题但只是解决了它。 如果您不使用X509而只使用普通RSACryptoServiceProvider来获取密钥,则仅支持SHA1。