C#实现AES加密解密

AES 

 

AES 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法

Rijndael(读作rain-dahl)是由美国国家标准与技术协会(NIST)所选的高级加密标准(AES)的候选算法。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。


Rijndael 算法首先是一个密钥分组加密的算法,通过置换(permutations )和替换(substitutions)迭代加密,进过多轮操作形成密文。


AES算是Rijndael算法的一种特殊实现,选的分组为128bit(16字节),密钥可以使用128、192 和 256bit三种,而Rijndael使用的密钥和区块长度可以是32位的整数倍,以128位为下限,256比特为上限。加密过程中使用的密钥是由Rijndael密钥生成方案产生。


AES加密过程是在一个4×4的字节矩阵上运作,这个矩阵又称为“状态(state)”,其初值就是一个明文区块(矩阵中一个元素大小就是明文区块中的一个Byte)。(Rijndael加密法因支持更大的区块,其矩阵行数可视情况增加)加密时,各轮AES加密循环(除最后一轮外)均包含4个步骤:
AddRoundKey — 矩阵中的每一个字节都与该次轮秘钥(round key)做XOR运算;每个子密钥由密钥生成方案产生。
SubBytes — 通过非线性的替换函数,用查找表的方式把每个字节替换成对应的字节。
ShiftRows — 将矩阵中的每个横列进行循环式移位。
MixColumns — 为了充分混合矩阵中各个直行的操作。这个步骤使用线性转换来混合每列的四个字节。

 

 

RijndaelManager代码实现

 

 

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.Text;
  4.  
    using System.Security.Cryptography;
  5.  
    using System.IO;
  6.  
     
  7.  
    namespace Csharp
  8.  
    {
  9.  
    class AESHelper
  10.  
    {
  11.  
    /// <summary>
  12.  
    /// AES加密
  13.  
    /// </summary>
  14.  
    /// <param name="Data">被加密的明文</param>
  15.  
    /// <param name="Key">密钥</param>
  16.  
    /// <param name="Vector">向量</param>
  17.  
    /// <returns>密文</returns>
  18.  
    public static String AESEncrypt(String Data, String Key, String Vector)
  19.  
    {
  20.  
    Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
  21.  
     
  22.  
    Byte[] bKey = new Byte[32];
  23.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  24.  
    Byte[] bVector = new Byte[16];
  25.  
    Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
  26.  
     
  27.  
    Byte[] Cryptograph = null; // 加密后的密文
  28.  
     
  29.  
    Rijndael Aes = Rijndael.Create();
  30.  
    try
  31.  
    {
  32.  
    // 开辟一块内存流
  33.  
    using (MemoryStream Memory = new MemoryStream())
  34.  
    {
  35.  
    // 把内存流对象包装成加密流对象
  36.  
    using (CryptoStream Encryptor = new CryptoStream(Memory,
  37.  
    Aes.CreateEncryptor(bKey, bVector),
  38.  
    CryptoStreamMode.Write))
  39.  
    {
  40.  
    // 明文数据写入加密流
  41.  
    Encryptor.Write(plainBytes, 0, plainBytes.Length);
  42.  
    Encryptor.FlushFinalBlock();
  43.  
     
  44.  
    Cryptograph = Memory.ToArray();
  45.  
    }
  46.  
    }
  47.  
    }
  48.  
    catch
  49.  
    {
  50.  
    Cryptograph = null;
  51.  
    }
  52.  
     
  53.  
    return Convert.ToBase64String(Cryptograph);
  54.  
    }
  55.  
     
  56.  
    /// <summary>
  57.  
    /// AES解密
  58.  
    /// </summary>
  59.  
    /// <param name="Data">被解密的密文</param>
  60.  
    /// <param name="Key">密钥</param>
  61.  
    /// <param name="Vector">向量</param>
  62.  
    /// <returns>明文</returns>
  63.  
    public static String AESDecrypt(String Data, String Key, String Vector)
  64.  
    {
  65.  
    Byte[] encryptedBytes = Convert.FromBase64String(Data);
  66.  
    Byte[] bKey = new Byte[32];
  67.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  68.  
    Byte[] bVector = new Byte[16];
  69.  
    Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
  70.  
     
  71.  
    Byte[] original = null; // 解密后的明文
  72.  
     
  73.  
    Rijndael Aes = Rijndael.Create();
  74.  
    try
  75.  
    {
  76.  
    // 开辟一块内存流,存储密文
  77.  
    using (MemoryStream Memory = new MemoryStream(encryptedBytes))
  78.  
    {
  79.  
    // 把内存流对象包装成加密流对象
  80.  
    using (CryptoStream Decryptor = new CryptoStream(Memory,
  81.  
    Aes.CreateDecryptor(bKey, bVector),
  82.  
    CryptoStreamMode.Read))
  83.  
    {
  84.  
    // 明文存储区
  85.  
    using (MemoryStream originalMemory = new MemoryStream())
  86.  
    {
  87.  
    Byte[] Buffer = new Byte[1024];
  88.  
    Int32 readBytes = 0;
  89.  
    while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
  90.  
    {
  91.  
    originalMemory.Write(Buffer, 0, readBytes);
  92.  
    }
  93.  
     
  94.  
    original = originalMemory.ToArray();
  95.  
    }
  96.  
    }
  97.  
    }
  98.  
    }
  99.  
    catch
  100.  
    {
  101.  
    original = null;
  102.  
    }
  103.  
    return Encoding.UTF8.GetString(original);
  104.  
    }
  105.  
     
  106.  
     
  107.  
     
  108.  
    /// <summary>
  109.  
    /// AES加密(无向量)
  110.  
    /// </summary>
  111.  
    /// <param name="plainBytes">被加密的明文</param>
  112.  
    /// <param name="key">密钥</param>
  113.  
    /// <returns>密文</returns>
  114.  
    public static string AESEncrypt(String Data, String Key)
  115.  
    {
  116.  
    MemoryStream mStream = new MemoryStream();
  117.  
    RijndaelManaged aes = new RijndaelManaged();
  118.  
     
  119.  
    byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
  120.  
    Byte[] bKey = new Byte[32];
  121.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  122.  
     
  123.  
    aes.Mode = CipherMode.ECB;
  124.  
    aes.Padding = PaddingMode.PKCS7;
  125.  
    aes.KeySize = 128;
  126.  
    //aes.Key = _key;
  127.  
    aes.Key = bKey;
  128.  
    //aes.IV = _iV;
  129.  
    CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
  130.  
    try
  131.  
    {
  132.  
    cryptoStream.Write(plainBytes, 0, plainBytes.Length);
  133.  
    cryptoStream.FlushFinalBlock();
  134.  
    return Convert.ToBase64String(mStream.ToArray());
  135.  
    }
  136.  
    finally
  137.  
    {
  138.  
    cryptoStream.Close();
  139.  
    mStream.Close();
  140.  
    aes.Clear();
  141.  
    }
  142.  
    }
  143.  
     
  144.  
     
  145.  
    /// <summary>
  146.  
    /// AES解密(无向量)
  147.  
    /// </summary>
  148.  
    /// <param name="encryptedBytes">被加密的明文</param>
  149.  
    /// <param name="key">密钥</param>
  150.  
    /// <returns>明文</returns>
  151.  
    public static string AESDecrypt(String Data, String Key)
  152.  
    {
  153.  
    Byte[] encryptedBytes = Convert.FromBase64String(Data);
  154.  
    Byte[] bKey = new Byte[32];
  155.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  156.  
     
  157.  
    MemoryStream mStream = new MemoryStream(encryptedBytes);
  158.  
    //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
  159.  
    //mStream.Seek( 0, SeekOrigin.Begin );
  160.  
    RijndaelManaged aes = new RijndaelManaged();
  161.  
    aes.Mode = CipherMode.ECB;
  162.  
    aes.Padding = PaddingMode.PKCS7;
  163.  
    aes.KeySize = 128;
  164.  
    aes.Key = bKey;
  165.  
    //aes.IV = _iV;
  166.  
    CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
  167.  
    try
  168.  
    {
  169.  
    byte[] tmp = new byte[encryptedBytes.Length + 32];
  170.  
    int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
  171.  
    byte[] ret = new byte[len];
  172.  
    Array.Copy(tmp, 0, ret, 0, len);
  173.  
    return Encoding.UTF8.GetString(ret);
  174.  
    }
  175.  
    finally
  176.  
    {
  177.  
    cryptoStream.Close();
  178.  
    mStream.Close();
  179.  
    aes.Clear();
  180.  
    }
  181.  
    }
  182.  
    }
  183.  
    }

AesManager代码实现

 

  1.  
    using System;
  2.  
    using System.IO;
  3.  
    using System.Security.Cryptography;
  4.  
     
  5.  
    namespace Aes_Example
  6.  
    {
  7.  
    class AesExample
  8.  
    {
  9.  
    public static void Main()
  10.  
    {
  11.  
    try
  12.  
    {
  13.  
    string original = "Here is some data to encrypt!";
  14.  
     
  15.  
    // Create a new instance of the AesManaged
  16.  
    // class. This generates a new key and initialization
  17.  
    // vector (IV).
  18.  
    using (AesManaged myAes = new AesManaged())
  19.  
    {
  20.  
    // Encrypt the string to an array of bytes.
  21.  
    byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
  22.  
     
  23.  
    // Decrypt the bytes to a string.
  24.  
    string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
  25.  
     
  26.  
    //Display the original data and the decrypted data.
  27.  
    Console.WriteLine("Original: {0}", original);
  28.  
    Console.WriteLine("Round Trip: {0}", roundtrip);
  29.  
    }
  30.  
     
  31.  
    }
  32.  
    catch (Exception e)
  33.  
    {
  34.  
    Console.WriteLine("Error: {0}", e.Message);
  35.  
    }
  36.  
    }
  37.  
    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
  38.  
    {
  39.  
    // Check arguments.
  40.  
    if (plainText == null || plainText.Length <= 0)
  41.  
    throw new ArgumentNullException("plainText");
  42.  
    if (Key == null || Key.Length <= 0)
  43.  
    throw new ArgumentNullException("Key");
  44.  
    if (IV == null || IV.Length <= 0)
  45.  
    throw new ArgumentNullException("IV");
  46.  
    byte[] encrypted;
  47.  
    // Create an AesManaged object
  48.  
    // with the specified key and IV.
  49.  
    using (AesManaged aesAlg = new AesManaged())
  50.  
    {
  51.  
    aesAlg.Key = Key;
  52.  
    aesAlg.IV = IV;
  53.  
     
  54.  
    // Create a decrytor to perform the stream transform.
  55.  
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  56.  
     
  57.  
    // Create the streams used for encryption.
  58.  
    using (MemoryStream msEncrypt = new MemoryStream())
  59.  
    {
  60.  
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  61.  
    {
  62.  
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  63.  
    {
  64.  
     
  65.  
    //Write all data to the stream.
  66.  
    swEncrypt.Write(plainText);
  67.  
    }
  68.  
    encrypted = msEncrypt.ToArray();
  69.  
    }
  70.  
    }
  71.  
    }
  72.  
     
  73.  
     
  74.  
    // Return the encrypted bytes from the memory stream.
  75.  
    return encrypted;
  76.  
     
  77.  
    }
  78.  
     
  79.  
    static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
  80.  
    {
  81.  
    // Check arguments.
  82.  
    if (cipherText == null || cipherText.Length <= 0)
  83.  
    throw new ArgumentNullException("cipherText");
  84.  
    if (Key == null || Key.Length <= 0)
  85.  
    throw new ArgumentNullException("Key");
  86.  
    if (IV == null || IV.Length <= 0)
  87.  
    throw new ArgumentNullException("IV");
  88.  
     
  89.  
    // Declare the string used to hold
  90.  
    // the decrypted text.
  91.  
    string plaintext = null;
  92.  
     
  93.  
    // Create an AesManaged object
  94.  
    // with the specified key and IV.
  95.  
    using (AesManaged aesAlg = new AesManaged())
  96.  
    {
  97.  
    aesAlg.Key = Key;
  98.  
    aesAlg.IV = IV;
  99.  
     
  100.  
    // Create a decrytor to perform the stream transform.
  101.  
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  102.  
     
  103.  
    // Create the streams used for decryption.
  104.  
    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
  105.  
    {
  106.  
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  107.  
    {
  108.  
    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  109.  
    {
  110.  
     
  111.  
    // Read the decrypted bytes from the decrypting stream
  112.  
    // and place them in a string.
  113.  
    plaintext = srDecrypt.ReadToEnd();
  114.  
    }
  115.  
    }
  116.  
    }
  117.  
     
  118.  
    }
  119.  
     
  120.  
    return plaintext;
  121.  
    }
  122.  
    }
  123.  
    }
原文地址:https://www.cnblogs.com/huanglg/p/11979473.html