加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实

发布时间:2020-12-15 03:48:53 所属栏目:百科 来源:网络整理
导读:思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。 代码: public static string Encrypt(string plainText,string AESKey){ RijndaelManaged rijndaelCipher = new RijndaelManaged(); byte[] in

思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前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,inputByteArray.Length);
      cs.FlushFinalBlock();
      cipherBytes = ms.ToArray();//得到加密后的字节数组
      cs.Close();
      ms.Close();
    }
  }
  var allEncrypt = new byte[keyIv.Length + cipherBytes.Length];
  Buffer.BlockCopy(keyIv,allEncrypt,keyIv.Length);
  Buffer.BlockCopy(cipherBytes,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,iv,16);
    rijndaelCipher.IV = iv;
    byte[] decryptBytes = new byte[length - 16];
    byte[] passwdText = new byte[length - 16];
    Buffer.BlockCopy(cipherText,16,passwdText,length - 16);
    using (MemoryStream ms = new MemoryStream(passwdText))
    {
      using (CryptoStream cs = new CryptoStream(ms,rijndaelCipher.CreateDecryptor(),CryptoStreamMode.Read))
      {
        cs.Read(decryptBytes,decryptBytes.Length);
        cs.Close();
        ms.Close();
      }
    }
    result = Encoding.UTF8.GetString(decryptBytes).Replace("","");  ///将字符串后尾的''去掉
  }
  catch { }
  return result;
}

调用:

string jiaMi = MyAESTools.Encrypt(textBox1.Text,"abcdefgh12345678abcdefgh12345678");
 
string jieMi = MyAESTools.Decrypt(textBox3.Text,"abcdefgh12345678abcdefgh12345678");


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读