title: Generating ASC files with Bouncy Castle C#
body: <p>I have this piece of code where its been generated a public and private key using Bouncy Castle API:</p>
  <pre><code>        RsaKeyPairGenerator g = new RsaKeyPairGenerator();
          g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
          AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();
  
          RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;
          RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;
  </code></pre>
  <p>I need to export my keys for an ASC file, for example:</p>
  <ul>
  <li>PublicKey.asc</li>
  <li>PrivateKey.asc</li>
  </ul>
  <p>At the moment, I'm using the code below to create the ASC files:</p>
  <pre><code>        TextWriter tw = new StringWriter();
          PemWriter pw = new PemWriter(tw);
          pw.WriteObject(publicKey);
          pw.Writer.Flush();
          string printPublicKey = tw.ToString();
          Console.WriteLine(printPublicKey);
  
          byte[] pbkasc = Encoding.ASCII.GetBytes(printPublicKey); 
          File.WriteAllBytes(&quot;c:\\temp\\PublicKey.asc&quot;, pbkasc);
  
          pw.WriteObject(privateKey);
          pw.Writer.Flush();
          string printPrivateKey = tw.ToString();
          Console.WriteLine(printPrivateKey);
  
          byte[] pvkasc = Encoding.ASCII.GetBytes(printPrivateKey);
          File.WriteAllBytes(&quot;c:\\temp\\PublicKey.asc&quot;, pvkasc);
  </code></pre>
  <p>But when I try to import them, to a third party software, Kleopatra for example, I'm receiving the error below:</p>
  <p><a href="https://i.stack.imgur.com/GFqAv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GFqAv.png" alt="Error here" /></a></p>
  <p>I'm beginner with all this encryption stuff. So, I need to know if I'm doing that in the correct way or if there is any other to generate those asc files. I did some research and I find this certificate generator:</p>
  <pre><code>        //// Create PFX (PKCS #12) with private key
          //File.WriteAllBytes(&quot;c:\\temp\\capronizera.pfx&quot;, cert.Export(X509ContentType.Pfx, &quot;senha&quot;));
  
          //// Create Base 64 encoded CER (public key only)
          //File.WriteAllText(&quot;c:\\temp\\mycert.cer&quot;,
          //    &quot;-----BEGIN CERTIFICATE-----\r\n&quot;
          //    + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
          //    + &quot;\r\n-----END CERTIFICATE-----&quot;);
  </code></pre>
  <p>But unfortunately, it doesn't apply for my issue/question/doubt.</p>
  <p>Thanks. :-)</p>