I am having a challenge for my specific requirement... I would like to encrypt a stream on the go, passing each chunk of data(in a buffer) to the next process(es) until it is finally closed/disposed after the last process.
I already have an implementation that uses Rijndael. The logic of the code is based on this excellent article(http://www.codeproject.com/Articles/356297/Copy-a-Stream-with-Progress-Reporting )
The method formed the basis is this one:
/// <summary>
/// Copies the source stream into the current
/// </summary>
/// <param name="stream">The current stream</param>
/// <param name="source">The source stream</param>
/// <param name="bufferSize">Optional the size of buffer used for copying bytes</param>
/// <returns>The number of bytes actually copied.</returns>
public static long CopyFrom(this Stream stream, Stream source, int bufferSize = 4096)
{
int count = 0;
byte[] buffer = new byte[bufferSize];
long length = 0;
while ((count = source.Read(buffer, 0, bufferSize)) != 0)
{
length += count;
stream.Write(buffer, 0, count);
}
return length;
}
I have seen that the Bouncy Castle code has the following Open method in the PgpLiteralDataGenerator class:
// encrypt - partial packet style.
//
SecureRandom rand = new SecureRandom();
byte[] test = new byte[1233];
rand.NextBytes(test);
bOut = new UncloseableMemoryStream();
comData = new PgpCompressedDataGenerator(
CompressionAlgorithmTag.Zip);
comOut = comData.Open(new UncloseableStream(bOut));
lData = new PgpLiteralDataGenerator();
ldOut = lData.Open(
new UncloseableStream(comOut),
PgpLiteralData.Binary,
PgpLiteralData.Console,
TestDateTime,
new byte[16]);
ldOut.Write(test, 0, test.Length);
lData.Close();
comData.Close();
cbOut = new UncloseableMemoryStream();
cPk = new PgpEncryptedDataGenerator(
SymmetricKeyAlgorithmTag.Cast5, rand);
cPk.AddMethod(pass);
cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
{
byte[] tmp = bOut.ToArray();
cOut.Write(tmp, 0, tmp.Length);
}
cPk.Close();
Is it the correct method to use if I wanted to encrypt/decrypt the stream in blocks then close/dispose of the stream much later?
Encrypting it in bytes of 4K and passing it on to the next process then fetching the next 4K bytes... and so on... allowing the stream to be encrypted byte by byte instead of all at once(size can vary from 500 to 4GB)?
I have also had a look at the Tests in class: "Org.BouncyCastle.Bcpg.OpenPgp.Tests.PgpPbeTest"
I may be wrong but I think the answer is somewhere around there. Anyone care to help? Sorry for the long message.