使用Bouncy Castle中正确的加密服务提供程序更新x509Certificate2

时间:2017-07-13 15:03:40

标签: c# cryptography x509certificate bouncycastle x509certificate2

我在Wiktor Zychla(http://www.wiktorzychla.com/2012/12/how-to-create-x509certificate2.html)的博文中使用x509Certificate2创建CertificateGenerator.GenerateCertificate

Bouncy Castle crypto library用于生成证书文件。我需要使用更强的签名算法,所以我使用SHA1withRSA而不是SHA256withRSA(例如一个)。

生成证书并成功导出到.pfx文件。稍后使用证书时,我收到错误Invalid algorithm specified

运行certutil -dump mycert.pfx时,我看到设置了错误的加密服务提供程序(CSP): Microsoft Base Cryptographic Provider v1.0

  

...

     

----------------结束嵌套等级1 ----------------

     

Provider = Microsoft Base Cryptographic Provider v1.0

     

...

如何告诉Bouncy Castle API使用不同的CSP? Microsoft增强型RSA和AES加密提供程序,实际上可以处理SHA256withRSA。< / p>

Bouncy Castle和C#上的资源很少,因此非常感谢任何文档或相关示例的链接。

CryptoAPI CSP和算法列表,它们支持:

https://msdn.microsoft.com/en-us/library/windows/desktop/bb931357(v=vs.85).aspx

1 个答案:

答案 0 :(得分:2)

最简单的方法是在导入生成的pfx时指定CSP。您可以使用此命令

certutil -importPFX -csp "Microsoft Enhanced RSA and AES Cryptographic Provider" -v c:\yourpfx.pfx AT_KEYEXCHANGE,NoExport,NoProtect

  • 导入LocalMachine \ My
  • 将CSP设置为Microsoft增强型RSA和AES加密提供程序
  • 将私钥使用设置为Exchange
  • 将私钥设为不可导出
  • 设置私钥而无需额外(密码)保护

CSP是PKCS#12(PFX)中特定于Windows的字段,除了Windows之外没有人设置此项。如果您使用文件new X509Certificate2(filename)中的PFX,则必须更改私钥。将PrivateKey属性转换为RSACryptoServiceProvider并修改CspParameters(我现在没有代码片段)。然后将修改后的RSACryptoServiceProvider设置回PrivateKey属性。

-------编辑

以下是更改从文件

读取的PFX上的CSP的示例代码
// need to set exportable flag to be able to ... export private key
X509Certificate2 cert = new X509Certificate2(@"d:\test.pfx", "a", X509KeyStorageFlags.Exportable);
var privKey = cert.PrivateKey as RSACryptoServiceProvider;

// will be needed later
var exported = privKey.ToXmlString(true);

// change CSP
var cspParams = new CspParameters()
{
    ProviderType = 24,
    ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"
};

// create new PrivateKey from CspParameters and exported privkey
var newPrivKey = new RSACryptoServiceProvider(cspParams);
newPrivKey.FromXmlString(exported);

// Assign edited private key back
cert.PrivateKey = newPrivKey;

// export as PKCS#12/PFX
var bytes = cert.Export(X509ContentType.Pfx, "a");
相关问题