欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-01-07 11:27:14|栏目:.NET代码|点击:

思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前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");


上一篇:通过VS中的数据源选择对话框简单实现数据库连接配置[图]

栏    目:.NET代码

下一篇:Global.asax的Application_BeginRequest实现url重写无后缀的代码

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

本文地址:http://www.codeinn.net/misctech/41851.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有