【问题标题】:Load RSA public key from RSAParams从 RSAParams 加载 RSA 公钥
【发布时间】:2020-06-18 10:23:48
【问题描述】:

我需要在 C# 中生成 RSA 密钥对,然后将公钥存储在数据库中,以便以后以 JWK 格式使用。

但我无法从 RSAParams.Modulus 获取字符串。

我尝试了 UTF8、UTF32 和通用编码,但仍然没有显示。

这是来自 MSDN 网站的以下代码。

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);
        }

谢谢。

【问题讨论】:

  • 公钥是ExponentModulus 的组合,因此您必须对两者进行序列化。您希望您的输出采用什么格式?
  • 感谢@a-ctor 纯文本(字符串)。
  • 还可以查看this 答案,因为您当前正在将生成的密钥存储在文件系统上。
  • 谢谢我最终使用 XML 来读取值.. 不确定这样做是否正确。字符串 publicKeyXML = RSA.ToXmlString(false); XDocument 文档 = XDocument.Parse(publicKeyXML); foreach (doc.XPathSelectElement("//RSAKeyValue").Descendants()中的XElement元素) { string value = element.Value; }

标签: c# cryptography rsa


【解决方案1】:

我假设您希望输出为 base64。然后您可以使用Convert.ToBase64String 转换RSA 密钥的ExponentModulus 部分:

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

这与您在 cmets 中的解决方案所做的相同(请参阅 source code of .ToXmlString),但它确实需要绕过 XML。

【讨论】:

    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2013-05-05
    • 2020-07-13
    • 2017-10-07
    相关资源
    最近更新 更多