Search code examples
c#encryptionbouncycastlepgpopenpgp

Why does passing a FileStream to a PGP Decryption function work but not a MemoryStream?


I'm trying to decrypt PGP encrypted text via a memory stream. Because the PgpCore NuGet package takes in a generic Stream object, I am expecting a MemoryStream to work. Instead, I am getting obscure errors like "unknown object in stream 47".

I've looked at a bunch of sources online indicating that the encoding is the key, but I just get different errors with different encodings. When I test it out with a FileStream object, the decryption function works great and runs without a problem.

This DOESN'T work:

using var pgp = new PGP();
var fileStream = new MemoryStream(Encoding.Default.GetBytes(File.ReadAllText(file)));
var privateKeyStream = new MemoryStream(Encoding.Default.GetBytes(File.ReadAllText("prod")));
pgp.DecryptStream(fileStream, outputStream, privateKeyStream, "[redacted]");

This DOES:

using var pgp = new PGP();
var fileStream = File.OpenRead(file);
var privateKeyStream = new MemoryStream(Encoding.Default.GetBytes(File.ReadAllText("prod")));
pgp.DecryptStream(fileStream, outputStream, privateKeyStream, "[redacted]");

What am I missing? What's different between a FileStream and MemoryStream that one works and the other doesn't?


Solution

  • Encoding.Default.GetBytes(File.ReadAllText(file))

    This is a rather odd way to read a file, and may introduce some encoding issues. Try use this instead:

    new MemoryStream(File.ReadAllBytes(file));