using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace DSWeb.Areas.Dispatch.Helper
{
public class AesHelper
{
///
/// AES加密
///
/// 被加密的明文
/// 密钥
/// 向量
/// 密文
public static Byte[] AESEncrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
Byte[] Cryptograph = null; // 加密后的密文
Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流
using (MemoryStream Memory = new MemoryStream())
{
// 把内存流对象包装成加密流对象
using (CryptoStream Encryptor = new CryptoStream(Memory,
Aes.CreateEncryptor(bKey, bVector),
CryptoStreamMode.Write))
{
// 明文数据写入加密流
Encryptor.Write(Data, 0, Data.Length);
Encryptor.FlushFinalBlock();
Cryptograph = Memory.ToArray();
}
}
}
catch
{
Cryptograph = null;
}
return Cryptograph;
}
///
/// AES解密
///
/// 被解密的密文
/// 密钥
/// 向量
/// 明文
public static Byte[] AESDecrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
Byte[] original = null; // 解密后的明文
Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流,存储密文
using (MemoryStream Memory = new MemoryStream(Data))
{
// 把内存流对象包装成加密流对象
using (CryptoStream Decryptor = new CryptoStream(Memory,
Aes.CreateDecryptor(bKey, bVector),
CryptoStreamMode.Read))
{
// 明文存储区
using (MemoryStream originalMemory = new MemoryStream())
{
Byte[] Buffer = new Byte[1024];
Int32 readBytes = 0;
while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}
original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}
return original;
}
public static byte[] AESDecrypt(byte[] Data, byte[] Key, byte[] vector)
{
byte[] original = null; // 解密后的明文
Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流,存储密文
using (MemoryStream Memory = new MemoryStream(Data))
{
// 把内存流对象包装成加密流对象
using (CryptoStream Decryptor = new CryptoStream(Memory,
Aes.CreateDecryptor(Key, vector),
CryptoStreamMode.Read))
{
// 明文存储区
using (MemoryStream originalMemory = new MemoryStream())
{
byte[] Buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}
original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}
return original;
}
}
}