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

C# 在Bouncy Castle中使用正确的加密服务提供程序更新x509Certificate2,c#,cryptography,x509certificate,bouncycastle,x509certificate2,C#,Cryptography,X509certificate,Bouncycastle,X509certificate2,我正在使用Wiktor Zychla()的这篇博文中的CertificateGenerator.GenerateCertificate创建x509Certificate2 用于生成证书文件。我需要使用更强的签名算法,因此我使用的不是SHA1withRSA(示例中的一个),而是SHA256withRSA 证书已生成并成功导出到.pfx文件。以后使用证书时,我收到错误指定的算法无效 当运行certutil-dump mycert.pfx时,我看到设置了不正确的加密服务提供程序(CSP):Micros

我正在使用Wiktor Zychla()的这篇博文中的
CertificateGenerator.GenerateCertificate创建
x509Certificate2

用于生成证书文件。我需要使用更强的签名算法,因此我使用的不是
SHA1withRSA
(示例中的一个),而是
SHA256withRSA

证书已生成并成功导出到
.pfx
文件。以后使用证书时,我收到错误
指定的算法无效

当运行certutil-dump mycert.pfx时,我看到设置了不正确的加密服务提供程序(CSP):Microsoft基本加密提供程序v1.0

----------------末端嵌套级别1----------------

Provider=Microsoft基本加密提供程序v1.0

我如何告诉Bouncy Castle API使用不同的CSP?Microsoft增强的RSA和AES加密提供商,它实际上可以用RSA处理SHA256

关于Bouncy Castle和
C#
的资源非常少,因此如果您能链接到一些文档或相关示例,我们将不胜感激

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


最简单的方法是在导入生成的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外,没有人设置此字段。如果您是从文件
新X509Certificate2(文件名)
使用PFX,则必须更改私钥。将
PrivateKey
属性转换为
rsacyptoserviceprovider
并修改
CspParameters
(我现在没有代码片段)。然后将修改后的
rsacyptoserviceprovider
设置回
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");

谢谢你的回答。我在数据库中存储了“错误”的证书。不要导入到LocalMachine(这就是我们的应用程序处理证书的方式)。需要重新生成那些“错误”的证书,最好是在c#中,并将它们存储回DB,而不破坏现有的集成。这在c#中甚至可以实现吗?:-)已转换的私钥
var rsa=(rsacyptoserviceprovider)x509cert.PrivateKey
。还有
rsa.CspKeyContainerInfo
,它包含
ProviderType
ProviderName
。这些是只读属性,不能更改,这对于私钥来说很有意义:-)您提到的是
CspParameters
?以及如何更新它们,如果可能的话。@mimo我已经添加了应该改变CSP的示例代码。谢谢您的代码。我收到异常
加密异常:密钥集不存在
在最后一行:
cert.Export(X509ContentType.Pfx,“a”)
。My cert.pfx位于
c:\code\temp
中。已授予对AppPool的完全访问权,在AppPool下运行我的代码到
temp
以及
cert.pfx
,但仍然获得
密钥集不存在
@mimo这很奇怪。我没有尝试从web应用程序运行代码。每次我看到这个异常都与私钥的特权有关。您可以尝试在
X509Certificate2
构造函数中使用
x509keystrageflags
。也许会有帮助。我将在晚上设法调查此事。