9

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.

Daniel Brink
  • 2,434
  • 4
  • 24
  • 26
  • maybe I'm not understanding PGP correctly, when you encrypt a file do you only use the 3rd party's public key? No part of your private key is used in the process, correct? If so, I need to change my question to "Example: how to encrypt with 3rd party public key and sign with private key" – Daniel Brink Apr 23 '10 at 08:29
  • It's so with any asymmetric cryptography - you use public key for encryption and signature verification, and private key is used for signing and decryption. – Eugene Mayevski 'Callback Apr 23 '10 at 16:36

1 Answers1

18

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();
        }
    }
Emmanuel
  • 1,531
  • 11
  • 12