【问题标题】:Convert from RSACryptoServiceProvider to RSACng从 RSACryptoServiceProvider 转换为 RSACng
【发布时间】:2018-11-14 07:23:25
【问题描述】:

我目前正在使用 RSACryptoServiceProvider,我想更改为 RSACng。我正在使用它来签署数据。更改的原因是我使用的是 Pkcs1 填充,并且我知道 Pss 填充是首选。我们正在进行安全审核。

我的问题是如何实例化 RSACng 以便它每次都使用相同的私钥/公钥?

我正在使用 RSACryptoServiceProvider:

CspParameters cp = new CspParameters();  
cp.KeyContainerName = "ContainerName";  
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cp);

传入容器名称意味着它使用保留在机器上容器存储中的密钥。

使用 RSACng,我尝试了这个,但出现异常:“不支持请求的操作”

RSACng RSA = new RSACng(CngKey.Create(CngAlgorithm.Sha256, ContainerName));

我只需要能够传递存储密钥名称,以便它每次都使用相同的密钥,而不是生成一个新密钥。

【问题讨论】:

  • CngAlgorithm的值应该是CngAlgorithm.Rsa吗?
  • 你不需要用CNGKey.Open代替Create吗?

标签: c# .net cryptography public-key-encryption


【解决方案1】:

如果您想使用 CNG 创建命名/持久 RSA 密钥:

private static RSA CreatePersistedRSAKey(string name, int keySizeInBits)
{
    CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
    {
        // This is what an ephemeral key would have had
        // (allows ExportParameters(true) to succeed). Adjust as desired.
        //
        // The default is not exportable (only applies to the private key)
        ExportPolicy =
            CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport,
    };

    creationParameters.Parameters.Add(
        new CngProperty(
            "Length",
            BitConverter.GetBytes(keySizeInBits),
            CngPropertyOptions.Persist));

    // RSACng will extract the data it needs from this key object,
    // but doesn't take ownership
    using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, name, creationParameters))
    {
        return new RSACng(key);
    }
}

这会跳过您将在调用 CngKey.Open 时尝试/捕获的部分,或者可能想要删除密钥(使用 CngKey.Open 打开它,然后在 CngKey 实例上调用 Delete)。

CngAlgorithm.Rsa 已添加到 net46 中。如果您使用的是旧版本,则等效版本为 new CngAlgorithm("RSA")

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多