C# 如何将RSACryptServiceProvider私钥导入bouncy castle
目前,我正在使用etoken(安全网)、bouncy castle库和X509certificate2对p7m文件进行解密 我想使用X509Ceritificate2私钥通过Bouncy Castle库解密p7m byteArray。我可以从X509Store中检索X509Ceritificate2私钥,并且该密钥不为null。当私钥是RSACryptServiceProvider对象时,我可以使用它C# 如何将RSACryptServiceProvider私钥导入bouncy castle,c#,bouncycastle,rsacryptoserviceprovider,C#,Bouncycastle,Rsacryptoserviceprovider,目前,我正在使用etoken(安全网)、bouncy castle库和X509certificate2对p7m文件进行解密 我想使用X509Ceritificate2私钥通过Bouncy Castle库解密p7m byteArray。我可以从X509Store中检索X509Ceritificate2私钥,并且该密钥不为null。当私钥是RSACryptServiceProvider对象时,我可以使用它 RSACryptoServiceProvider systemUserOnlyReadable
RSACryptoServiceProvider systemUserOnlyReadablePrivateKey = certificate.PrivateKey as RSACryptoServiceProvider;
但是,当我尝试将私钥从RSACryptServiceProvider对象转换为其他对象(如byte[]或AsymetricKeyParameter)时,显示了一条异常消息“key not valid for use in specified state.”
AsymetricKeyParameter key = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private; //Exception prompt
由于证书存储在eToken中,并在eToken插件插入计算机时自动添加到X509Store中,并且在eToken插件插入时删除证书,因此我无法将证书设置为可导出
byte[] p7mByte = p7mByteArray; //p7m to byte array
cmsEnvelopedData = new CmsEnvelopedDataParser(p7mByteArray);
RecipientInformationStore recipientInformationStore = cmsEnvelopedData.GetRecipientInfos();
RecipientInformation recipientInformation = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
if (certificate.PrivateKey != null)
{
RecipientID recipientId = new RecipientID();
recipientId.SerialNumber = certificate.SerialNumber;
recipientId.Issuer = certificate.IssuerDN;
recipientInformation = recipientInformationStore.GetFirstRecipient(recipientId);
RSACryptoServiceProvider systemUserOnlyReadablePrivateKey = certificate.PrivateKey as RSACryptoServiceProvider;
CspParameters cspParameters = new CspParameters(systemUserOnlyReadablePrivateKey.CspKeyContainerInfo.ProviderType, systemUserOnlyReadablePrivateKey.CspKeyContainerInfo.ProviderName, systemUserOnlyReadablePrivateKey.CspKeyContainerInfo.KeyContainerName)
{
Flags = CspProviderFlags.UseArchivableKey
};
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParameters);
csp = (RSACryptoServiceProvider)certificate.PrivateKey;
CmsTypedStream recData = null;
recData = recipientInformation.GetContentStream(DotNetUtilities.GetKeyPair(cert.PrivateKey).Private); //Exception prompt
}
}
最后,我使用System.Security.Cryptography而不是Bouncy Castle进行解密。函数的作用是:自动加载相应的私钥进行解密。因此,我不需要导出私钥并将其放入Bouncy Castle API。EnvelopedCms EnvelopedCms=新的EnvelopedCms();包络CMS.解码(p7mByteArray);Decrypt();为了让bouncy castle获得您的密钥,存储中安装的证书的参数
Exportable
应设置为true。否则,所使用的底层API将阻止这种访问。