c# AESUtils

7 篇文章 0 订阅

完整代码

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Script.Common.Utils
{
    public class AESUtils
    {
        public static string Encrypt(string content, string key)
        {
            byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);

            RijndaelManaged rm = new RijndaelManaged();

            rm.Key = keyBytes;

            rm.Mode = CipherMode.ECB;

            rm.Padding = PaddingMode.PKCS7;

            ICryptoTransform ict = rm.CreateEncryptor();

            byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content);

            byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);

            return ConvertByteToHexString(resultBytes);
        }


        public static string Decrypt(string content, string key)
        {
            byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);
            RijndaelManaged rm = new RijndaelManaged();
            rm.Key = keyBytes;
            rm.Mode = CipherMode.ECB;
            rm.Padding = PaddingMode.PKCS7;
            ICryptoTransform ict = rm.CreateDecryptor();
            byte[] contentBytes = ConvertHexStringToBytes(content);
            byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
            return UTF8Encoding.UTF8.GetString(resultBytes);
        }

        public static string ConvertByteToHexString(byte[] bytes)
        {
            StringBuilder ret = new StringBuilder();
            foreach (byte b in bytes)
            {
                //{0:X2} 大写
                ret.AppendFormat("{0:x2}", b);
            }

            var hex = ret.ToString();
            return hex;
        }

        public static byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return returnBytes;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值