C#: Import a rsa public key generated by openssl

Hi,

the C# (.NET 4) RSACryptoServiceProvider->ImportCspBlob methode has the ability to import RSA (public) keys.

It use the Microsoft BLOB format and this cannot be changed. Hint: .NET Core can directly import PKCS1 keys.

If you want to import a RSA public key generated by openssl it must be exported in the correct format ImportCspBlob understands. When you try to import the default openssl public key format you will get an error

bad version of provider

openssl can export a key in the MS CryptoApi format. Set output format as “MS PUBLICKEYBLOB” respectively for a private key “MS PRIVATEKEYBLOB”.

openssl rsa -in my.key -passin pass:mySecret -RSAPublicKey_out -outform "MS PUBLICKEYBLOB" -out my_rsa.pem

And get the base64 signature

openssl base64 -in my_rsa.pem

For example: Verify a file integrity created by this post. You can use the base64 signature output from the openssl command or read signature from the pem file.

using System.Security.Cryptography;
namespace TestRSAPublicKey
{
    class Program
    {
        static string PubKey= @"BgIAAACkAABSU0ExAAgAAAEAAQCpnLBNQxZ+2i30CJ7Rq2j6Lyf/YUkRVyok7ACM
HdQMhvrW8297fE7EjU36Y7RbaXJakOIPS78AAudG1V6mpAEyttMEPZHu30rjdUIs
tbxTiy5Q70MoAU5cxnWi0/x3IUiQSWOeIQoeF1I1icqA06vOfomNEVedDrVjFVdG
yP06nD3xESvBiyRS4+pqntDd45IBsWk0fjRsW6PkIygRan+oX/GPoYQ9s1sRDTC5
C4Nku7T/Ek7KZ96KBiAjME2BKDuH6qawIqzrfKyOs3w3dMPi5MqOWRRjKWhOEaQI
iAj9Nx6jvTUUB5q6DQWqOq7Ahkg4UVuHazOIVhiI+CnO9BLW";
        static void Main(string[] args)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            // byte[] pubKeyBytes = Convert.FromBase64String(PubKey);
            byte[] pubKeyBytes = System.IO.File.ReadAllBytes(@"D:\temp\my_rsa.pem");
            rsa.ImportCspBlob(pubKeyBytes);
            SHA256Managed sha256 = new SHA256Managed();
            byte[] data = System.IO.File.ReadAllBytes(@"D:\temp\ImportendData.txt");
            byte[] hash = sha256.ComputeHash(data);
            byte[] signature = System.IO.File.ReadAllBytes(@"D:\temp\ImportendData.txt.sign");
            bool Result=rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), signature);
        }
    }
}

Michael

Leave a Reply Cancel reply