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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.