I am tryng to decrypt a file I just encrypted using bouncycastle, but im getting this exception:
Premature end of stream in PartialInputStream
I am using the example code from bouncycastle and haven't changed anything.
I'm getting this when I use this code for encryption:
private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
{
MemoryStream encOut = new MemoryStream();
try
{
MemoryStream bOut = new MemoryStream();
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip );
//PgpUtilities.WriteFileToLiteralData(
// comData.Open(bOut),
// PgpLiteralData.Binary,
// new FileInfo(fileName));
Stream cos = comData.Open(bOut);
PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
Stream pOut = lData.Open(
cos,
PgpLiteralData.Binary,
fileName,
clearData.Length,
DateTime.UtcNow
);
lData.Close();
comData.Close();
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom() );
cPk.AddMethod(encKey);
byte[] bytes = bOut.ToArray();
Stream os = encOut;
Stream cOut = cPk.Open(os, bytes.Length);
cOut.Write(bytes, 0, bytes.Length);
cOut.Close();
encOut.Close();
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
return encOut.ToArray();
}
I think it has something to do with the PgpLiteralDataGenerator
.
But I need to use it because I want to encrypt data from a byte array, not from a file. Is there some other way to do this?
I got the same error, when I tried to read from the 'stream'.
A solution for me was to copy the stream to a new .net Stream object like
MemoryStream
. And after that read from the memoryStream object.So, my base stream type has nothing to do with
Org.BouncyCastle.Bcpg
stream types.Anybody who is struggeling heres a working code: