Я "перевел" код Java в c # для dercrypt файла PDF.Я не понимаю, почему, когда я запускаю новый объект CmsEnvelopedData, я получаю исключение: «Попытка чтения после конца потока».Я также пытался загрузить исходные коды Bouncy Castle без установки пакета NuGet, но не мог понять, в чем проблема.Спасибо тем, кто поможет.
Код 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