首页 > 代码库 > Aes加密解密

Aes加密解密

 

      加密时:先对string进行utf8解析成数组-->对数组进行加密-->对加密结果用base64解析成string。

              那么揭秘时,对字符串的解析方式是必须要“倒”过来的,就成这样子了:

       解密时:先对string进行base64解析成数组-->对数组进行解密-->对解密结果用utf8解析成string

 

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

namespace ConsoleApp14
{
    public delegate void GreetDelegate(string name);
    class Program
    {
        private static void Main(string[] args)
        {
            string s = EncodeStr("Good");
            Console.WriteLine(s);
            string ss = "hFsfyUinz3jzjulh0y7HWw==";
            Console.WriteLine(DecodeStr(ss));
            Console.ReadKey();

        }
        //加密和解密的密钥必须相等。
        public static string EncodeStr(string ss)
        {
            string s = string.Empty;
            //设置密钥
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            //加密时用utf8,当解密时要反过来
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ss);
            //建立算法实例
            RijndaelManaged r = new RijndaelManaged();
            //设置属性
            r.Key = keyArray;
            r.Mode = CipherMode.ECB;
            r.Padding = PaddingMode.PKCS7;
            //制定加密或者解密方式
            ICryptoTransform ic = r.CreateEncryptor();
         byte[] bb= ic.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            //以base64进行加密输出,当解密时要先用base64进行解析
            s = Convert.ToBase64String(bb);
            return s;
        }
        public static string DecodeStr(string ss)
        {
            string s = string.Empty;
            //设置密钥
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] toEncryptArray = Convert.FromBase64String(ss);

            //建立算法实例
            RijndaelManaged r = new RijndaelManaged();
            //设置属性
            r.Key = keyArray;
            r.Mode = CipherMode.ECB;
            r.Padding = PaddingMode.PKCS7;
            //制定加密或者解密方式
            ICryptoTransform ic = r.CreateDecryptor();
            byte[] bb = ic.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            s = UTF8Encoding.UTF8.GetString(bb);
            return s;
        }

    }
}

 

Aes加密解密