时间:2021-05-20
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。
代码:
public static string Encrypt(string plainText, string AESKey){ RijndaelManaged rijndaelCipher = new RijndaelManaged(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 rijndaelCipher.Key = Convert.FromBase64String(AESKey);//加解密双方约定好密钥:AESKey rijndaelCipher.GenerateIV(); byte[] keyIv = rijndaelCipher.IV; byte[] cipherBytes = null; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); } } var allEncrypt = new byte[keyIv.Length + cipherBytes.Length]; Buffer.BlockCopy(keyIv, 0, allEncrypt, 0, keyIv.Length); Buffer.BlockCopy(cipherBytes, 0, allEncrypt, keyIv.Length * sizeof(byte), cipherBytes.Length); return Convert.ToBase64String(allEncrypt);} public static string Decrypt(string showText, string AESKey){ string result = string.Empty; try { byte[] cipherText = Convert.FromBase64String(showText); int length = cipherText.Length; SymmetricAlgorithm rijndaelCipher = Rijndael.Create(); rijndaelCipher.Key = Convert.FromBase64String(AESKey);//加解密双方约定好的密钥 byte[] iv = new byte[16]; Buffer.BlockCopy(cipherText, 0, iv, 0, 16); rijndaelCipher.IV = iv; byte[] decryptBytes = new byte[length - 16]; byte[] passwdText = new byte[length - 16]; Buffer.BlockCopy(cipherText, 16, passwdText, 0, length - 16); using (MemoryStream ms = new MemoryStream(passwdText)) { using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } } result = Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); ///将字符串后尾的'\0'去掉 } catch { } return result;}调用:
string jiaMi = MyAESTools.Encrypt(textBox1.Text, "abcdefgh12345678abcdefgh12345678"); string jieMi = MyAESTools.Decrypt(textBox3.Text, "abcdefgh12345678abcdefgh12345678");声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例为大家分享了python实现AES加密和解密的具体代码,供大家参考,具体内容如下参考:python实现AES加密和解密AES加密算法是一种对称加密算法,
本文实例汇总了C#文件加密方法。分享给大家供大家参考。具体实现方法如下:1、AES加密类复制代码代码如下:usingSystem;usingSystem.IO;
本文实例讲述了C#实现的AES加密解密。分享给大家供大家参考,具体如下:/*******************************************
本文实例讲述了python实现的AES双向对称加密解密与用法。分享给大家供大家参考,具体如下:高级加密标准(AdvancedEncryptionStandard
本文实例为大家分享了python实现AES和RSA加解密的具体代码,供大家参考,具体内容如下AESAES是一种对称加密算法,用key对一段text加密,则用同一