1. 程式人生 > 程式設計 >c# AES位元組陣列加密解密流程及程式碼實現

c# AES位元組陣列加密解密流程及程式碼實現

AES類時微軟MSDN中最常用的加密類,微軟官網也有例子,參考連結:https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.aes?view=netframework-4.8
但是這個例子並不好用,限制太多,通用性差,實際使用中,我遇到的更多情況需要是這樣:
1、輸入一個位元組陣列,經AES加密後,直接輸出加密後的位元組陣列。
2、輸入一個加密後的位元組陣列,經AES解密後,直接輸出原位元組陣列。

對於我這個十八流業餘愛好者來說,AES我是以用為主的,所以具體的AES是怎麼運算的,我其實並不關心,我更關心的是AES的處理流程。結果恰恰這一方面,網上的資訊差強人意,看了網上不少的帖子,但感覺都沒有說完整說透,而且很多帖子有錯誤。

因此,我自己繪製了一張此種方式下的流程圖:

c# AES位元組陣列加密解密流程及程式碼實現

按照此流程圖進行了核心程式碼的編寫,驗證方法AesCoreSingleTest既是依照此流程的產物,例項化類AesCoreSingle後呼叫此方法即可驗證。

至於類中的非同步方法EnOrDecryptFileAsync,則是專門用於檔案加解密的處理,此非同步方法參考自《C# 6.0學習筆記》(周家安 著)最後的示例,這本書寫得真棒。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace AesSingleFile
{
  class AesCoreSingle
  {
    /// <summary>
    /// 使用使用者口令,生成符合AES標準的key和iv。
    /// </summary>
    /// <param name="password">使用者輸入的口令</param>
    /// <returns>返回包含金鑰和向量的元組</returns>
    private (byte[] Key,byte[] IV) GenerateKeyAndIV(string password)
    {
      byte[] key = new byte[32];
      byte[] iv = new byte[16];
      byte[] hash = default;
      if (string.IsNullOrWhiteSpace(password))
        throw new ArgumentException("必須輸入口令!");
      using (SHA384 sha = SHA384.Create())
      {
        byte[] buffer = Encoding.UTF8.GetBytes(password);
        hash = sha.ComputeHash(buffer);
      }
      //用SHA384的原因:生成的384位雜湊值正好被分成兩段使用。(32+16)*8=384。
      Array.Copy(hash,key,32);//生成256位金鑰(32*8=256)
      Array.Copy(hash,32,iv,16);//生成128位向量(16*8=128)
      return (Key: key,IV: iv);
    }

    public byte[] EncryptByte(byte[] buffer,string password)
    {
      byte[] encrypted;
      using (Aes aes = Aes.Create())
      {
        //設定金鑰和向量
        (aes.Key,aes.IV) = GenerateKeyAndIV(password);
        //設定運算模式和填充模式
        aes.Mode = CipherMode.CBC;//預設
        aes.Padding = PaddingMode.PKCS7;//預設
        //建立加密器物件(加解密方法不同處僅僅這一句話)
        var encryptor = aes.CreateEncryptor(aes.Key,aes.IV);
        using (MemoryStream msEncrypt = new MemoryStream())
        {
          using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))//選擇Write模式
          {
            csEncrypt.Write(buffer,buffer.Length);//對原陣列加密並寫入流中
            csEncrypt.FlushFinalBlock();//使用Write模式需要此句,但Read模式必須要有。
            encrypted = msEncrypt.ToArray();//從流中寫入陣列(加密之後,陣列變長,詳見方法AesCoreSingleTest內容)
          }
        }
      }
      return encrypted;
    }
    public byte[] DecryptByte(byte[] buffer,string password)
    {
      byte[] decrypted;
      using (Aes aes = Aes.Create())
      {
        //設定金鑰和向量
        (aes.Key,aes.IV) = GenerateKeyAndIV(password);
        //設定運算模式和填充模式
        aes.Mode = CipherMode.CBC;//預設
        aes.Padding = PaddingMode.PKCS7;//預設
        //建立解密器物件(加解密方法不同處僅僅這一句話)
        var decryptor = aes.CreateDecryptor(aes.Key,aes.IV);
        using (MemoryStream msDecrypt = new MemoryStream(buffer))
        {
          using (CryptoStream csDecrypt = new CryptoStream(msDecrypt,decryptor,CryptoStreamMode.Read))//選擇Read模式
          {
            byte[] buffer_T = new byte[buffer.Length];/*--s1:建立臨時陣列,用於包含可用位元組+無用位元組--*/

            int i = csDecrypt.Read(buffer_T,buffer.Length);/*--s2:對加密陣列進行解密,並通過i確定實際多少位元組可用--*/

            //csDecrypt.FlushFinalBlock();//使用Read模式不能有此句,但write模式必須要有。

            decrypted = new byte[i];/*--s3:建立只容納可用位元組的陣列--*/

            Array.Copy(buffer_T,decrypted,i);/*--s4:從bufferT拷貝出可用位元組到decrypted--*/
          }
        }
        return decrypted;
      }
    }
    public byte[] EnOrDecryptByte(byte[] buffer,string password,ActionDirection direction)
    {
      if (buffer == null)
        throw new ArgumentNullException("buffer為空");
      if (password == null || password == "")
        throw new ArgumentNullException("password為空");
      if (direction == ActionDirection.EnCrypt)
        return EncryptByte(buffer,password);
      else
        return DecryptByte(buffer,password);
    }
    public enum ActionDirection//該列舉說明是加密還是解密
    {
      EnCrypt,//加密
      DeCrypt//解密
    }
    public static void AesCoreSingleTest(string s_in,string password)//驗證加密解密模組正確性方法
    {
      byte[] buffer = Encoding.UTF8.GetBytes(s_in);
      AesCoreSingle aesCore = new AesCoreSingle();
      byte[] buffer_ed = aesCore.EncryptByte(buffer,password);
      byte[] buffer_ed2 = aesCore.DecryptByte(buffer_ed,password);
      string s = Encoding.UTF8.GetString(buffer_ed2);
      string s2 = "下列字串\n" + s + '\n' + $"原buffer長度 → {buffer.Length},加密後buffer_ed長度 → {buffer_ed.Length},解密後buffer_ed2長度 → {buffer_ed2.Length}";
      MessageBox.Show(s2);
      /* 字串在加密前後的變化(預設CipherMode.CBC運算模式,PaddingMode.PKCS7填充模式)
       * 1、如果陣列長度為16的倍數,則加密後的陣列長度=原長度+16
        如對於下列字串
        D:\User\Documents\Administrator - DOpus Config - 2020-06-301.ocb
        使用UTF8編碼轉化為位元組陣列後,
        原buffer → 64,加密後buffer_ed → 80,解密後buffer_ed2 → 64
       * 2、如果陣列長度不為16的倍數,則加密後的陣列長度=16倍數向上取整
        如對於下列字串
        D:\User\Documents\cc_20200630_113921.reg
        使用UTF8編碼轉化為位元組陣列後
        原buffer → 40,加密後buffer_ed → 48,解密後buffer_ed2 → 40
        參考文獻:
        1-《AES補位填充PaddingMode.Zeros模式》http://blog.chinaunix.net/uid-29641438-id-5786927.html
        2-《關於PKCS5Padding與PKCS7Padding的區別》https://www.cnblogs.com/midea0978/articles/1437257.html
        3-《AES-128 ECB 加密有感》http://blog.sina.com.cn/s/blog_60cf051301015orf.html
       */
    }

    /***---宣告CancellationTokenSource物件--***/
    private CancellationTokenSource cts;//using System.Threading;引用
    public Task EnOrDecryptFileAsync(Stream inStream,long inStream_Seek,Stream outStream,long outStream_Seek,ActionDirection direction,IProgress<int> progress)
    {
      /***---例項化CancellationTokenSource物件--***/
      cts?.Dispose();//cts為空,不動作,cts不為空,執行Dispose。
      cts = new CancellationTokenSource();

      Task mytask = new Task(
        () =>
        {
          EnOrDecryptFile(inStream,inStream_Seek,outStream,outStream_Seek,password,direction,progress);
        },cts.Token,TaskCreationOptions.LongRunning);
      mytask.Start();
      return mytask;
    }
    public void EnOrDecryptFile(Stream inStream,IProgress<int> progress)
    {
      if (inStream == null || outStream == null)
        throw new ArgumentException("輸入流與輸出流是必須的");
      //--調整流的位置(通常是為了避開檔案頭部分)
      inStream.Seek(inStream_Seek,SeekOrigin.Begin);
      outStream.Seek(outStream_Seek,SeekOrigin.Begin);
      //用於記錄處理進度
      long total_Length = inStream.Length - inStream_Seek;
      long totalread_Length = 0;
      //初始化報告進度
      progress.Report(0);

      using (Aes aes = Aes.Create())
      {
        //設定金鑰和向量
        (aes.Key,aes.IV) = GenerateKeyAndIV(password);
        //建立加密器解密器物件(加解密方法不同處僅僅這一句話)
        ICryptoTransform cryptor;
        if (direction == ActionDirection.EnCrypt)
          cryptor = aes.CreateEncryptor(aes.Key,aes.IV);
        else
          cryptor = aes.CreateDecryptor(aes.Key,aes.IV);
        using (CryptoStream cstream = new CryptoStream(outStream,cryptor,CryptoStreamMode.Write))
        {
          byte[] buffer = new byte[512 * 1024];//每次讀取512kb的資料
          int readLen = 0;
          while ((readLen = inStream.Read(buffer,buffer.Length)) != 0)
          {
            // 向加密流寫入資料
            cstream.Write(buffer,readLen);
            totalread_Length += readLen;
            //彙報處理進度
            if (progress != null)
            {
              long per = 100 * totalread_Length / total_Length;
              progress.Report(Convert.ToInt32(per));
            }
          }
        }
      }
    }
  }
}

以上就是c# AES位元組陣列加密解密流程及程式碼實現的詳細內容,更多關於c# AES位元組陣列加密解密的資料請關注我們其它相關文章!