【发布时间】:2019-05-08 08:23:49
【问题描述】:
我已经“翻译”了 c# 中的 java 代码,用于 pdf 文件的 dercrypt。我不明白为什么当我启动一个新的 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
【问题讨论】:
-
等一下,您是否要直接通过 CMS 解密实际的 PDF 文件? PDF 可能包含签名或加密数据,但 PDF 不符合 CMS 规范(或者无法使用 PDF 查看器打开)。我不会在我的计算机上“执行”不受信任的 PDF 文件,非常感谢。
-
这是一个经过数字签名和加密的文件。别担心,我正在寻找解决方案,而不是“感染”人!
-
我下载的文件首先编码为base 64。解码后它似乎在OCTET STRING中包含很多数据,但我感觉文件被缩短为
openssl asn1parse也失败了。也许您的 IT 部门认为执行 FTP-then-copy 会很有用,但在 FTP 完成传输时没有任何明确的指示。就我而言,双重尴尬,因为我告诉他们这会失败,并且当它失败时他们不应该带着部分文件来找我。确实如此,他们来找我了。还要提防文本文件传输等。 -
如果不是PDF,那就别叫PDF了。
-
当然是这样的。例外和错误似乎表明了这一点,但老实说,它们都没有过于具体。
标签: java c# encryption .net-core bouncycastle