.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());
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章