3

I have RSA public key encoded in Base64. After decoding I can get RSA public key like:

-----BEGIN PUBLIC KEY----- XXXXXXXXXXXXXXXXXXXXXXX -----END PUBLIC KEY-----

Now I need to import this key into RSACryptoServiceProvider. I was looking for solution but wasn't able to find anything working. From pieces I found, I created such code sample

    public static string Encrypt(string input, string base64PublicKey)
    {
        var rsa = new RSACryptoServiceProvider();
        var byteKey = System.Convert.FromBase64String(base64PublicKey);
        var byteInput = Encoding.UTF8.GetBytes(input);

        var parameters = rsa.ExportParameters(false);
        parameters.Modulus = byteKey;

        rsa.ImportParameters(parameters);

        var bytesEncrypted = rsa.Encrypt(byteInput, false);

        var result = System.Convert.ToBase64String(bytesEncrypted);

        return result;
    }

I suppose it is not working correctly, because I always get response with error from the system I'm integrating with.

Is it a correct way to import public key? If not how should I do it?

Filip Szesto
  • 153
  • 2
  • 14

1 Answers1

4

The public key you have is presumably encoded in the PKCS#1 format, which is the common standard for encoding RSA public keys.

The .NET crypto classes do not understand this format directly, you will have to parse the ASN.1 encoding yourself to get the modulus and public exponent from your key and set the corresponding parameters ouf your RSAParameters object.

Community
  • 1
  • 1
mat
  • 1,645
  • 15
  • 36