登录
原创

C#实现AES-ECB加解密

发布于 2022-07-11 阅读 284
  • C#
原创
using System;
using System.Text;
using System.Security.Cryptography;

namespace Common_API_Test.Test_Demo
{
    class AES_ecb_Encrypt
    {
        static void Main(string[] args)
        {
            string key = "1234567812345678";// 密钥
            string encryptStr = "12345678"; // 明文
            string enStr = AESEncrypt(encryptStr, key);
            Console.Write(enStr);
            Console.ReadLine();
        }

        /// <summary>
        /// AES-ecb加密
        /// </summary>
        /// <param name="encryptStr">明文</param>
        /// <param name="Key">密钥</param>
        /// <returns></returns>
        public static string AESEncrypt(string encryptStr, string Key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// AES-ecb解密
        /// </summary>
        /// <param name="encryptStr">密文</param>
        /// <param name="Key">密钥</param>
        /// <returns></returns>
        public static string AESDEncrypt(string encryptStr, string Key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            byte[] toEncryptArray = Convert.FromBase64String(encryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}

评论区

king
4粉丝

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0

举报