|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- using System;
- using System.Security.Cryptography;
- using System.Text;
-
- namespace Common
- {
- public class AesHelper
- {
- public static string QrcodeLoginKey = "zyyxhlywkdatakey";
-
- /// <summary>
- /// AES 加密
- /// </summary>
- /// <param name="data"></param>
- /// <param name="key"></param>
- /// <returns>Encrypted 16 hex string</returns>
- public static string AesEncrypt(string data, string key = "")
- {
- if (string.IsNullOrWhiteSpace(key))
- {
- key = QrcodeLoginKey.PadRight(16, '0');
- }
- // 256-AES key
- byte[] keyArray = Encoding.UTF8.GetBytes(key);
- byte[] toEncryptArray = Encoding.UTF8.GetBytes(data);
- RijndaelManaged rDel = new RijndaelManaged { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
- ICryptoTransform cTransform = rDel.CreateEncryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
- return BytesToHexString(resultArray);
- }
-
- /// <summary>
- /// AES 解密
- /// </summary>
- /// <param name="hexString">Encrypted 16 hex string</param>
- /// <param name="key"></param>
- /// <returns>Decrypted string</returns>
- public static string AesDecrypt(string hexString, string key = "")
- {
- if (string.IsNullOrWhiteSpace(key))
- {
- key = QrcodeLoginKey.PadRight(16, '0');
- }
- // 256-AES key
- byte[] keyArray = Encoding.UTF8.GetBytes(key);
- byte[] toEncryptArray = HexStringToBytes(hexString);
- RijndaelManaged rDel = new RijndaelManaged { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
- ICryptoTransform cTransform = rDel.CreateDecryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
- return Encoding.UTF8.GetString(resultArray);
- }
-
- /// <summary>
- /// Byte array to convert 16 hex string
- /// </summary>
- /// <param name="bytes">byte array</param>
- /// <returns>16 hex string</returns>
- public static string BytesToHexString(byte[] bytes)
- {
- StringBuilder returnStr = new StringBuilder();
- if (bytes != null)
- {
- foreach (var t in bytes)
- {
- returnStr.Append(t.ToString("X2"));
- }
- }
- return returnStr.ToString();
- }
-
- /// <summary>
- /// 16 hex string converted to byte array
- /// </summary>
- /// <param name="hexString">16 hex string</param>
- /// <returns>byte array</returns>
- public static byte[] HexStringToBytes(string hexString)
- {
- if (hexString == null || hexString.Equals(""))
- {
- return null;
- }
- int length = hexString.Length / 2;
- if (hexString.Length % 2 != 0)
- {
- return null;
- }
- byte[] d = new byte[length];
- for (int i = 0; i < length; i++)
- {
- d[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- }
- return d;
- }
- }
- }
|