Home > other >  RSA Encryption in C# PEM format
RSA Encryption in C# PEM format

Time:06-09

I have a method in C# that I pass a public key string.

public string RsaEncryptWithPublic(string clearText, string publicKey)

    {
      byte[] bytes = Encoding.UTF8.GetBytes(clearText);
      Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding((IAsymmetricBlockCipher) new RsaEngine());
      using (StringReader reader = new StringReader(publicKey))
      {
        AsymmetricKeyParameter parameters = (AsymmetricKeyParameter) new PemReader((TextReader) reader).ReadObject();
        pkcs1Encoding.Init(true, (ICipherParameters) parameters);
      }
      return Convert.ToBase64String(pkcs1Encoding.ProcessBlock(bytes, 0, bytes.Length));
    }

The public key string that I pass is

string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTlwYb3N m4v6IME 4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh7LTD4xXOaGDJHjX5 YgqK4fb9rs ImjMpIACrND/LAdrq5mctWWzw3UtW3F o sNwIZM8n65ysS Vhq9IypFlfuQbWrKjAcWZ3u1iLtplz yf/pjhOEyyZiBUnh6D219 pMiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmA KYxVgA9BGXPEGE89dQbeJsieTj FSsp9oTm 4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKPtwIDA QAB";

I get an error Org.BouncyCastle.Security.InvalidKeyException: 'Not an RSA key'. Is the publickey format that I passed to the method is incorrect?

CodePudding user response:

The posted key is an RSA key in X.509/SPKI format. PemReader expects a PEM encoded key. However, the posted key is not PEM encoded, it is missing header, footer and line breaks after every 64 characters. The PEM encoded key looks like this:

string publicKey = @"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTl
wYb3N m4v6IME4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh
7LTD4xXOaGDJHjX5 YgqK4fb9rsImjMpIACrND/LAdrq5mctWWzw3UtW3F o sNw
IZM8n65ysS Vhq9IypFlfuQbWrKjAcWZ3u1iLtplzyf/pjhOEyyZiBUnh6D219 p
MiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmAKYxVgA9BG
XPEGE89dQbeJsieTj FSsp9oTm 4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKP
twIDAQAB
-----END PUBLIC KEY-----";

Regarding line breaks PemReader is tolerant: Only header and footer must be in separate lines.

Btw, as of .NET Core 3.0, import of a DER encoded RSA key in X.509/SPKI format is supported by RSA.ImportSubjectPublicKeyInfo(). As of .NET 5, import of PEM encoded RSA keys is supported with RSA.ImportFromPem().

  • Related