码迷,mamicode.com
首页 > 其他好文 > 详细

AES 加密位: 128位,加密模式:CBC, 填充模式:Zeros

时间:2017-06-10 13:48:13      阅读:429      评论:0      收藏:0      [点我收藏+]

标签:created   byte   bytes   clear   .text   odi   oar   creat   close   

// AES 加密
        public byte[] AESEncrypt(string text)
        {
            byte[] data = Encoding.Unicode.GetBytes(text);
            SymmetricAlgorithm aes = Rijndael.Create();
            aes.Key = keyArray;
            aes.IV = keyArray;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();
                    byte[] cipherBytes = ms.ToArray(); // 得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                    aes.Clear();

                    return cipherBytes;
                }
            }
        }

// AES 解密
        public string AESDecrypt(byte[] data)
        {
            SymmetricAlgorithm aes = Rijndael.Create();
            aes.Key = keyArray;
            aes.IV = keyArray;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            byte[] decryptBytes = new byte[data.Length];

            using (MemoryStream ms = new MemoryStream(data))
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            aes.Clear();

            return System.Text.Encoding.Unicode.GetString(decryptBytes).Replace("\0", " ");
        }

AES 加密位: 128位,加密模式:CBC, 填充模式:Zeros

标签:created   byte   bytes   clear   .text   odi   oar   creat   close   

原文地址:http://www.cnblogs.com/wzzkaifa/p/6978403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!