Interoperability between RSACryptoServiceProvider and openSSL

后端 未结 2 2007
青春惊慌失措
青春惊慌失措 2021-02-07 20:25

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

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
  File.         


        
2条回答
  •  北海茫月
    2021-02-07 21:19

    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/emailAddress=info@example.com' -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 .....

提交回复
热议问题