在很多项目中,对于安全性的要求是很高的,这就涉及到了各种加密,解密算法,常见的算法有MD5加密、DES加解密、字符串加解密、AES加解密等,下面来一起看一下AES加解密算法。
AES(Advanced Encryption Standard),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。AES加密算法速度快,适合大量数据,相对于3DES,又快又安全。
//默认密钥向量
private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
//秘钥可以自定义,长度为16位字符
static string strKey = "dongbinhuiasxiny";//密钥,128位
///
/// AES加密算法
///
/// 明文字符串
/// 密钥
/// 返回加密后的密文字节数组
public static byte[] AESEncrypt(string plainText, string strKey)
{
//分组加密算法
SymmetricAlgorithm des = Rijndael.Create();
byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
//设置密钥及密钥向量
des.Key = Encoding.UTF8.GetBytes(strKey);
des.IV = _key1;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
cs.Close();
ms.Close();
return cipherBytes;
}
///
/// AES解密
///
/// 密文字节数组
/// 密钥
/// 返回解密后的字符串
public static byte[] AESDecrypt(byte[] cipherText, string strKey)
{
SymmetricAlgorithm des = Rijndael.Create();
des.Key = Encoding.UTF8.GetBytes(strKey);
des.IV = _key1;
byte[] decryptBytes = new byte[cipherText.Length];
MemoryStream ms = new MemoryStream(cipherText);
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
cs.Read(decryptBytes, 0, decryptBytes.Length);
cs.Close();
ms.Close();
return decryptBytes;
}
//AES加密
string keys = "dongbinhuiasxiny";//密钥,128位
string s = "dfererfereerefregrgrgtrytrgrty5hrthyhthtyhttyhjutyjhtyjtyhvfrgtgdfgrtgrbrtyrt12323243455creffefdeddewdwdfwefwevdfvdcvdfgdgrtgdtfgdgref"; //被加密的明文
byte[] encryptBytes = Secret.AESEncrypt(s, keys);
s = Convert.ToBase64String(encryptBytes);
//AES解密
byte[] decryptBytes = Secret.AESDecrypt(encryptBytes, keys);
//将解密后的结果转换为字符串,也可以将该步骤封装在解密算法中
string result = Encoding.UTF8.GetString(decryptBytes);
AES加解密算法已经成为对称密钥加密中最流行的算法之一,希望对大家有所帮助,感谢您的阅读。