AES簡介
AES(The Advanced Encryption Standard)是美國國家標準與技術(shù)研究所用于加密電子數(shù)據(jù)的規(guī)范。它被預期能成為人們公認的加密包括金融、電信和政府數(shù)字信息的方法。
AES 是一個新的可以用于保護電子數(shù)據(jù)的加密算法。明確地說,AES 是一個迭代的、對稱密鑰分組的密碼,它可以使用128、192 和 256 位密鑰,并且用 128 位(16字節(jié))分組加密和解密數(shù)據(jù)。與公共密鑰密碼使用密鑰對不同,對稱密鑰密碼使用相同的密鑰加密和解密數(shù)據(jù)。通過分組密碼返回的加密數(shù)據(jù) 的位數(shù)與輸入數(shù)據(jù)相同。以下是我經(jīng)過整理的代碼,希望對大家有所幫助:
//默認密鑰向量
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ù)組
//設置密鑰及密鑰向量
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'去掉
}
}
新聞熱點
疑難解答