Created
March 11, 2020 07:19
-
-
Save eaba/e52fea4304d3c9ce5a0942e5cc1cf4e0 to your computer and use it in GitHub Desktop.
BouncyCastle RSA keys to bytes and back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| RsaKeyPairGenerator r = new RsaKeyPairGenerator(); | |
| r.Init(new KeyGenerationParameters(prng, 2048)); | |
| AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); | |
| SubjectPublicKeyInfo pubF = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public); | |
| byte[] pubbytes = pubF.GetDerEncoded(); | |
| PrivateKeyInfo privF = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private); | |
| byte[] privBytes = privF.GetDerEncoded(); | |
| // encrypt with public | |
| SubjectPublicKeyInfo pbInfo = SubjectPublicKeyInfo.GetInstance(pubbytes); | |
| AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(pbInfo); | |
| IAsymmetricBlockCipher encryptEngine = new RsaEngine(); | |
| encryptEngine.Init(true, pubKey); | |
| byte[] dt = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | |
| byte[] encDt = encryptEngine.ProcessBlock(dt, 0, dt.Length); | |
| // decrypt with private | |
| PrivateKeyInfo pkInfo = PrivateKeyInfo.GetInstance(privBytes); | |
| AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(pkInfo); | |
| IAsymmetricBlockCipher decryptEngine = new RsaEngine(); | |
| decryptEngine.Init(false, privateKey); | |
| byte[] decDt = decryptEngine.ProcessBlock(encDt, 0, encDt.Length); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment