使用 AES 加密與解密字串

使用 AES 加密與解密字串

參考:

  1. Keep Your Data Secure with the New Advanced Encryption Standard by James McCaffrey
  2. C#使用AES加密算法源代碼 (上一篇的中文翻譯)
  3. Advanced Encryption Standard

 

範例程式碼:

   1:  string inputString = "測試文字";
   2:  string password = "p@ssw0rd";
   3:   
   4:  byte[] binputString = Encoding.UTF8.GetBytes(inputString);
   5:  byte[] saltBytes = Encoding.UTF8.GetBytes("salt string");
   6:   
   7:  RijndaelManaged aes = new RijndaelManaged();
   8:  Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, saltBytes);
   9:   
  10:  aes.KeySize = 128;
  11:  aes.Key = key.GetBytes(16);
  12:   
  13:  aes.BlockSize = 128;
  14:  aes.IV = key.GetBytes(16);
  15:   
  16:  ICryptoTransform encryptor = aes.CreateEncryptor();
  17:  MemoryStream memoryStream = new MemoryStream();
  18:  CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
  19:   
  20:  cryptoStream.Write(binputString, 0, binputString.Length);
  21:  cryptoStream.FlushFinalBlock();
  22:  cryptoStream.Close();
  23:   
  24:  byte[] encryptBytes = memoryStream.ToArray();
  25:  string encryptedData = Convert.ToBase64String(encryptBytes);
  26:   
  27:  MessageBox.Show(encryptedData);
  28:   
  29:  ICryptoTransform decryptor = aes.CreateDecryptor();
  30:  encryptBytes = Convert.FromBase64String(encryptedData);
  31:  memoryStream = new MemoryStream();
  32:  cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write);
  33:   
  34:  cryptoStream.Write(encryptBytes, 0, encryptBytes.Length);
  35:  cryptoStream.Flush();
  36:  cryptoStream.Close();
  37:   
  38:  byte[] decryptBytes = memoryStream.ToArray();
  39:  string decryptedData = Encoding.UTF8.GetString(decryptBytes);
  40:  MessageBox.Show(decryptedData);