我想在C#中生成RSA密钥对。我能够获得xml字符串的键,但我需要base64表示它们。这是我的xml代码
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
privateKeyXmlText = rsa.ToXmlString(true);
publicKeyXmlText = rsa.ToXmlString(false);
但我想要的是像
privateKeyStr=="MIICITAjBgoqhkiG9w0BDAEDMBUEEKaTCK5mE2MsQANxDAfaJe8CAQoEggH47qb6bFO+a2Fj...";
publicKeyStr == "MIIBKjCB4wYHKoZIzj0CATCB1wIBATAsBgcqhkjOPQEBAiEA/////wAA...";
任何想法?
答案 0 :(得分:0)
(回答)C# Export Private/Public RSA key from RSACryptoServiceProvider to PEM string
public static Func<string, string> ToBase64PemFromKeyXMLString= (xmlPrivateKey) =>
{
if (string.IsNullOrEmpty(xmlPrivateKey))
throw new ArgumentNullException("RSA key must contains value!");
var keyContent = new PemReader(new StringReader(xmlPrivateKey));
if (keyContent == null)
throw new ArgumentNullException("private key is not valid!");
var ciphrPrivateKey = (AsymmetricCipherKeyPair)keyContent.ReadObject();
var asymmetricKey = new AsymmetricKeyEntry(ciphrPrivateKey.Private);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricKey.Key);
var serializedPrivateKey = privateKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPrivateKey);
};