snowflakes74
snowflakes74

Reputation: 1307

Load RSA public key from RSAParams

I have a requirement to generate RSA key pair in C# and then store public key in the database to be used in JWK format later on.

But I am unable to get the string from the RSAParams.Modulus.

I have tried UTF8,UTF32 and general encoding but still it is not showing.

Here is the code below from MSDN site.

try
        {
            // Create a new RSACryptoServiceProvider object.
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {

                //Export the key information to an RSAParameters object.
                //Pass false to export the public key information or pass
                //true to export public and private key information.
                RSAParameters RSAParams = RSA.ExportParameters(true);

                byte[] modulus = RSAParams.Modulus;
                var str = System.Text.Encoding.UTF8.GetString(RSAParams.Modulus);
                Console.WriteLine(str);
                Console.ReadKey();

            }
        }
        catch (CryptographicException e)
        {
            //Catch this exception in case the encryption did
            // not succeed.
            Console.WriteLine(e.Message);
        }

Thank you.

Upvotes: 0

Views: 470

Answers (1)

a-ctor
a-ctor

Reputation: 3733

I assume that you want your output to be base64. Then you can use Convert.ToBase64String to convert the Exponent and the Modulus parts of the RSA key:

var exponent = Convert.ToBase64String(rsaParams.Modulus);
var modulus = Convert.ToBase64String(rsaParams.Exponent);

That is the same thing that your solution in the comments does (see source code of .ToXmlString) but it does require the detour over XML.

Upvotes: 1

Related Questions