从RSACryptoServiceProvider转换为RSACng [英] Convert from RSACryptoServiceProvider to RSACng

查看:64
本文介绍了从RSACryptoServiceProvider转换为RSACng的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently using RSACryptoServiceProvider and I want to change to RSACng. I am using it to sign data. The reason for the change is that I am using Pkcs1 padding and I understand that Pss padding is preferred. We are undergoing security audits.

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

My question is how do I instantiate RSACng so that it uses the same private / public key each time?

我正在使用RSACryptoServiceProvider:

With RSACryptoServiceProvider I am doing:

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

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

passing in the container name means it uses the key that persists in the in the container store on the machine.

我使用RSACng进行了尝试,但出现了异常:不支持所请求的操作"

With RSACng, I tried this, but I get an exception: "The requested operation is not supported"

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

我只需要能够传递商店密钥名称,以便它每次都使用相同的密钥而不是生成新密钥.

I just need to be able to pass the store key name so it uses the same key each time instead of generating a new key.

推荐答案

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

If you want to create a named/persisted RSA key with CNG:

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)的部分.

This skips the parts where you would do a try/catch around a call to CngKey.Open, or might want to delete the key (open it with CngKey.Open, and call Delete on the CngKey instance).

( CngAlgorithm.Rsa .如果您使用的是旧版本,则等效项为 new CngAlgorithm("RSA"))

(CngAlgorithm.Rsa was added in net46. If you're on an older version then an equivalent would be new CngAlgorithm("RSA"))

这篇关于从RSACryptoServiceProvider转换为RSACng的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆