如何将RSACryptoServiceProvider私钥导入弹力城堡

时间:2017-01-19 11:12:00

标签: c# bouncycastle rsacryptoserviceprovider

目前,我正在使用etoken(safenet),充气城堡库和X509certificate2来解密p7m文件。

我想使用X509Ceritificate2私钥通过Bouncy Castle库解密p7m byteArray。我可以从X509Store检索X509Ceritificate2私钥,密钥不为空。当它是RSACryptoServiceProvider对象时,我可以使用私钥。

RSACryptoServiceProvider systemUserOnlyReadablePrivateKey = certificate.PrivateKey as RSACryptoServiceProvider;

但是,当我尝试将私钥从RSACryptoServiceProvider对象转换为其他对象(如byte []或AsymetricKeyParameter)时,异常消息“密钥无效,无法在指定状态下使用”。已被证明。

AsymetricKeyParameter key = DotNetUtilities.GetKeyPair(cert.Privat‌​eKey).Private; //Exception prompt

由于证书存储在eToken中并在eToken插件插入计算机时自动添加到X509Store中,并且在eToken插件时删除了证书,因此我无法将证书设置为可导出。

  1. Bouncy Castle API是否支持使用X509Ceritificate2私钥进行解密?
  2. 如何将密钥转换为其他对象,以便我可以通过Bouncy Castle API进行解密。
  3. 感谢。

    以下是我的源代码。

    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.Privat‌​eKey).Private); //Exception prompt
      }
    }
    

0 个答案:

没有答案