C#實現(xiàn)對AES加密和解密的方法
/// <summary>
/// ASE加解密
/// </summary>
public class AESHelper
{
/// <summary>
/// 獲取密鑰
/// </summary>
private static string Key
{
get
{
return "abcdef1234567890"; ////必須是16位
}
}
//默認密鑰向量
private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <summary>
/// AES加密算法
/// </summary>
/// <param name="plainText">明文字符串</param>
/// <returns>將加密后的密文轉(zhuǎn)換為Base64編碼,以便顯示</returns>
public static string AESEncrypt(string plainText)
{
//分組加密算法
SymmetricAlgorithm des = Rijndael.Create();
byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字節(jié)數(shù)組
//設(shè)置密鑰及密鑰向量
des.Key = Encoding.UTF8.GetBytes(Key);
des.IV = _key1;
byte[] cipherBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();//得到加密后的字節(jié)數(shù)組
cs.Close();
ms.Close();
}
}
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="cipherText">密文字符串</param>
/// <returns>返回解密后的明文字符串</returns>
public static string AESDecrypt(string showText)
{
byte[] cipherText = Convert.FromBase64String(showText);
SymmetricAlgorithm des = Rijndael.Create();
des.Key = Encoding.UTF8.GetBytes(Key);
des.IV = _key1;
byte[] decryptBytes = new byte[cipherText.Length];
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, 0, decryptBytes.Length);
cs.Close();
ms.Close();
}
}
return Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); ///將字符串后尾的'\0'去掉
}
}
Key的值可以放在config文件中,也可放入數(shù)據(jù)庫中。
相關(guān)文章
C#探秘系列(四)——GetHashCode,ExpandoObject
這篇繼續(xù)分享下GetHashCode和ExpandoObject這兩個比較好玩的方法。2014-05-05
C#網(wǎng)絡(luò)編程基礎(chǔ)之進程和線程詳解
這篇文章主要介紹了C#網(wǎng)絡(luò)編程基礎(chǔ)之進程和線程詳解,本文對進程、線程、線程池知識做了淺顯易懂的講解,并配有代碼實例,需要的朋友可以參考下2014-08-08

