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

Art*_*yan 5 c# rsa digital-signature

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

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

privateKeyXmlText = rsa.ToXmlString(true);
publicKeyXmlText = rsa.ToXmlString(false);
Run Code Online (Sandbox Code Playgroud)

但我想要的是

privateKeyStr=="MIICITAjBgoqhkiG9w0BDAEDMBUEEKaTCK5mE2MsQANxDAfaJe8CAQoEggH47qb6bFO+a2Fj...";
publicKeyStr == "MIIBKjCB4wYHKoZIzj0CATCB1wIBATAsBgcqhkjOPQEBAiEA/////wAA...";
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Moh*_*bdo 0

(答案来自)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);
        };
Run Code Online (Sandbox Code Playgroud)