Using the BouncyCastle API
http://www.bouncycastle.org/
and something similar to the following:
public AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits) { RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), keySizeInBits)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); return keys; }
You can access an object that will have properties. Public and. Private with correctly formatted strings.
Some time ago I had a similar problem and this was the best solution I could find. I do not have the exact code, but I will publish it when I come to the office, if necessary, but the above should work.
Updated with code
This is the code that I used to generate public / private keys.
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Security; public static AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits) { var r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(),keySizeInBits)); var keys = r.GenerateKeyPair(); return keys; } static void Main(string[] args) { var keys = GenerateKeys(2048); var publicKey = keys.Public.ToString(); var textWriter = new StreamWriter("private.key"); var pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keys.Private); pemWriter.Writer.Flush(); textWriter.Close(); textWriter = new StreamWriter("public.key"); pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keys.Public); pemWriter.Writer.Flush(); textWriter.Close(); Console.ReadKey(); }
source share