I have "translated" java code in c # for the dercrypt of a pdf file. I don't understand why when I start a new CmsEnvelopedData object, I get an exception: "Attempted to read past the end of the stream". I also tried to download the Bouncy Castle sources without installing the NuGet package, but I couldn't figure out what the problem might be. Thanks to those who will help.
Code 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;
}
Code 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;
}
Method C# for reading the private key:
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;
}
Exception returned when I attempt to instantiate a new CmsEnvelopedData object:
I also enclose the encrypted example file used in the example: https://www.dropbox.com/s/gkwovnifpjf1xza/offer.pdf?dl=0