Skip to content

Instantly share code, notes, and snippets.

@sadrakgunadi
Last active March 25, 2023 20:12
Show Gist options
  • Save sadrakgunadi/43634752ea5e750bc5f86c78d6e7ed66 to your computer and use it in GitHub Desktop.
Save sadrakgunadi/43634752ea5e750bc5f86c78d6e7ed66 to your computer and use it in GitHub Desktop.
Generate RSA Key Pair with BouncyCastle

Generate RSA Key Pair with BouncyCastle

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment