在 C# 中加载 ASN.1/DER 编码的 RSA 密钥对

Load ASN.1/DER encoded RSA keypair in C#

我有用 Crypto++ 创建的 DER 编码 RSA 密钥对,以及密码。它们是 Base64Encoded 字符串。我首先将数据从 Base64 解码为字节数组,但我不确定如何将它们加载到 RSACryptoServiceProvider.

static void Main()
{
    string pbkeystr = "mypublickey";
    string pvkeystr = "myprivatekey";
    string cipherstr = "mycipher";

    byte[] pbkey = Convert.FromBase64String(pbkeystr);
    byte[] pvkey = Convert.FromBase64String(pvkeystr);
    byte[] cipher = Convert.FromBase64String(cipherstr);

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    //Set keys here..

    //Decrypt the cipher using private key
    rsa.Decrypt(pvkey, false);
}

没有设置按键的功能。我唯一发现的是 ImportParameters 方法,它采用 RSAParameters class,其中包含 pqn、模数、指数等.我没有权限访问这些。

有什么方法可以将键作为字符串加载吗?如何将密钥加载到 RSACryptoServiceProvider?

Is there any way I can load the keys as string? How can I load the key into RSACryptoServiceProvider?

根据你的另一个 Crypto++ 问题 ,你似乎只有 public 和私钥,因为你使用了 DEREncodeBERDecode。也就是说,您拥有 RSA 参数,而不是主题 public 密钥信息和私钥信息。您的密钥缺少 OID 标识符和版本号。这样就好了。

从代码项目的 Cryptographic Interoperability: Keys 开始,您将需要一个 C# class 来在 Base64 解码后解析 ASN.1/DER。 CodeProject 文章提供了一个名为 AsnKeyParser 的 C# class 来读取 ASN.1/DER 和 returns 一个 RSAParameters 来加载到 CSP 中。

AsnKeyParser class 的代码大约有 800 行,还有其他五个支持文件来实现这一切,因此将其放在此处不太合适。你应该自己下载。感兴趣的文件名为 CSInteropKeys.zip

一旦你 wire-in AsnKeyParser class,RSA Public 密钥就很简单了。私钥会类似,代码在CodeProject网站上给出。

// Your ASN.1/DER parser class
AsnKeyParser keyParser = new AsnKeyParser("rsa-public.der");
RSAParameters publicKey = keyParser.ParseRSAPublicKey();

// .Net class
CspParameters csp = new CspParameters;
csp.KeyContainerName = "RSA Test (OK to Delete)";    
csp.ProviderType = PROV_RSA_FULL;    // 1
csp.KeyNumber = AT_KEYEXCHANGE;      // 1

// .Net class
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(publicKey);

链接到另一个站点上的文件是不受欢迎的,但我不知道如何提供其他信息。涉及的源代码太多,无法放在答案中。


为了完整性,.Net 不会 使互操作变得容易。他们不接受 ASN.1/DER 或 PEM。相反,.Net 接受一些 XML 键的表示。我相信你可以在 RFC 3275, XML-Signature Syntax and Processing. Microsoft does not state that for you 中找到它。我在写代码项目文章时把它拼凑起来了。

也许我们应该在 Crypto++ 中添加一个 class 以反省 XML 除了 ASN.1/DER 和 PEM。