Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need example for BouncyCastle PGP File encryption in C#

I'm trying to encrypt files using my private key (in ascii format) and any other public key (also in ascii format). The BouncyCastle library looks like the correct thing to use, but I cannot find documentation for C#. Could anyone please assist me with an example. Thank you.

like image 954
Daniel Brink Avatar asked Apr 22 '10 19:04

Daniel Brink


People also ask

What is needed for PGP encryption?

At a basic level, PGP encryption uses a combination of two forms of encryption: symmetric key encryption, and public-key encryption.

How PGP works explain with example?

PGP uses the public key system in which every user has a unique encryption key known publicly and a private key that only they know. A message is encrypted when a user sends it to someone using their public key, then decrypted when the recipient opens it with their private key.


1 Answers

Here's some code from the BouncyCastle example. You should grab the source code and look in the unit tests, they contain examples. I've found that Java resources are also useful. The example can be found in the source under crypto\test\src\openpgp\examples\PbeFileProcessor.cs

private static void EncryptFile(
        Stream  outputStream,
        string  fileName,
        char[]  passPhrase,
        bool    armor,
        bool    withIntegrityCheck)
    {
        if (armor)
        {
            outputStream = new ArmoredOutputStream(outputStream);
        }

        MemoryStream bOut = new MemoryStream();

        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
            CompressionAlgorithmTag.Zip);

        PgpUtilities.WriteFileToLiteralData(
            comData.Open(bOut),
            PgpLiteralData.Binary,
            new FileInfo(fileName));

        comData.Close();

        byte[] bytes = bOut.ToArray();

        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
            SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

        cPk.AddMethod(passPhrase);

        Stream cOut = cPk.Open(outputStream, bytes.Length);

        cOut.Write(bytes, 0, bytes.Length);

        cOut.Close();

        if (armor)
        {
            outputStream.Close();
        }
    }
like image 136
Emmanuel Avatar answered Oct 05 '22 22:10

Emmanuel