使用Bouncy Castle库c#

时间:2019-05-08 08:23:49

标签: java c# encryption .net-core bouncycastle

我在c#中为pdf文件的dercrypt已“翻译”了Java代码。我不明白为什么当我启动一个新的CmsEnvelopedData对象时出现一个异常:“试图读取流的末尾”。我还尝试不安装NuGet软件包而下载Bouncy Castle源代码,但是我无法弄清楚问题可能出在哪里。感谢那些会提供帮助的人。

代码Java:

 public final synchronized byte[] decryptData(byte[] cipherData, String pwd)
    throws CSException 
{

    cipherData = Base64.decode(cipherData);

    PrivateKey privKey = null;

    privKey = loadKeyFromPKCS12( this.encPrivateKeyId, pwd);

    try
    {            
        CMSEnvelopedData envelopedData = new CMSEnvelopedData(cipherData);
        RecipientInformationStore  recipients = envelopedData.getRecipientInfos();
        Collection  c = recipients.getRecipients();
        Iterator    it = c.iterator();

        if (it.hasNext()) 
        {
            RecipientInformation   recipient = (RecipientInformation)it.next();

            this.outputBuffer = recipient.getContent(privKey);
        }
        else{
            this.outputBuffer = null;
        }
    }

    return this.outputBuffer;        
}

代码C#:

  public byte[] DecryptFile(byte[] file)
    {


        var fileDecode = Org.BouncyCastle.Utilities.Encoders.Base64.Decode(file);

        CmsEnvelopedData envelopedData = new CmsEnvelopedData(fileDecode);

        RecipientInformationStore recipients = envelopedData.GetRecipientInfos();
        var c = recipients.GetRecipients();
        foreach (RecipientInformation recipient in c)
        {
            var decrypted = recipient.GetContent(RetrievePrivateKey());
            return decrypted;


        }

        return null;
    }

用于读取私钥的方法C#:

 private RsaKeyParameters RetrievePrivateKey()
    {

        var obj = AppConfiguration.GetBasePath();
        var path = obj.BasePath + obj.KeystoreFolder;
        var keyfolder = new DirectoryInfo(path);
        if (!keyfolder.Exists)
        {
            keyfolder.Create();
        }
        X509Certificate2 certi = new X509Certificate2(path + obj.KeystoreFile, "Password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

        RSA crypt = certi.GetRSAPrivateKey();

        var Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(certi.PrivateKey).Private;

        return (RsaKeyParameters)Akp;
    }

当我尝试实例化一个新的CmsEnvelopedData对象时返回了异常: enter image description here

我还附上示例中使用的加密示例文件: https://www.dropbox.com/s/gkwovnifpjf1xza/offer.pdf?dl=0

1 个答案:

答案 0 :(得分:1)

您正在尝试解密部分文件。您显示的文件是单行base64字符串。解码后,它会生成一个带有许多OCTET STRING值的ASN.1编码文件。当您尝试读取ASN.1编码的二进制值时,遇到的异常是,但是在完全检索流之前,流已结束。这通常是因为缺少文件尾部,但它当然也可能表示文件已更改,例如当将行尾转换为二进制文件时,或者如果传输引起了(如今不太可能)错误。

文件的尾部经常丢失,因为在完全接收文件之前复制或移动了文件。例如。如果您使用FTP服务器,则可能很难判断文件上传的完成时间。