I am looking to convert an RSA public key into something that I could use as an SSH public key.
Currently I have Bouncy Castle producing me a public key that looks like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq1Y5300i8bN+cI2U3wJE
Kh3xG/.........jbuz+WB0vvG
P25UwCle2k5siVMwbImEYsr+Xt0dsMmGVB3/6MHAqrM3QQdQ8p2E5TyzL+JYa1FT
gwIDAQAB
-----END PUBLIC KEY-----
I want it to have an RFC 4716 format similar to this:
ssh-rsa AAAAB3NzaC1yc2.......G1p2Ag3mZLFsks7RNHVLgMsGIAikQ==
My Code so far using Bouncy Castle looks like this:
var r = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
r.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
var keys = r.GenerateKeyPair();
var stringWriter = new StringWriter();
var pemWriter = new PemWriter(stringWriter);
pemWriter.WriteObject(keys.Private);
pemWriter.Writer.Flush();
stringWriter.Close();
PrivateKey = stringWriter.ToString();
stringWriter = new StringWriter();
pemWriter = new PemWriter(stringWriter);
pemWriter.WriteObject(keys.Public);
pemWriter.Writer.Flush();
stringWriter.Close();
PublicKey = stringWriter.ToString();
How do I reformat and encode the key to make it look like this?
Has anyone created SSH public keys with Bouncy Castle or similar?
Note: I work at Microsoft but this is not a Microsoft Answer, just Personal.
Adding to Pavels Answer,
I've found that for some reason when generating a 3072 Bit RSA key, PuttyGen would generate a different RSA public key than mine.
After researching, I found that it seems in the source code of the Putty Gen Program it would do .Length + 1 to the Byte array, adding a leading 0.
For the BouncyCastle, you would change this line.
to
For Microsoft .net RSACryptoServiceProvider it would look like this
You can see my Private Key I used for testing & the putty gen source code link https://www.cameronmoten.com/2017/12/21/rsacryptoserviceprovider-create-a-ssh-rsa-public-key/
Realise your post is a few months old now but if you're still looking try the code snippet below, inspired by gotoalberto on Using public key from authorized_keys with Java security ...
I found no ready-to-use function for this in BouncyCastle. So, the workaround is to use
PemReader
and then format the result. The result will be available asPublicSSH
property: