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
You're trying to decrypt a partial file. The file you showed was a single line base64 string. When decoded, it resulted into an ASN.1 encoded file with lots of OCTET STRING values. The exception you get is when you try and read an ASN.1 encoded binary value, but the stream ends before it can be fully retrieved. This commonly is because the tail of the file is missing, but it could of course also be an indication of a file that is altered, e.g. when line endings are converted in a binary file, or if transmission caused a (nowadays unlikely) error.
The tail of the file is often missing because the file is copied or moved before it is fully received. E.g. if you use an FTP server, it may be hard to tell when a file upload has completed.