A while ago I knocked up a NuGet package called PgpCore which uses the BouncyCastle library to easily encrypt and decrypt files and streams.

The code for the project is here and this post is mainly here to point anyone in need towards it as I had to fix a bug in it recently and was once again reminded of how many confusing StackOverflow answers exist about this subject.

using (PGP pgp = new PGP())
{
	// Generate keys
	pgp.GenerateKey(@"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "[email protected]", "password");
	// Encrypt file
	pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\public.asc", true, true);
	// Encrypt and sign file
	pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "password", true, true);
	// Decrypt file
	pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\content__decrypted.txt", @"C:\TEMP\keys\private.asc", "password");
	// Decrypt signed file
	pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\content__decrypted_signed.txt", @"C:\TEMP\keys\private.asc", "password");

	// Encrypt stream
	using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content.txt", FileMode.Open))
	using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__encrypted2.pgp"))
	using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open))
		pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);

	// Decrypt stream
	using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open))
	using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt"))
	using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open))
		pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password");
}

2 Comments

Francisco Gil · 15 June 2022 at 10:43

What is the email necessary for?

Nikolay · 12 December 2022 at 19:19

I am very grateful to you.
Nice job! You helped me a lot!

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *