Source : BouncyCastle
Code
RsaKeyPairGenerator g = new RsaKeyPairGenerator();
int size = 1024;
if (size == 1024) {
g.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
}
if (size == 2048) {
g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
}
if (size == 3072) {
g.Init(new KeyGenerationParameters(new SecureRandom(), 3072));
}
AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
string serializedPrivate = Convert.ToBase64String(serializedPrivateBytes);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
string serializedPublic = Convert.ToBase64String(serializedPublicBytes);