C#: Import a rsa public key generated by openssl


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
        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");
            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);


Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.