1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- namespace TEAMModelOS.Controllers.Third.Helpers
- {
- public class AESHelper
- {
- /// <summary>
- /// 有密码的加密
- /// </summary>
- /// <param name="toEncrypt">加密字符</param>
- /// <param name="key">加密的密码</param>
- /// <returns></returns>
- public static string AESEncrypt(string toEncrypt, string key)
- {
- byte[] keyArray = hexStringTobyte(key);
- byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
- RijndaelManaged rDel = new RijndaelManaged();
- rDel.KeySize = 128;
- rDel.BlockSize = 128;
- rDel.Key = keyArray;
- rDel.Mode = CipherMode.ECB;
- rDel.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = rDel.CreateEncryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
- return byteToHexString(resultArray);
- }
- /// <summary>
- /// 解密
- /// </summary>
- /// <param name="toDecrypt">解密字符</param>
- /// <param name="key">加密的密码</param>
- /// <returns></returns>
- public static string AESDecrypt(string toDecrypt, string key)
- {
- byte[] keyArray = hexStringTobyte(key);
- byte[] dest = hexStringTobyte(toDecrypt);
- RijndaelManaged rDel = new RijndaelManaged();
- rDel.KeySize = 128;
- rDel.BlockSize = 128;
- rDel.Key = keyArray;
- rDel.Mode = CipherMode.ECB;
- rDel.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = rDel.CreateDecryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(dest, 0, dest.Length);
- return UTF8Encoding.UTF8.GetString(resultArray);
- }
- private static byte[] hexStringTobyte(String s)
- {
- if (string.IsNullOrEmpty(s)) return null;
- s = s.ToLower();
- int byteArrayLength = s.Length / 2;
- byte[] b = new byte[byteArrayLength];
- for (int i = 0; i < byteArrayLength; i++)
- {
- byte b0 = Convert.ToByte(s.Substring(i * 2, 2), 16);
- b[i] = b0;
- }
- return b;
- }
- public static string byteToHexString(byte[] t)
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < t.Length; i++)
- {
- sb.Append(t[i].ToString("x").PadLeft(2, '0'));
- }
- return sb.ToString().ToUpper();
- }
- }
- }
|