11

I would like to write an application that will generate SSH 2 RSA public and private keys as well.

I would like to get the keys as format as the PuTTY Key Generator can generate.

enter image description here

With the help of ChilKat I can generate the public and private keys as well, but I don't know how to get that kind of format.

Is there any sample to get the keys at that format or I missed something?

Thank you very much!

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
Gábor Domonkos
  • 1,081
  • 1
  • 17
  • 33

2 Answers2

7

The SSH key format is rather complex; if you want to implement it yourself, this, this and this answer might be a good start.

However, someone else actually already did the work and created a NuGet package for generating SSH keys: SshKeyGenerator. Right now the package is offered for both .NET Framework and .NET Standard. The source code is available on GitHub.

Example code:

static void Main(string[] args)
{
    int keyBits = 2048;
    string keyComment = "mykey";

    var keygen = new SshKeyGenerator.SshKeyGenerator(keyBits);

    Console.WriteLine(keygen.ToPrivateKey());
    Console.WriteLine(keygen.ToRfcPublicKey(keyComment));
}

generates (shortened for readability)

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA7ejxsqTKLMLht6HVC57l59mMzQNIVdeMaPzxM14VYjkyU1rg
...
L4NAI1BCgGpSC+iY3QuVwK8GVphVSzNrOQj97Uuhx0WYsEdPzJvjQw==
-----END RSA PRIVATE KEY-----

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD...nFX7Rhou4OdkDGA1 mykey

Note that the package currently does not support setting a private key passphrase.

janw
  • 8,758
  • 11
  • 40
  • 62
2

I found a solution: Download the Chilkat.NET Nuget from the Nuget Gallery. With the help of this library, you can generate an RSA Key Pair in the following way:

public ISshKeyPair RsaKeyPair()
{
   Chilkat.SshKey key = new Chilkat.SshKey();

   bool success;
   int numBits;
   int exponent;
   numBits = 2048;
   exponent = 65537;
   success = key.GenerateRsaKey(numBits, exponent);
   var sshKeyPair = new SshKeyPair();
   sshKeyPair.PublicKey = key.ToOpenSshPublicKey();
   sshKeyPair.PrivateKey = key.ToPuttyPrivateKey(false);
   if (!success) RsaKeyPair();
   return sshKeyPair;
}

Cheers!

Gábor Domonkos
  • 1,081
  • 1
  • 17
  • 33
  • 2
    I think Chilkat is paid software. Can you provide another approach with free source code? Thanks :) – SuperJMN Feb 20 '20 at 16:47