PGP Encryption and Decryption in C#

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", "", "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");


Bob Loftus · 8th October 2018 at 6:48 pm

Thanks a lot, can’t wait to try it out 🙂

    sandeep · 6th December 2018 at 6:51 am

    not able to decrypte data by signed key.

    Santosh · 25th January 2019 at 9:41 am

    Not able to decrypte data by signed key getting below issue.

    Org.BouncyCastle.Bcpg.OpenPgp.PgpPublicKeyRing found where PgpSecretKeyRing expected

Leave a Reply to sandeep Cancel reply

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