I have encrypted a text file into pgp using Bouncy Castel but now i
need to decrypt it. How can i go about reading the text from the pgp
file.
This is one of those question where first reaction is: when you
encrypt with FoobarEncrypt class/method, then you just decrypt
with the FoobarDecrypt class/method.
But looking at the API reveals that encryption and decryption
is very asymmetric, so the question actually makes sense.
The code you need to look at is:
csharp\crypto\test\src\openpgp\examples\KeyBasedLargeFileProcessor.cs
But I have created a slightly simpler example. See below.
Arne
====================
using System;
using System.IO;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
namespace E
{
public class PGPWrapper
{
private const int BUFSIZ = 10240;
public static void Encrypt(string infnm, string outfnm, string pp)
{
Stream instm = new FileStream(infnm, FileMode.Open,
FileAccess.Read);
Stream outstm = new FileStream(outfnm, FileMode.Create,
FileAccess.Write);
PgpEncryptedDataGenerator pedg = new
PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes128, new
SecureRandom());
pedg.AddMethod(pp.ToCharArray());
Stream encstm = pedg.Open(outstm, new byte[BUFSIZ]);
PgpCompressedDataGenerator pcdg = new
PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
Stream compstm = pcdg.Open(encstm);
PgpUtilities.WriteFileToLiteralData(compstm,
PgpLiteralData.Binary, new FileInfo(infnm), new byte[BUFSIZ]);
compstm.Close();
encstm.Close();
outstm.Close();
instm.Close();
}
public static void Decrypt(string infnm, string outfnm, string pp)
{
Stream instm = new FileStream(infnm, FileMode.Open,
FileAccess.Read);
Stream outstm = new FileStream(outfnm, FileMode.Create,
FileAccess.Write);
Stream utilstm = PgpUtilities.GetDecoderStream(instm);
PgpObjectFactory pof = new PgpObjectFactory(utilstm);
PgpObject po;
for(;
{
po = pof.NextPgpObject();
if(po is PgpEncryptedDataList) break;
}
PgpEncryptedDataList pedl = (PgpEncryptedDataList)po;
PgpPbeEncryptedData pped = (PgpPbeEncryptedData)pedl[0];
Stream encstm = pped.GetDataStream(pp.ToCharArray());
pof = new PgpObjectFactory(encstm);
PgpCompressedData pcd = (PgpCompressedData)pof.NextPgpObject();
Stream compstm = pcd.GetDataStream();
pof = new PgpObjectFactory(compstm);
PgpLiteralData pld = (PgpLiteralData)pof.NextPgpObject();
Stream litstm = pld.GetInputStream();
Streams.PipeAll(litstm, outstm);
litstm.Close();
compstm.Close();
encstm.Close();
utilstm.Close();
outstm.Close();
instm.Close();
}
}
public class Program
{
public static void Main(string[] args)
{
PGPWrapper.Encrypt(@"C:\z1.txt", @"C:\z.pgp", "This is a
super secret passphrase");
PGPWrapper.Decrypt(@"C:\z.pgp", @"C:\z2.txt", "This is a
super secret passphrase");
Console.ReadKey();
}
}
}