none
PGP encryption using Visual Studio 2005 RRS feed

Answers

All replies

  • Try to find on codeproject.com or codguru.com .

    I 'd seen this problem solved there.

    Tuesday, April 4, 2006 9:19 PM
  • I donot know much about the PGP encryption, i tried both CodeProject and CodeGuru site but could not get enough information.
    Wednesday, April 5, 2006 6:16 PM
  • 1. Go to google.com

    2 Write query "PGP C# code"

    3. select first, second or threed link

    the second for example is  http://www.codeproject.com/csharp/sharpprivacy.asp?df=100&forumid=15716&exp=0&select=573797 

    Try this method just before to insert the question into forum.

    Regards

    Piotr

    Monday, April 10, 2006 10:44 PM
  • SharpPrivacy seems to be dead.

     

    There's OpenPGPBlackbox offered here.

    Saturday, January 19, 2008 11:32 AM
  •  

    There is an excellent fully self contained C# PGP implementation at bouncycastle.org. For an example of how to encrypt/decrypt a file see the example found in the source code: bouncy_castle\bccrypto-net-1.3-src\csharp\crypto\test\src\openpgp\examples\KeyBasedFileProcessor.cs

     

    Be aware that the source may have to be recompiled for .NET 2.0. I received errors using the .NET 1.1 dll under 2.0.

     

    I needed to send PGP encrypted emails, so I modified the example slightly to encrypt a string:

    Code Snippet

    public static string Encrypt(string input)
    {
      string publicKeyFile;
      PgpPublicKey pubkey;
      Stream keyIn;
                
      publicKeyFile = Server.MapPath("/MyPubKey.asc");
                
      keyIn = File.OpenRead(publicKeyFile);
      pubkey = Pgp.ReadPublicKey(keyIn);
      byte[] original = Encoding.ASCII.GetBytes(input);
      byte[] encrypted = Pgp.Encrypt(original, pubkey);
                
      return Encoding.ASCII.GetString(encrypted);
    }
            
    private static PgpPublicKey ReadPublicKey(
                Stream inputStream)
    {
      inputStream = PgpUtilities.GetDecoderStream(inputStream);

      PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);

               

      foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())
      {
         foreach (PgpPublicKey k in kRing.GetPublicKeys())
         {
            if (k.IsEncryptionKey)
            {
               return k;
            }
         }
      }

      throw new ArgumentException("Can't find encryption key in key ring.");
    }    

     

    private static byte[] Encrypt(byte[] clearData, PgpPublicKey encKey)
    {
       bool armor = true;
       string fileName = PgpLiteralData.Console;

       MemoryStream bOut = new MemoryStream();

     

       PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
         CompressionAlgorithmTag.Zip);


       Stream cos = comData.Open(bOut); // open it with the final destination


       PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

                
       Stream pOut = lData.Open(

    cos, // the compressed output stream
    PgpLiteralData.Binary,
    fileName,    // "filename" to store
    clearData.Length,  // length of clear data
    DateTime.UtcNow   // current time

    );

     

       pOut.Write(clearData, 0, clearData.Length);

       lData.Close();
       comData.Close();

     

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

     

       cPk.AddMethod(encKey);

     

       byte[] bytes = bOut.ToArray();

     

       MemoryStream encOut = new MemoryStream();
       Stream os = encOut;


       if (armor)
       {
        os = new ArmoredOutputStream(os);
       }

     

       Stream cOut = cPk.Open(os, bytes.Length);
       cOut.Write(bytes, 0, bytes.Length);  // get bytes from compressed stream
       cOut.Close();

     

       if (armor)
       {
         os.Close();
       }

     

       encOut.Close();

       return encOut.ToArray();
    }   

     

    Thursday, April 3, 2008 4:40 AM
  • @rjolly- I have been using BouncyCastle to do PGP encryption with the help of your code and also now got clear(?) signing working but I have come up against a problem doing both to send a properly secure PGP email. Have you managed to get this to work?

    A forum post (http://forum.java.sun.com/thread.jspa?threadID=5267501&tstart=255) alludes to doing it in one step but I cannot work it out. Do you have any idea?

    Cheers,

    Richard.
    Friday, June 20, 2008 5:53 PM
  • I managed to work out how to sign and encrypt, so in case anyone else stumbles across this forum looking for Bouncy Castle answers, I thought I would post the code:


    1       private string EncryptAndSign(string input, string recipientPublicKeyPath, string senderPrivateKeyPath, string passPhrase) 
    2        { 
    3 
    4            //get data to encrypt 
    5            byte[] clearData = Encoding.ASCII.GetBytes(input); 
    6 
    7            //create memory stream to hold output from encryption 
    8            MemoryStream finalOut = new MemoryStream(); 
    9 
    10            //enclide output in ascii armour (i.e. base 64 encode) so definietly can be sent over plain text email 
    11            ArmoredOutputStream armouredOut = new ArmoredOutputStream(finalOut); 
    12 
    13            //get public key to encrypt message 
    14            PgpPublicKey encryptionKey = this.ReadPublicKey(recipientPublicKeyPath); 
    15 
    16            //initialise encrypted data generator 
    17            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); 
    18            encryptedDataGenerator.AddMethod(encryptionKey); 
    19            Stream encOut = encryptedDataGenerator.Open(armouredOut, clearData.Length); 
    20 
    21 
    22            //initialise compression 
    23            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); 
    24            Stream compressedOut = compressedDataGenerator.Open(encOut); 
    25 
    26 
    27 
    28            //get signing key (secret key = private key with pass-phrase protection 
    29            PgpSecretKey pgpSecKey = ReadSecretKey(senderPrivateKeyPath); 
    30            //get actual private key to use by unlocaking with pass-phrase 
    31            PgpPrivateKey signingPrivateKey = pgpSecKey.ExtractPrivateKey(passPhrase.ToCharArray()); 
    32 
    33            //initialise signature generator 
    34            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); 
    35             
    36            signatureGenerator.InitSign(PgpSignature.CanonicalTextDocument, signingPrivateKey); 
    37            PgpSignatureSubpacketGenerator subpacketGenerator = new PgpSignatureSubpacketGenerator(); 
    38            System.Collections.IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); 
    39            if (enumerator.MoveNext()) 
    40            { 
    41                subpacketGenerator.SetSignerUserId(false, (string)enumerator.Current); 
    42                signatureGenerator.SetHashedSubpackets(subpacketGenerator.Generate()); 
    43            } 
    44            PgpOnePassSignature onePassSignature = signatureGenerator.GenerateOnePassVersion(false); 
    45            onePassSignature.Encode(compressedOut); 
    46 
    47            // Create the Literal Data generator Output stream which writes to the compression stream 
    48            string fileName = PgpLiteralData.Console; 
    49 
    50            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); 
    51            Stream literalOut = literalDataGenerator.Open(compressedOut, // the compressed output stream 
    52                                                    PgpLiteralData.Binary, 
    53                                                    fileName,    // "filename" to store 
    54                                                    clearData.Length,  // length of clear data 
    55                                                    DateTime.UtcNow   // current time 
    56                                                    ); 
    57 
    58 
    59            //write data to output stream (eventually - goes through literal stream, compression stream, and encryption stream on the way!) 
    60            literalOut.Write(clearData, 0, clearData.Length); 
    61 
    62            //update signature generator with data 
    63            signatureGenerator.Update(clearData, 0, clearData.Length); 
    64 
    65            //close literal output 
    66            literalOut.Close(); 
    67            literalDataGenerator.Close(); 
    68 
    69 
    70            //generate signature and send to output stream 
    71            signatureGenerator.Generate().Encode(compressedOut); 
    72            //close other output streams 
    73            compressedOut.Close(); 
    74            compressedDataGenerator.Close(); 
    75            encOut.Close(); 
    76            encryptedDataGenerator.Close(); 
    77            armouredOut.Close(); 
    78            finalOut.Close(); 
    79            return Encoding.ASCII.GetString(finalOut.ToArray()); 
    80 
    81        } 
    82 
    83        private PgpSecretKey ReadSecretKey(string senderPrivateKeyPath) 
    84        { 
    85 
    86            Stream keyIn = File.OpenRead(senderPrivateKeyPath); 
    87            Stream inputStream = PgpUtilities.GetDecoderStream(keyIn); 
    88            PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(inputStream); 
    89            inputStream.Close(); 
    90            keyIn.Close(); 
    91 
    92            // just loop through the collection till we find a key suitable for encryption 
    93            // assuming only one key in there 
    94 
    95            foreach (PgpSecretKeyRing kRing in pgpSec.GetKeyRings()) 
    96            { 
    97                foreach (PgpSecretKey k in kRing.GetSecretKeys()) 
    98                { 
    99                    if (k.IsSigningKey) 
    100                    { 
    101                        return k; 
    102                    } 
    103                } 
    104            } 
    105 
    106            throw new ArgumentException("Can't find signing key in key ring."); 
    107        } 
    108 
    109        private PgpPublicKey ReadPublicKey(string publicKeyPath) 
    110        { 
    111            Stream keyIn = File.OpenRead(publicKeyPath); 
    112            Stream inputStream = PgpUtilities.GetDecoderStream(keyIn); 
    113            PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream); 
    114            inputStream.Close(); 
    115            keyIn.Close(); 
    116 
    117            foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings()) 
    118            { 
    119                foreach (PgpPublicKey k in kRing.GetPublicKeys()) 
    120                { 
    121                    if (k.IsEncryptionKey) 
    122                    { 
    123                        return k; 
    124                    } 
    125                } 
    126            } 
    127            throw new ArgumentException("Can't find encryption key in key ring."); 
    128        } 
    129 
    130 

    A great tip for anyone else trying to get to grips with Bouncy Castle is to have a look at their mailing list archives at http://www.bouncycastle.org/devmailarchive/threads.html.

    • Edited by RichardSudworth Monday, June 23, 2008 3:56 PM Spelling mistake
    • Proposed as answer by zander8778 Thursday, March 5, 2009 6:55 PM
    Monday, June 23, 2008 3:56 PM
  • Hi RichardSudworth,

    Recently when I was looking for open source PGP in .net, I came acroos your post.
    This is a very good example which matched my requirement.

    Do you by any chance has a "Decrypt" method also? Can you please share the "Decrypt" method code?

    Thanks in advance.

    Cheers,
    Suhas
    Tuesday, February 10, 2009 7:49 PM
  • I have also used the above code and it seems to work great.  If you have an example of how to decrypt that would be great.
    Thursday, March 5, 2009 6:47 PM
  • I took the code from the console application KeyBasedFileProcessor.cs contained in the examples foler in bccrypto-net-1.4-src and changed it to a class that can be used in a Windows or Web application.  It can encrypt and decrypt a file.  It needs some refactoring but it gets the job done.  Hope this helps.

    using System;

    using System.Collections;

    using System.IO;

    using Org.BouncyCastle.Bcpg.OpenPgp;

    using Org.BouncyCastle.Security;

    using Org.BouncyCastle.Utilities.IO;

    using Org.BouncyCastle.Bcpg;

    namespace Org.BouncyCastle.Crypto

    {

    public class PGPEncryptDecrypt

    {

    public PGPEncryptDecrypt()

    {

    }

    /**

    * A simple routine that opens a key ring file and loads the first available key suitable for

    * encryption.

    *

    * @param in

    * @return

    * @m_out

    * @

    */

    private static PgpPublicKey ReadPublicKey(Stream inputStream)

    {

    inputStream = PgpUtilities.GetDecoderStream(inputStream);

    PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);

    //

    // we just loop through the collection till we find a key suitable for encryption, in the real

    // world you would probably want to be a bit smarter about this.

    //

    //

    // iterate through the key rings.

    //

    foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())

    {

    foreach (PgpPublicKey k in kRing.GetPublicKeys())

    {

    if (k.IsEncryptionKey)

    {

    return k;

    }

    }

    }

    throw new ArgumentException("Can't find encryption key in key ring.");

    }

    /**

    * Search a secret key ring collection for a secret key corresponding to

    * keyId if it exists.

    *

    * @param pgpSec a secret key ring collection.

    * @param keyId keyId we want.

    * @param pass passphrase to decrypt secret key with.

    * @return

    */

    private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyId, char[] pass)

    {

    PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId);

    if (pgpSecKey == null)

    {

    return null;

    }

    return pgpSecKey.ExtractPrivateKey(pass);

    }

    /**

    * decrypt the passed in message stream

    */

    private static void DecryptFile(Stream inputStream, Stream keyIn, char[] passwd, string defaultFileName, string pathToSaveFile)

    {

    inputStream = PgpUtilities.GetDecoderStream(inputStream);

    try

    {

    PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);

    PgpEncryptedDataList enc;

    PgpObject o = pgpF.NextPgpObject();

    //

    // the first object might be a PGP marker packet.

    //

    if (o is PgpEncryptedDataList)

    {

    enc = (PgpEncryptedDataList)o;

    }

    else

    {

    enc = (PgpEncryptedDataList)pgpF.NextPgpObject();

    }

    //

    // find the secret key

    //

    PgpPrivateKey sKey = null;

    PgpPublicKeyEncryptedData pbe = null;

    PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(

    PgpUtilities.GetDecoderStream(keyIn));

    foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())

    {

    sKey = FindSecretKey(pgpSec, pked.KeyId, passwd);

    if (sKey != null)

    {

    pbe = pked;

    break;

    }

    }

    if (sKey == null)

    {

    throw new ArgumentException("secret key for message not found.");

    }

    Stream clear = pbe.GetDataStream(sKey);

    PgpObjectFactory plainFact = new PgpObjectFactory(clear);

    PgpObject message = plainFact.NextPgpObject();

    if (message is PgpCompressedData)

    {

    PgpCompressedData cData = (PgpCompressedData)message;

    PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());

    message = pgpFact.NextPgpObject();

    }

    if (message is PgpLiteralData)

    {

    PgpLiteralData ld = (PgpLiteralData)message;

    string outFileName = ld.FileName;

    if (outFileName.Length == 0)

    {

    outFileName = defaultFileName;

    }

    Stream fOut = File.Create(pathToSaveFile + outFileName);

    Stream unc = ld.GetInputStream();

    Streams.PipeAll(unc, fOut);

    fOut.Close();

    }

    else if (message is PgpOnePassSignatureList)

    {

    throw new PgpException("encrypted message contains a signed message - not literal data.");

    }

    else

    {

    throw new PgpException("message is not a simple encrypted file - type unknown.");

    }

    if (pbe.IsIntegrityProtected())

    {

    if (!pbe.Verify())

    {

    Console.Error.WriteLine("message failed integrity check");

    }

    else

    {

    Console.Error.WriteLine("message integrity check passed");

    }

    }

    else

    {

    Console.Error.WriteLine("no message integrity check");

    }

    }

    catch (PgpException e)

    {

    Console.Error.WriteLine(e);

    Exception underlyingException = e.InnerException;

    if (underlyingException != null)

    {

    Console.Error.WriteLine(underlyingException.Message);

    Console.Error.WriteLine(underlyingException.StackTrace);

    }

    }

    }

    private static void EncryptFile(Stream outputStream, string fileName, PgpPublicKey encKey, bool armor, bool withIntegrityCheck)

    {

    if (armor)

    {

    outputStream = new ArmoredOutputStream(outputStream);

    }

    try

    {

    MemoryStream bOut = new MemoryStream();

    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(

    CompressionAlgorithmTag.Zip);

    PgpUtilities.WriteFileToLiteralData(

    comData.Open(bOut),

    PgpLiteralData.Binary,

    new FileInfo(fileName));

    comData.Close();

    PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(

    SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

    cPk.AddMethod(encKey);

    byte[] bytes = bOut.ToArray();

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

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

    cOut.Close();

    if (armor)

    {

    outputStream.Close();

    }

    }

    catch (PgpException e)

    {

    Console.Error.WriteLine(e);

    Exception underlyingException = e.InnerException;

    if (underlyingException != null)

    {

    Console.Error.WriteLine(underlyingException.Message);

    Console.Error.WriteLine(underlyingException.StackTrace);

    }

    }

    }

    public void Encrypt(string filePath, string publicKeyFile, string pathToSaveFile)

    {

    Stream keyIn, fos;

    keyIn = File.OpenRead(publicKeyFile);

    string[] fileSplit = filePath.Split('\\');

    string fileName = fileSplit[fileSplit.Length - 1];

    fos = File.Create(pathToSaveFile + fileName + ".asc");

    EncryptFile(fos, filePath, ReadPublicKey(keyIn), true, true);

    keyIn.Close();

    fos.Close();

    }

    public void Decrypt(string filePath, string privateKeyFile, string passPhrase, string pathToSaveFile)

    {

    Stream fin = File.OpenRead(filePath);

    Stream keyIn = File.OpenRead(privateKeyFile);

    DecryptFile(fin, keyIn, passPhrase.ToCharArray(), new FileInfo(filePath).Name + ".out", pathToSaveFile);

    fin.Close();

    keyIn.Close();

    }

    }

    }

    • Proposed as answer by jkelly75 Friday, May 14, 2010 6:26 PM
    Friday, March 6, 2009 7:00 AM
  • hi zander8778, but the thing is im getting object reference not set to an instance error over here when decrypting the file.

     

    foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())

    as enc is null.can you please help me over here.

    Wednesday, May 6, 2009 9:51 AM
  • hi zander, thanx for the code u ve given.it works perfect.
    Saturday, May 9, 2009 6:04 AM
  • hi zander , the code u ve given is working perfect..but i want to do some changes over here u r  passing publickey and private key from a file with the keys generated from pgp desktop but here i want to pass the keys by specifying the values in the web.config .. so can u please help me with this..:)
    Tuesday, May 12, 2009 9:39 AM
  • hi zander, thnx for the reply. yeah i am able encrypt and decrypt the file by specifying a key in web.config. previously the mistake i was doing is i was not considering the new line instance which it was expecting.so it was throwing me error.

    theres one more issue with which i am struck . the thing is previously i was generating the keys using pgp desktop but now i need to generate the on my own ie using c# code and i am unable to generate the correct keys.i ve tried several ways by using chilkat dll and by using rsakeygenerator but i am unable to encrypt and decrypt using those.
    pavankumar kavety
    Tuesday, May 19, 2009 12:52 PM
  • hi zander, thnx for the reply. yeah i am able encrypt and decrypt the file by specifying a key in web.config. previously the mistake i was doing is i was not considering the new line instance which it was expecting.so it was throwing me error.

    theres one more issue with which i am struck . the thing is previously i was generating the keys using pgp desktop but now i need to generate the on my own ie using c# code and i am unable to generate the correct keys.i ve tried several ways by using chilkat dll and by using rsakeygenerator but i am unable to encrypt and decrypt using those.
    pavankumar kavety
    Can I ask why you are planning on using your keys in this manner? Normally, encryption keys are things that are strictly managed - by generating the keys in your code, you kind of loose a bit of the security involved with the concept. Also, how are you going to manage your keys? If you generate a key in your code, then encrypt something with it how are you then going to communicate that to the recipient? Also, if the recipient is always getting encrypted files from you, how will they know which lkey to use? I have been working with PGP encryption a bit lately, in a very large organisation. They only have a few keys (less than five) to encrypt files for certain destinations. When the keys change (which they do), we need to communicate this out to our recipients well in advance. I know this doesnt help you much with your initial question, and I hate to see messages that seem to ridicule people on forums, but I am totally confused as to how you are going to manage your keys etc.

    I should also point out that all Zander has done so far is copy and paste the C# examples from BouncyCastle.org. If you take a look at the examples they provide, there is a complete section on generating keys.
    Sunday, June 7, 2009 3:13 PM
  • thanks for the code.
    Wednesday, May 26, 2010 3:23 AM
  • Regarding Richard Sudworth's post and the bouncy castle solution:

    BINGO.  I'm new to PGP and had to encrypt with their public key, then sign with my private key.  The trick is that this needs to be done in a "one pass" process and this method you describe here is just what is needed.

    I had a problem with loading the private key getting a cluster of errors, one being "unknown object in stream 21".  To resolve I re-exported the private key, copied the text from the private key asc file, placed it in a .txt file and used that.  I have no idea why this helped, but it worked.

    It was hard to find a library that did this, and bingo here it is.  So thank you for your post.

    Tuesday, December 14, 2010 7:57 PM
  • Those interested in BouncyCastle's OpenPGP implementation may like to know that we have recently released version 1.7, which can be downloaded from http://www.bouncycastle.org/csharp

     

    Sunday, April 10, 2011 3:32 PM
  • I know it's been a long time since you posted this answer/solution, but I wanted to thank you anyway.  I'd been searching the internet for quite some time looking for a simple, concrete, workable way of using BouncyCastle and PGP to encrypt AND decrypt.  Encrypt was easy, but for some reason decrypt examples were much more scarce and most didn't even work.

    Your solution worked perfectly and my code is tons cleaner because of it.

    Now I can go back through your code and figure out how it works.

    Thank you very much.

    Tuesday, October 4, 2011 2:00 PM
  • I know this thread is really old BUT I was writting an encryption engine using the Bouncy Castle Library (for C#). While working on it I hit the same error that CoreyMagin hit "unknown object in stream 21".

    I google the crap out of it and couldn't find any help, but did find a few pages like this where other hit the error. Corey's solution didn't work for me, So I am posting this here for anyone else that runs into the problem.

    The problem is either with the key being used or with ArmoredInputStream (in ArmoredInputStream.ParseHeaders()). But after 18 hrs straight of debugging the stupid thing, the bottom line is ArmoredInputStream.ParseHeaders() is expecting the headers in the key to be format like so:

    -----BEGIN PGP PUBLIC KEY BLOCK-----\r\n

    Version: FileCrypt eBusiness 3.7.2\r\n

    Comment: www.veridis.com\r\n

    \r\r\n

    key......

    -----END PGP PUBLIC KEY BLOCK-----

    (with \r = carriagr return and \n = line feed)

    The key I was given by a client (which threw the error) Was formatted like this:

    -----BEGIN PGP PUBLIC KEY BLOCK-----\r\r\n

    Version: FileCrypt eBusiness 3.7.2\r\r\n

    Comment: www.veridis.com\r\r\n

    \r\r\n

    key......
    -----END PGP PUBLIC KEY BLOCK-----


    Note the extra \r (carriage return) on the 1st 3 lines of the header.

    So either a key is supposed to be formatted with only \r\n for the end of a header line and \r\r\n for the end of the header section or the code does not read all key formats correctly. ArmoredInputStream.ParseHeaders() loops through the headers until it see \r\r\n which it then breaks out of the loop (assuming the headers are done)

    Looking at the code: approx line 212 (I am anal about formatting and reformatted the src code ;-)

                            if (c == '\r' || (last != '\r' && c == '\n'))
                            {
                                eolReached = true;
                            }
    

    the first time it get \r is sets eolReached

    When it loops back through (approx line 192) if it find a 2nd \r it thinks it is done extracting the headers.

                        if (eolReached && c == '\r')
                        {
                            break;
                        }
    

    So I do not know if this is a problem with certain key generators breaking the key format or if this is a bug in Bouncy Castle. But it can be solved by editing the key or editing the code. (I haven't decided which to do)

    Wednesday, October 19, 2011 8:12 PM
  • I had this problem using Visual Studio 2015 and the Bouncy-Castle library when I called the PgpPublicKeyRingBundle function.

    unknown object in stream 47

    I had created the PublicKey.asc and PrivateKey.asc text files using Visual Studio Text files.

    By default VS uses Unicode UTF-8 encoding.

    You'll need to change this to US-ASCII.

    • From the menu select File -> Save As
    • On the "Save" button there will be a drop down menu where you can select "Save with Encoding"
    • Select US-ASCII
    Friday, January 19, 2018 10:47 PM