RSA如何设置KeySize?

Jam*_*ing 5 .net c# encryption rsa

如何设置RSA类上的密钥大小?

没有密钥大小选项,创建后RSA.Create()设置不会产生KeySize任何影响。RSA

bar*_*njs 4

如果您使用.NET Framework:

不存在提供商不知道的解决方案。您必须使用RSACryptoServiceProvider(int)构造函数或有意创建一个RSACng对象。

如果您使用.NET Core:

RSA rsa = RSA.Create();
rsa.KeySize = someValue
Run Code Online (Sandbox Code Playgroud)

是正确的方法,它适用于 RSA.Create() 的所有可能答案。

如果您使用的是单声道:

我不知道它符合哪种行为。

如果你来自未来:

https://github.com/dotnet/corefx/issues/8688正在跟踪未来添加RSA.Create(int)( 和RSA.Create(RSAParameters)) 以帮助解决此问题。

需要交叉编译的作用域方法:

(为您的构建正确定义 NETFX 并将其排列在 nuget 包中是留给读者的练习)

internal static RSA RsaCreate(int keySize)
{
#if NETFX
    // If your baseline is .NET 4.6.2 or higher prefer RSACng
    // or 4.6+ if you are never giving the object back to the framework
    // (4.6.2 improved the framework's handling of those objects)
    // On older versions RSACryptoServiceProvider is the only way to go.
    return new RSACng(keySize);
#else
    RSA rsa = RSA.Create();
    rsa.KeySize = keySize;

    if (rsa.KeySize != keySize)
        throw new Exception("Setting rsa.KeySize had no effect");

    return rsa;
#endif
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您来自未来,您可以直接以更高的优先级 #if 调用新的 Create 重载。