前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#对称加密(AES加密)每次生成的密文结果不同思路代码分享

C#对称加密(AES加密)每次生成的密文结果不同思路代码分享

作者头像
磊哥
发布2018-04-26 17:03:47
1.5K0
发布2018-04-26 17:03:47
举报

思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前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");
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-01-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档