【发布时间】: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);
}
谢谢。
【问题讨论】:
-
公钥是
Exponent和Modulus的组合,因此您必须对两者进行序列化。您希望您的输出采用什么格式? -
感谢@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