C#从字符串形式的公共证书密钥创建RSACryptoServiceProvider

本文关键字:证书 密钥 创建 RSACryptoServiceProvider 字符串 | 更新日期: 2023-09-27 17:59:53

是否可以从字符串形式的公共证书密钥生成RSACryptoServiceProvider。

我试着:

RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
var publicKey = PublicKey.GetPublicKey();
provider.FromXmlString("<RSAKeyValue><Modulus>" + publicKey + "</Modulus></RSAKeyValue>");

但我得到的异常是无效的base64

  at Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.Security.Cryptography.CryptographicException: Couldn't decode XML ---> System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

我能做什么?

C#从字符串形式的公共证书密钥创建RSACryptoServiceProvider

两件事。

第一:你的结束标签是向后的。。。

</RSAKeyValue></Modulus>

应读取

</Modulus></RSAKeyValue>

第二:您缺少指数参数。

请参阅此工作代码:

RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
//var publicKey = PublicKey.GetPublicKey();
provider.FromXmlString(
    "<RSAKeyValue>"+
        "<Modulus>CmZ5HcaYgWjeerd0Gbt/sMABxicQJwB1FClC4ZqNjFHQU7PjeCod5dxa9OvplGgXARSh3+Z83Jqa9V1lViC7qw==</Modulus>"+
        "<Exponent>AQAB</Exponent>"+
    "</RSAKeyValue>");

.NET Core 3.0及更高版本中,您可以执行以下操作:

//create a RSACryptoServiceProvinder, sample use
using (var rsa = new RSACryptoServiceProvider())
{
    rsa.FromXmlString(ConvertPublicKeyFromBase64(base64publicKey));
    //rest of the code
    ...
}
public string ConvertPublicKeyFromBase64(string publicKeyBase64)
{
    // Decode the Base64 public key into a byte array
    byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64);
    // Create an RSA object to import the public key
    using (var rsa = RSA.Create())
    {
        // Import the public key bytes
        rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
        // Export the public key as an XML string
        string publicKeyXml = rsa.ToXmlString(false);
        return publicKeyXml;
    }
}

对于.NETFramework,没有ImportSubjectPublicKeyInfo()方法,因此您可以使用为其提供ImportSubjectPublic KeyInformation()的RSAExtensions类,然后使用上面的代码。

RSAE扩展的GitHub代码
RSAE.NET Framework文章的扩展