//密钥为pem格式 public class EncryptUtils { private const int _maxEncryptSize = 117; private const int _maxDecryptSize = 256; public static string RSAEncrypt(string publicKey, string bizContent) { //此处请根据需要设置集合capacity,也可不指定 var encryptedData = new List<byte>(45000); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.ImportFromPem(publicKey); int start = 0; var bytes = Encoding.UTF8.GetBytes(bizContent).AsSpan(); while (start < bytes.Length) { var buffer = bytes.Length - start <= _maxEncryptSize ? bytes.Slice(start).ToArray() : bytes.Slice(start, _maxEncryptSize).ToArray(); encryptedData.AddRange(rsa.Encrypt(buffer, false)); start += _maxEncryptSize; }; } return Convert.ToBase64String(encryptedData.ToArray()); } public static string RSADecrypt(string privateKey, string bizContent) { //此处请根据需要设置集合capacity,也可不指定 var encryptedData = new List<byte>(45000); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.ImportFromPem(privateKey); int start = 0; var bytes = Convert.FromBase64String(bizContent).AsSpan(); while (start < bytes.Length) { var buffer = bytes.Length - start <= _maxDecryptSize ? bytes.Slice(start).ToArray() : bytes.Slice(start, _maxDecryptSize).ToArray(); encryptedData.AddRange(rsa.Decrypt(buffer, false)); start += _maxDecryptSize; }; } return Encoding.UTF8.GetString(encryptedData.ToArray()); } }
标签:C#,bytes,RSA,rsa,start,int,RSACryptoServiceProvider,var,Net From: https://www.cnblogs.com/anech/p/17273260.html