在这个数字科技时代,数据的加密是非常重要的。试想一下,如果我们的数据都没有进行加密,那么,我们日常生活中的电话,短信,聊天内容就可能轻易的被别人所窥视。那我们的生活就乱套了。所以,今天给需要进行数据加密的朋友推荐一个加密方式:AES加密。AES是作为取代DES的高级加密标准,已经被广泛使用,要破解AES加密的难度是非常大的。下面是C#的AES加密解密算法。
///<summary>
/// 有密码的AES加密
///</summary>
///<param name="text"/>加密字符
///<returns></returns>
public static string AESEncrypt(string text)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] keyBytes = new byte[16];
rijndaelCipher.Key = GetKey();// keyBytes;
rijndaelCipher.IV = GetIv();
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
///<summary>/// 获取密钥
///</summary>///<returns></returns>public static byte[] GetKey()
{
byte[] arrChar = new byte[]{0x21, 0x24, 0x16, 0x58, 0x30, 0x5B, 0xCD,
0x42, 0x93, 0xAB, 0x56, 0xDE, 0xAC, 0x26, 0xEF, 0xCD };
return arrChar;
}
///<summary>/// 获取默认密钥向量
///</summary>///<returns></returns>
public static byte[] GetIv()
{
byte[] arrChar = new byte[]{0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD,
0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0x31, 0x78 };
return arrChar;
}
///<summary>/// AES解密
///</summary>///<param name="text"/>///<returns></returns>
public static string AESDecrypt(string text, byte[] key, byte[] iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(text);
rijndaelCipher.Key = key;
rijndaelCipher.IV = iv;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}彭亚欧个人博客原创文章,转载请注明出处
文章关键词:C# AES加解 AES解密
文章固定链接:https://www.pengyaou.com/homeart/NTY=.html
上一篇 BEYOND