根据.NET Framework团队的指导(必须搜索"Cryptography Updates",附近似乎没有锚点 - 或者,只需查看代码示例).
public static byte[] EncryptDataOaepSha1(X509Certificate2 cert, byte[] data) { // GetRSAPublicKey returns an object with an independent lifetime, so it should be // handled via a using statement. using (RSA rsa = cert.GetRSAPublicKey()) { // OAEP allows for multiple hashing algorithms, what was formermly just "OAEP" is // now OAEP-SHA1. return rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1); } }
解密就是这样
public static byte[] DecryptDataOaepSha1(X509Certificate2 cert, byte[] data) { // GetRSAPrivateKey returns an object with an independent lifetime, so it should be // handled via a using statement. using (RSA rsa = cert.GetRSAPrivateKey()) { return rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA1); } }
注意事项:
在.NET Framework 4.6(和.NET Core 1.0/.NET Standard 1.3)中添加了RSA.Encrypt(byte [],RSAEncryptionPadding),因此请确保构建具有足够高目标版本的项目.
RSA加密主要用于加密对称密钥,而不是实际数据有效负载,因为它很昂贵并且具有大小限制(始终低于密钥大小(以字节为单位),不同的填充模式消耗不同的可用空间量).
虽然RSA基类讨论的是OaepSHA256(等),但是.NET Core中的所有提供程序都只支持Pkcs1和OaepSHA1.(OaepSHA256 +仅限RSACng)