TG.WXCRM.V4/Common/AESHelper.cs

89 lines
3.0 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Security.Cryptography;
using System.Text;
namespace WX.CRM.Common
{
public class AESHelper
{
public static string Decrypt(string text, string key)
{
try
{
byte[] encryptedData = strToHexByte(text);
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Key = Encoding.UTF8.GetBytes(key);
rijndaelCipher.Mode = CipherMode.ECB;
rijndaelCipher.Padding = PaddingMode.None;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
string result = Encoding.Default.GetString(plainText);
return result;
}
catch (Exception ex)
{
return null;
}
}
public static string Encrypt(string text, string key)
{
try
{
byte[] encryptedData = Encoding.UTF8.GetBytes(text);
encryptedData = padding(encryptedData);
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Key = Encoding.UTF8.GetBytes(key);
rijndaelCipher.Mode = CipherMode.ECB;
rijndaelCipher.Padding = PaddingMode.None;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return byteToHexStr(plainText);
}
catch (Exception ex)
{
return null;
}
}
private static byte[] strToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
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;
}
private static byte[] padding(byte[] src)
{
if (src.Length % 16 == 0)
{
return src;
}
byte[] buffer = new byte[src.Length / 16 * 16 + 16];
System.Array.Copy(src, 0, buffer, 0, src.Length);
return buffer;
}
private static string byteToHexStr(byte[] bytes)
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString.ToLower();
}
}
}