107 lines
3.2 KiB
C#
107 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MyCode.Project.Infrastructure.Common
|
|
{
|
|
public class AESHelper
|
|
{
|
|
private static byte[] AESCreateKey(byte[] key, int keyLength)
|
|
{
|
|
byte[] realkey = new byte[keyLength];
|
|
|
|
for (int i = 0; i < key.Length; i++)
|
|
{
|
|
realkey[i % keyLength] ^= key[i];
|
|
}
|
|
|
|
return realkey;
|
|
}
|
|
|
|
|
|
#region AESEncrypt(AES加密算法)
|
|
/// <summary>
|
|
/// AES加密算法
|
|
/// </summary>
|
|
/// <param name="plainText">明文字符串</param>
|
|
/// <param name="strKey">密钥</param>
|
|
/// <returns>返回加密后的密文字节数组</returns>
|
|
public static string AESEncrypt(string plainText, string strKey)
|
|
{
|
|
MemoryStream mStream = new MemoryStream();
|
|
AesManaged aes = new AesManaged();
|
|
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
|
|
|
|
Byte[] bKey = Encoding.ASCII.GetBytes(strKey);
|
|
|
|
aes.Mode = CipherMode.ECB;
|
|
aes.Padding = PaddingMode.PKCS7;
|
|
aes.KeySize = 128;
|
|
aes.Key = AESCreateKey(bKey, aes.KeySize / 8);
|
|
|
|
CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
|
|
|
|
try
|
|
{
|
|
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
|
|
cryptoStream.FlushFinalBlock();
|
|
return Convert.ToBase64String(mStream.ToArray());
|
|
}
|
|
finally
|
|
{
|
|
cryptoStream.Close();
|
|
mStream.Close();
|
|
aes.Clear();
|
|
}
|
|
|
|
}
|
|
#endregion
|
|
|
|
#region AESDecrypt(AES解密)
|
|
/// <summary>
|
|
/// AES解密
|
|
/// </summary>
|
|
/// <param name="strCipherText">密文字符串</param>
|
|
/// <param name="strKey">密钥</param>
|
|
/// <returns>返回解密后的字符串</returns>
|
|
public static string AESDecrypt(string strCipherText, string strKey)
|
|
{
|
|
Byte[] encryptedBytes = Convert.FromBase64String(strCipherText);
|
|
|
|
Byte[] bKey = Encoding.ASCII.GetBytes(strKey);
|
|
|
|
MemoryStream mStream = new MemoryStream(encryptedBytes);
|
|
|
|
AesManaged aes = new AesManaged();
|
|
aes.Mode = CipherMode.ECB;
|
|
aes.Padding = PaddingMode.PKCS7;
|
|
aes.KeySize = 128;
|
|
aes.Key = AESCreateKey(bKey, aes.KeySize / 8);
|
|
|
|
CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
|
|
try
|
|
{
|
|
byte[] tmp = new byte[encryptedBytes.Length + 32];
|
|
int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
|
|
byte[] ret = new byte[len];
|
|
Array.Copy(tmp, 0, ret, 0, len);
|
|
return Encoding.UTF8.GetString(ret);
|
|
}
|
|
finally
|
|
{
|
|
cryptoStream.Close();
|
|
mStream.Close();
|
|
aes.Clear();
|
|
}
|
|
|
|
}
|
|
#endregion
|
|
|
|
}
|
|
|
|
}
|