// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 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"); } } }