Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate SSH 2 RSA key in C# application?

Tags:

c#

.net

ssh

rsa

putty

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!

like image 910
Gábor Domonkos Avatar asked Jul 29 '14 16:07

Gábor Domonkos


People also ask

Can we generate 2 SSH keys?

Generate two different SSH keys in the local Git repository. ssh-keygen -t rsa -C "email" Generating public/private rsa key pair. Enter file in which to save the key (~/. ssh/id_rsa):< Type two file names before pressing Enter. >

What is the command to generate RSA keys for SSH?

Run ssh-keygen to generate an SSH key-pair.


1 Answers

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.

like image 100
janw Avatar answered Sep 16 '22 13:09

janw