0

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.

snowflakes74
  • 1,307
  • 1
  • 20
  • 43
  • The public key is a combination of `Exponent` and `Modulus`, so you'll have to serialize both. What format do you expect your output to be in? – a-ctor Jun 18 '20 at 10:42
  • Thanks @a-ctor in plain text(string). – snowflakes74 Jun 18 '20 at 10:45
  • Also take a look at [this](https://stackoverflow.com/a/5845191) answer since you are currently storing the generated key on the file system. – a-ctor Jun 18 '20 at 10:46
  • Thank you I ended up using XML to read the value .. not sure it is proper way to do or not. string publicKeyXML = RSA.ToXmlString(false); XDocument doc = XDocument.Parse(publicKeyXML); foreach (XElement element in doc.XPathSelectElement("//RSAKeyValue").Descendants()) { string value = element.Value; } – snowflakes74 Jun 18 '20 at 10:55

1 Answers1

1

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.

a-ctor
  • 3,568
  • 27
  • 41