mattosaurus / PgpCore

.NET Core class library for using PGP
MIT License
245 stars 98 forks source link

NullReferenceException #144

Closed 0xF6 closed 2 years ago

0xF6 commented 3 years ago

So, sample code:

var input = new MemoryStream(Encoding.UTF8.GetBytes("foo bar\n"));
var output = new MemoryStream();

var private_key = new MemoryStream();
var public_key = new MemoryStream();

new PGP().GenerateKey(public_key, private_key, "foobar@gmail.com", "1234", 4096);

var keys = new EncryptionKeys(Encoding.UTF8.GetString(public_key.ToArray()), Encoding.UTF8.GetString(private_key.ToArray()), "1234");
await new PGP(keys).ClearSignStreamAsync(input, output);
await new PGP(keys).VerifyClearStreamAsync(output);

And get exception on await new PGP(keys).VerifyClearStreamAsync(output);:

Object reference not set to an instance of an object.
   at PgpCore.PGP.<VerifyClearAsync>d__270.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at PgpCore.PGP.<VerifyClearStreamAsync>d__230.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Program.<<Main>$>d__0.MoveNext() in C:\git\vein-lang\compiler\Program.cs:line 54
0xF6 commented 3 years ago

So, its fixed by output.Seek(0, SeekOrigin.Begin); after await new PGP(keys).ClearSignStreamAsync(input, output);.

But I still don't understand why such an uninformative error?

mikeneumann commented 3 years ago

FWIW, I am similarly served a System.NullReferenceException when executing the following:

PGP pgp = new PGP(encryptionKeys); // no errors. encryptionKeys is valid.
bool verified = await pgp.VerifyClearFileAsync(inputFile); // exception thrown in here. inputFile is valid.
mattosaurus commented 3 years ago

Hi @0xF6, this is because the method expects the stream to be at the start and used more like this.

            // Act
            using (Stream inputFileStream = testFactory.ContentStream)
            using (Stream outputFileStream = File.Create(testFactory.SignedContentFilePath))
                await pgpSign.ClearSignStreamAsync(inputFileStream, outputFileStream);

            using (Stream inputFileStream = testFactory.SignedContentStream)
                verified = await pgpVerify.VerifyClearStreamAsync(inputFileStream);

I agree the error isn't that useful though so I'll put in a specific check for this.