如果可以的话,你应该避免使用RSACryptoServiceProvider。它仅适用于 Windows(它是 Windows 上不太好的 RSA 实现)。坚持使用RSA 基类,并通过RSA.Create() 创建新实例
临时密钥(创建)
.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。因此,如果您需要临时密钥,则需要在 .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);
}
临时密钥(导入)
尽管 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 框架
// 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);
使用命名/持久键(仅限 Windows)
我将包含一些关于 RSACryptoServiceProvider (WinXP+/CAPI) 和 RSACng (Win7+/CNG) 创建/打开命名密钥的示例,但这在 .NET 中不是很常见的场景;而且它当然不可移植(对其他操作系统的可移植性是 .NET Core 更引人注目的论点之一)。
引用事物。
对于 .NET Core 1.0 和 1.1,您可以从 System.Security.Cryptography.Algorithms 包访问 RSA 基类。在 .NET Core 2.0 中,它将包含在 netstandard 包参考中。
如果您需要与操作系统进行复杂的互操作,您可以参考 System.Security.Cryptography.Cng (Windows CNG)、System.Security.Cryptography.Csp (Windows CAPI/CryptoServiceProvider) 或 System.Security.Cryptography.OpenSsl (Linux OpenSSL、macOS OpenSSL)并访问启用互操作的类(RSACng、RSACryptoServiceProvider、RSAOpenSsl)。但是,真的,你不应该那样做。
RSA.Create() 返回什么?
- .NET Framework:RSACryptoServiceProvider,除非由 CryptoConfig 更改。
- .NET Core (Windows):通过 CNG 实现 RSA 的私有类,您不能将其转换为任何更具体的类型。
- .NET Core (Linux):通过 OpenSSL 实现 RSA 的私有类,您不能将其转换为任何更具体的类型。
- .NET Core (macOS):通过 OpenSSL 实现 RSA 的私有类,您不能将其转换为任何更具体的类型。 (这应该在 .NET Core 的下一版本中通过 SecureTransforms)