java - 使用 Bouncy Castle 库 c# 解密 pdf.p7m 文件的问题
问题描述
我已经在 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 对象时返回异常:
我还附上了示例中使用的加密示例文件: https ://www.dropbox.com/s/gkwovnifpjf1xza/offer.pdf?dl=0
解决方案
您正在尝试解密部分文件。您显示的文件是单行 base64 字符串。解码后,它会生成一个包含许多 OCTET STRING 值的 ASN.1 编码文件。您遇到的例外情况是,当您尝试读取 ASN.1 编码的二进制值时,流在完全检索之前就结束了。这通常是因为文件的尾部丢失,但它当然也可能表明文件已被更改,例如当行尾在二进制文件中转换时,或者如果传输导致(现在不太可能)错误。
文件尾部经常丢失,因为文件在完全接收之前被复制或移动。例如,如果您使用 FTP 服务器,可能很难判断文件上传何时完成。
推荐阅读
- python - Pandas 打破行并阻止 Google Data Studio 正确读取文件
- eclipse - 为什么其他代码有 Log4j 输出到控制台,而不是我的代码?
- reactjs - 为什么按钮没有从 x 变为 y 做出反应?
- entity-framework-core - EF Core 无法翻译多个 Like 查询
- mongodb - Mongoose 在另一个子文档数组中增加子文档数组值
- c - 将 GLib 包含到 CLion(Windows、Msys2)中
- python - 我该怎么做-> python、selenium 和 chrome
- bootstrap-4 - Bootstrap 4 Flexbox - 将多个列与对齐项目中心对齐
- reactjs - 反应钩子查询不更新状态更改
- c++ - 之后仍需要使用源对象时调用父移动赋值运算符