I have this piece of code where its been generated a public and private key using Bouncy Castle API:
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;
I need to export my keys for an ASC file, for example:
- PublicKey.asc
- PrivateKey.asc
At the moment, I'm using the code below to create the ASC files:
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("c:\\temp\\PublicKey.asc", pbkasc);
pw.WriteObject(privateKey);
pw.Writer.Flush();
string printPrivateKey = tw.ToString();
Console.WriteLine(printPrivateKey);
byte[] pvkasc = Encoding.ASCII.GetBytes(printPrivateKey);
File.WriteAllBytes("c:\\temp\\PublicKey.asc", pvkasc);
But when I try to import them, to a third party software, Kleopatra for example, I'm receiving the error below:
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:
//// Create PFX (PKCS #12) with private key
//File.WriteAllBytes("c:\\temp\\capronizera.pfx", cert.Export(X509ContentType.Pfx, "senha"));
//// Create Base 64 encoded CER (public key only)
//File.WriteAllText("c:\\temp\\mycert.cer",
// "-----BEGIN CERTIFICATE-----\r\n"
// + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
// + "\r\n-----END CERTIFICATE-----");
But unfortunately, it doesn't apply for my issue/question/doubt.
Thanks. :-)