C#对称加密(AES加密)每次生成的密文结果不同思路代码分享
2015-01-16 17:12
639 查看
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前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");
相关文章推荐
- C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例
- [组件代码共享]可逆加密,支持中文,支持密钥,支持ASP,加密后的密文每次都不同,且可随意改变算法
- linux DES秘钥生成每次加密结果不同
- [代码发布]可逆加密,支持中文,支持密钥,支持ASP,加密后的密文每次都不同,且可随意改变算法
- 实用的PHP带公钥加密类分享(每次加密结果都不一样哦)
- 可逆加密,支持中文,支持密钥,加密后的密文每次都不同,且可随意改变算法 组件之Vb.Net版本
- 实用的PHP带公钥加密类分享(每次加密结果都不一样哦)
- android平台下的aes加密和java平台下的运行结果不同的解决办法
- [自用门户]加密解密,每次生成的结果不一样(Base64Utils+RSAUtils)
- 明密钥+暗密钥加密算法,好处:每次加密结果不同
- 不再害羞,过程比结果更重要;分享一套 CodeSmit 代码生成模板。
- AES加密算法在linux下相同输入每次加密结果都不同的问题
- android平台下的aes加密和java平台下的运行结果不同的解决办法
- Linux操作系统下每次AES加密结果不一致的原因
- AES加密解密Windows下跟linux下结果不同的解决方案
- [转-来自啊泰]可逆加密,支持中文,支持密钥,加密后的密文每次都不同,且可随意改变算法 组件之Vb.Net版本 [http://www.cnblogs.com/babyt/archive/2005/04/13/136613.html]
- Rsa 非对称加密算法使用问题分享--使用通过密钥对同一段数据加密得到结果每次不一样
- android平台下的aes加密和java平台下的运行结果不同的解决办法
- 使用openssl 生成AES加密并且对加密结果进行base64加密
- AES加密解密Windows下跟linux下结果不同的解决方案