2011-09-15 167 views
12

这是我的代码。为什么我得到“指定的算法无效”异常

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 “指定了无效的算法。”

我在做什么错?

UPDATE:

ID = 2.16.840.1.101.3.4.2.1

+0

'id'的价值是什么? – dtb

+0

我用id的值更新了问题。 – scott

回答

9

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

你的问题是,CSP只是不支持SHA 256可以得到进一步的信息here

+0

有什么办法可以使这项工作?我从java移植它,它需要使用相同的算法。据我可以告诉它是使用rsa + sha – scott

+0

你可能想检查http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256.aspx是一个SHA256类。网络框架。但是,我没有用过它。 –

+0

SHA256CryptoServiceProvider不接受非对称密钥 – scott

2

请注意,我用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和使用CSP(加密服务提供商)是SHA512能干。以下是CSP及其功能的列表。如果您查找SHA512,您会发现“Microsoft增强型RSA和AES加密提供程序”。默认情况下,生成证书不会使用(至少在Windows中),因此您必须在创建证书时指定它。

创建私钥和证书 - 这一步会问你的问题,州,地区等等等等

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

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

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

不知道这是什么downvote ..它肯定帮助了我,非常感谢! +1 +1 –

1

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

相关问题