如何设置RSA的KeySize

本文关键字:RSA KeySize 设置 何设置 | 更新日期: 2023-09-27 18:07:40

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

没有键大小选项与RSA.Create()和设置KeySizeRSA后,它已经创建没有任何影响。

如何设置RSA的KeySize

如果你正在使用。net Framework:

不存在与提供者无关的解决方案。您必须使用RSACryptoServiceProvider(int)构造函数或有意创建RSACng对象。

如果你正在使用。net Core:

RSA rsa = RSA.Create();
rsa.KeySize = someValue

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

如果你使用Mono:

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

如果你来自未来:

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
}

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

RSA只是RSA实现的一个抽象类。你应该使用RSACryptoServiceProvider

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(bitSize);

请注意,直到您尝试使用它时才会生成键,因此不要将构造函数本身放在后台工作器中等。