Skip to content

ShawInnes/SshKeyGenerator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DotNet Core SSH KeyGen

Build status NuGet version (SshKeyGenerator)

After searching around for a solution to creating SSH keys using C# and dotnet core I came across the following stackoverflow posts which explain how to convert from RSACryptoServiceProvider to values suitable for use with ssh.

Supported Platforms

  • .NET 4.5 (Desktop / Server)
  • .NET Standard 2.0
  • .NET Standard 2.1
  • .NET 5.0
  • .NET 6.0

Installation

SshKeyGenerator is a library for .NET and is available on NuGet:

Install-Package SshKeyGenerator

or

dotnet add package SshKeyGenerator

Usage Example

var keygen = new SshKeyGenerator.SshKeyGenerator(2048);

var privateKey = keygen.ToPrivateKey();
Console.WriteLine(privateKey);

var publicSshKey = keygen.ToRfcPublicKey();
Console.WriteLine(publicSshKey);

var publicSshKeyWithComment = keygen.ToRfcPublicKey("[email protected]");
Console.WriteLine(publicSshKeyWithComment);

Sample Output

keygen.ToPrivateKey()

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAs1O/9F2XlZVaVWEUYfflxx0wDG9FE09hQF2wngA6EemHpe6I
hvdwvQ7obrZ85jSYdBxBRjNAYF3T9+wU+8w6m4qZCVYvqqRjszN8j3VwUBLzWilt
...
wDGzJIkmbhANi+252pH6PAuWjZPfz8COGA6QPPH0/khpHPj1LY4mi5Ubi3YT1uRo
dOGttjtkj9fLX5IQ81G9HR0MdT1Gd4fPenYPOUCgCPB5adpT1BB+
-----END RSA PRIVATE KEY-----

keygen.ToRfcPublicKey()

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzU7/0XZeVlVpVYRRh9
...
+ohFsbcbAMcfLWGUdouyHvLvF21G0z50z2i2CrU7WW4WdrGGfxhU3TeRTXd7Skwk/K7iBBn3oc/xct generated-key

keygen.ToRfcPublicKey("[email protected]")

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzU7/0XZeVlVpVYRRh9
...
+ohFsbcbAMcfLWGUdouyHvLvF21G0z50z2i2CrU7WW4WdrGGfxhU3TeRTXd7Skwk/K7iBBn3oc/xct [email protected]

Export Methods

There are three methods which can be used to export SSH key data for use by other libraries such as FxSsh:

  1. byte[] ToBlobs : Export as Blobs
  2. string ToB64Blob : Export blobs as base64 string
  3. string ToXml : Export as XML string

Export methods usage:

// Create a new instance 
var keygen = new SshKeyGenerator.SshKeyGenerator(4096);

// Get Base64 encoded keys with private key
var base64Keys = keygen.ToB64Blob(true);

// Use in a SSH server. e.g. FxSsh
var server = new SshServer();
server.AddHostKey("ssh-rsa", base64Keys);

References

Contributors

Thanks to the following contributors for their assistance with this library.