我正在尝试使用 RSA 加密和解密一些数据。我查过 RSA
类,但我只看到抽象类 https://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa(v=vs.110).aspx
我读过 DNX5 中的 RSA 类与 .net 4.6.1 中的不同,这与我所看到的不同吗?如果是这样,我在哪里可以找到使用该文档的文档?似乎 RSACryptoServiceProvider
在 .net 核心中不起作用,我只能访问 RSA
抽象类。
最佳答案
您应该避免使用 RSACryptoServiceProvider
如果你可以的话。它仅适用于 Windows(它是 Windows 上不太好的 RSA 实现)。坚持RSA
基类,并通过 RSA.Create()
创建新实例
临时 key (创建)
.NET 核心
using (RSA rsa = RSA.Create())
{
rsa.KeySize = desiredKeySizeInBits;
// when the key next gets used it will be created at that keysize.
DoStuffWithThePrivateKey(rsa);
}
.NET 框架
不幸的是,.NET Framework 上 RSA.Create() 的默认值是 RSACryptoServiceProvider,它不遵守 set_KeySize。因此,如果您需要临时 key ,则需要在 .NET Framework 与 .NET Core 上使用不同的代码:
using (RSA rsa = new RSACng())
{
rsa.KeySize = desiredKeySizeInBits;
DoStuffWithThePrivateKey(rsa);
}
或者,如果您需要支持早于 4.6(RSACng 不存在)/4.6.2(大多数 .NET Framework 使用 RSACng 对象而不是 RSACryptoServiceProvider 对象)的版本,您可以继续使用旧的实现:
using (RSA rsa = new RSACryptoServiceProvider(desiredKeySizeInBits))
{
// Since before net46 the Encrypt/Decrypt, SignData/VerifyData, SignHash/VerifyHash
// methods were not defined at the RSA base class, you might need to keep this strongly
// typed as RSACryptoServiceProvider.
DoStuffWithThePrivateKey(rsa);
}
临时 key (导入)
尽管 RSACng 通常比 RSACryptoServiceProvider 更容易使用,但 RSACryptoServiceProvider 在这种情况下应该可以正常工作,因此 RSA.Create() 在所有平台上都很好:
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(rsaParameters);
DoStuffWithWhateverKindOfKeyYouImported(rsa);
}
从证书:
.NET Core 1.0+、.NET Framework 4.6+
using (RSA rsa = cert.GetRSAPublicKey())
{
DoStuffWithThePublicKey(rsa);
}
或者
using (RSA rsa = cert.GetRSAPrivateKey())
{
DoStuffWithThePrivateKey(rsa);
}
.NET 框架 < 4.6
// Do NOT put this in a using block, since the object is shared by all callers:
RSA rsaPrivate = (RSA)cert.PrivateKey;
DoStuffWithThePrivateKey(rsaPrivate);
// Do NOT put this in a using block, since the object is shared by all callers:
RSA rsaPublicOnly = (RSA)cert.PublicKey.Key;
DoStuffWithThePublicKey(rsaPublic);
使用命名/持久 key (仅限 Windows)
我将包含一些关于 RSACryptoServiceProvider (WinXP+/CAPI) 和 RSACng (Win7+/CNG) 创建/打开命名 key 的示例,但这在 .NET 中不是很常见的场景;而且它当然不可移植(对其他操作系统的可移植性是 .NET Core 更引人注目的论点之一)。
引用事物。
对于 .NET Core 1.0 和 1.1,您可以从
System.Security.Cryptography.Algorithms
访问 RSA 基类。包裹。在 .NET Core 2.0 中,它将包含在 netstandard
中。包引用。如果您需要与操作系统进行复杂的互操作,您可以引用
System.Security.Cryptography.Cng
(Windows CN), System.Security.Cryptography.Csp
(Windows CAPI/CryptoServiceProvider),或System.Security.Cryptography.OpenSsl
(Linux OpenSSL、macOS OpenSSL)并访问启用互操作的类(RSACng、RSACryptoServiceProvider、RSAOpenSsl)。但是,真的,你不应该那样做。RSA.Create() 返回什么?
关于.net - 在 .NET 核心中实现 RSA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41986995/