程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#對稱加密(AES加密)每次生成的成果都分歧的完成思緒和代碼實例

C#對稱加密(AES加密)每次生成的成果都分歧的完成思緒和代碼實例

編輯:C#入門知識

C#對稱加密(AES加密)每次生成的成果都分歧的完成思緒和代碼實例。本站提示廣大學習愛好者:(C#對稱加密(AES加密)每次生成的成果都分歧的完成思緒和代碼實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#對稱加密(AES加密)每次生成的成果都分歧的完成思緒和代碼實例正文


思緒:應用隨機向量,把隨機向量放入密文中,每次解密時從密文中截取前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).WordStr("\0", "");  ///將字符串後尾的'\0'去失落
  }
  catch { }
  return result;
}

挪用:

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


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved