C# Example of AES256 encryption using System.Security.Cryptography.Aes

前端 未结 3 1321
攒了一身酷
攒了一身酷 2021-01-01 12:07

I need to implement AES 256 encryption /decryption and I haven\'t been able to find an example that works correctly.

MSDN suggests that I should use the AES class.

3条回答
  •  清酒与你
    2021-01-01 13:02

    Maybe this example listed here can help you out. Statement from the author

    about 24 lines of code to encrypt, 23 to decrypt

    Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

      /*
      Copyright (c) 2010 James Craig
      
      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files (the "Software"), to deal
      in the Software without restriction, including without limitation the rights
      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:
      
      The above copyright notice and this permission notice shall be included in
      all copies or substantial portions of the Software.
      
      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      THE SOFTWARE.*/
       
      #region Usings
      using System;
      using System.IO;
      using System.Security.Cryptography;
      using System.Text;
      #endregion
       
      namespace Utilities.Encryption
      {
          /// 
          /// Utility class that handles encryption
          /// 
          public static class AESEncryption
          {
              #region Static Functions
       
              /// 
              /// Encrypts a string
              /// 
              /// Text to be encrypted
              /// Password to encrypt with
              /// Salt to encrypt with
              /// Can be either SHA1 or MD5
              /// Number of iterations to do
              /// Needs to be 16 ASCII characters long
              /// Can be 128, 192, or 256
              /// An encrypted string
              public static string Encrypt(string PlainText, string Password,
                  string Salt = "Kosher", string HashAlgorithm = "SHA1",
                  int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
                  int KeySize = 256)
              {
                  if (string.IsNullOrEmpty(PlainText))
                      return "";
                  byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
                  byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
                  byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
                  PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                  byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                  RijndaelManaged SymmetricKey = new RijndaelManaged();
                  SymmetricKey.Mode = CipherMode.CBC;
                  byte[] CipherTextBytes = null;
                  using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
                  {
                      using (MemoryStream MemStream = new MemoryStream())
                      {
                          using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                          {
                              CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                              CryptoStream.FlushFinalBlock();
                              CipherTextBytes = MemStream.ToArray();
                              MemStream.Close();
                              CryptoStream.Close();
                          }
                      }
                  }
                  SymmetricKey.Clear();
                  return Convert.ToBase64String(CipherTextBytes);
              }
       
              /// 
              /// Decrypts a string
              /// 
              /// Text to be decrypted
              /// Password to decrypt with
              /// Salt to decrypt with
              /// Can be either SHA1 or MD5
              /// Number of iterations to do
              /// Needs to be 16 ASCII characters long
              /// Can be 128, 192, or 256
              /// A decrypted string
              public static string Decrypt(string CipherText, string Password,
                  string Salt = "Kosher", string HashAlgorithm = "SHA1",
                  int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
                  int KeySize = 256)
              {
                  if (string.IsNullOrEmpty(CipherText))
                      return "";
                  byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
                  byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
                  byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
                  PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                  byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                  RijndaelManaged SymmetricKey = new RijndaelManaged();
                  SymmetricKey.Mode = CipherMode.CBC;
                  byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
                  int ByteCount = 0;
                  using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
                  {
                      using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                      {
                          using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                          {
       
                              ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                              MemStream.Close();
                              CryptoStream.Close();
                          }
                      }
                  }
                  SymmetricKey.Clear();
                  return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
              }
       
              #endregion
          }
      }
    

提交回复
热议问题