[C#]使用AES進行檔案加密

這次的學習與參考來自:
[C#.NET] 字串及檔案 利用 DES / AES 演算法加解密 – 余小章 @ 大內殿堂

以下實作了一個AesController來使用
範例如下,設定KeyIV之後,測試加密與解密功能

static void Main(string[] args)
{
    string key = "YourKey16Bytes..";
    string iv = "YourIv16Bytes...";
    string file = "D:\\TestCase\\file.xml";
    string afterEncrypt = "D:\\TestCase\\afterEncrypt.xml";
    string afterDecrypt = "D:\\TestCase\\afterDecrypt.xml";

    AesController ctrl = new AesController(key, iv);
    ctrl.Encrypt(file, afterEncrypt);
    ctrl.Decrypt(afterEncrypt, afterDecrypt);
}

下圖是原始檔案的內容

2017-5-12 下午 04-25-51.png

經過加密之後,無法判讀原始內容

2017-5-12 下午 05-10-11.png

最後再解密回來

2017-5-12 下午 05-10-27.png

範例完成
最後則是AesController的內容

public class AesController
{
    private Aes aes;
    public AesController(string key, string iv)
    {
        Aes aes = CreateAes(key, iv);
    }
    public void Decrypt(string inputPath, string outputPath)
    {
        ICryptoTransform decryptor = aes.CreateDecryptor();
        ToCrypt(inputPath, outputPath, decryptor);
    }
    
 
    public void Encrypt(string inputPath, string outputPath)
    {
        ICryptoTransform encryptor = aes.CreateEncryptor();
        ToCrypt(inputPath, outputPath, encryptor);
    }
    private Aes CreateAes(string key, string iv)
    {
        byte setSize = 16;
        if (key.Length != setSize || iv.Length != setSize)
        {
            throw new Exception($"Input.Length != {setSize}");
        }
        aes = Aes.Create();
        aes.Key = Encoding.ASCII.GetBytes(key);
        aes.IV = Encoding.ASCII.GetBytes(iv);
        return aes;
    }
    private void ToCrypt(string inputPath, string outputPath, ICryptoTransform icrypt)
    {
        using (FileStream fsRead = new FileStream(inputPath, FileMode.Open, FileAccess.Read))
        using (FileStream fsWrite = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
        {
            byte[] dataAry = new byte[fsRead.Length];
            fsRead.Read(dataAry, 0, dataAry.Length);

            using (CryptoStream cs = new CryptoStream(fsWrite, icrypt, CryptoStreamMode.Write))
            {
                cs.Write(dataAry, 0, dataAry.Length);
                cs.FlushFinalBlock();
            }
        }
    }
}
廣告