c# - 如何在 RSA 上设置 KeySize?

标签 c# .net encryption rsa

如何在 RSA 类上设置 key 大小?

RSA.Create() 没有 key 大小选项,在 RSA 创建后设置 KeySize 没有任何效果。

最佳答案

如果您使用的是 .NET Framework:

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

如果您使用的是 .NET Core:

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

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

如果您使用的是单声道

我不知道它匹配的是哪种行为。

如果你来自 future :

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
}

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

关于c# - 如何在 RSA 上设置 KeySize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585023/

相关文章:

c# - 如何知道在发布时构建的 .net 进程中挂起的方法

c# - 从 asp.net 前端添加 sql 记录的最佳实践?

php - 加密mysql数据并通过超链接,然后在下一页解密?

c# - string.Format 异常输入字符串的格式不正确

c# - 缺少 DLLImport,即使有 "using InteropServices"

.net - T4包含项目根目录中的文件路径

Android 设备是否经过硬件加密?以编程方式

java - 如何在数组中存储英文字符而不重复(尝试解决 Play Fair Cypher 加密)? ( java )

c# - 从 dll 文件加载 Prism 模块(在启动时)

c# - ElasticSearch NEST - 所有字段均为 NULL