Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interoperability between RSACryptoServiceProvider and openSSL

I've used the .NET class RSACryptoServiceProvider to get a keypair:

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
  File.WriteAllText ("PublicKeyOnly.xml", rsa.ToXmlString (false));
  File.WriteAllText ("PublicPrivate.xml", rsa.ToXmlString (true));
}

Now, I would like to use this with openSSH, but the key format looks nothing alike. Does anyone know how to convert both the public and private keys to files that openSSH can use?

Thanks!

like image 644
Hylke Bons Avatar asked Jul 15 '10 21:07

Hylke Bons


1 Answers

I really needed to achieve Openssl interoperability with RSACryptoServiceProvider, so that I could implement a software licence key system (Ref).

I needed to be able to create the private and public keys in Linux using openssl so that they could later be used for license management in a PHP web application. Yet, also use them as the basis of an RSA signature license system in a VB.Net applciation.

After a week of searching, I eventually discovered that this is perfectly possible, so I thought I would share it.

Start on Linux (or any other useful OS) and use openssl to create a private key (private.pem), a public key (public.pem), a certificate (certificate.crt) and a Personal Information Exchange File (certificate.pfx). Don't worry about the CN and emailAddress fields, the certificate and pfx files are only being used as a vehicle to get the public or private key into the RSACryptoServiceProvider object.

openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -out public.pem -pubout
openssl req -nodes -x509 -days 3650 -subj '/CN=www.example.com/[email protected]' -new -key private.pem -out certificate.crt
openssl pkcs12 -export -out certificate.pfx -inkey private.pem -in certificate.crt

Now to get the private key into the code:

Dim cert As New X509Certificate2("certificate.pfx", "", X509KeyStorageFlags.Exportable)
Dim rsaProvider As RSACryptoServiceProvider = DirectCast(cert.PrivateKey, RSACryptoServiceProvider)

If you need the private key or public key try this:

msgbox(rsaProvider.ToXmlString(True))  'Private key in XML format
msgbox(rsaProvider.ToXmlString(False)) 'Public key in XML format

To get the public key into the code:

Dim cert As New X509Certificate2("certificate.crt")
Dim rsaProvider As RSACryptoServiceProvider = DirectCast(cert.PublicKey.Key, RSACryptoServiceProvider)

If you need the public key try this:

msgbox(rsaProvider.ToXmlString(False))  'Public key in XML format

More to come .....

like image 94
theDuck Avatar answered Sep 17 '22 17:09

theDuck