从 RSA 密钥对获取私钥/公钥 base64 表示形式

本文关键字:base64 表示 公钥 RSA 密钥对 获取 私钥 | 更新日期: 2023-09-27 18:37:04

我想在C#中生成RSA密钥对。我能够获得键的 xml 字符串,但我需要它们的 base64 表示形式。这是我的 xml 代码

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
privateKeyXmlText = rsa.ToXmlString(true);
publicKeyXmlText = rsa.ToXmlString(false);

但我想要的是类似的东西

privateKeyStr=="MIICITAjBgoqhkiG9w0BDAEDMBUEEKaTCK5mE2MsQANxDAfaJe8CAQoEggH47qb6bFO+a2Fj...";
publicKeyStr == "MIIBKjCB4wYHKoZIzj0CATCB1wIBATAsBgcqhkjOPQEBAiEA/////wAA...";

有什么想法吗?

从 RSA 密钥对获取私钥/公钥 base64 表示形式

(答案来自) C# 将私有/公共 RSA 密钥从 RSACryptoServiceProvider 导出到 PEM 字符串

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