.Net(C#) RSA分段加密和解密

//密钥为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());
        }
    }

 

posted @ 2023-03-30 16:19  anech  阅读(305)  评论(0编辑  收藏  举报