2013/02/28

C#.Net 檔案加解密

C#.NET 檔案加解密指南

在 C#.NET 中,檔案加解密是保護敏感數據的一種重要方法。本文將介紹如何使用 System.Security.Cryptography 命名空間來實現檔案的加密與解密。


1. 為什麼需要檔案加解密?

在現代應用中,數據安全是一個重要議題。如果未經加密,存儲的敏感數據可能被惡意存取。使用加密技術可以確保只有授權人員能夠存取檔案內容。


2. 使用 AES 進行檔案加密

AES(Advanced Encryption Standard)是一種常用的加密標準,適用於對檔案進行加解密。以下是 AES 加密檔案的 C# 代碼:

using System;
using System.IO;
using System.Security.Cryptography;

public class FileEncryptor
{
    public static void EncryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
    {
        using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
        using (FileStream fsEncrypted = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        using (Aes aes = Aes.Create())
        using (CryptoStream cs = new CryptoStream(fsEncrypted, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write))
        {
            byte[] buffer = new byte[1048576];
            int read;
            while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
            {
                cs.Write(buffer, 0, read);
            }
            cs.FlushFinalBlock();
        }
    }
}

3. 使用 AES 進行檔案解密

加密後的檔案可以使用相同的金鑰(Key)和初始化向量(IV)來解密,以下是解密的 C# 代碼:

using System;
using System.IO;
using System.Security.Cryptography;

public class FileDecryptor
{
    public static void DecryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
    {
        using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
        using (FileStream fsDecrypted = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        using (Aes aes = Aes.Create())
        using (CryptoStream cs = new CryptoStream(fsInput, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read))
        {
            byte[] buffer = new byte[1048576];
            int read;
            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                fsDecrypted.Write(buffer, 0, read);
            }
        }
    }
}

4. 重要注意事項

  • 金鑰(Key)與 IV:請確保在加密和解密時使用相同的 keyiv,否則解密將失敗。
  • 金鑰管理:避免將金鑰硬編碼在代碼中,建議使用安全存儲方式,如環境變數或加密金鑰管理系統。
  • 錯誤處理:應加強錯誤處理機制,以確保在加解密過程中能夠正確處理異常情況。

5. 結論

透過以上的方式,我們可以在 C#.NET 中使用 AES 進行檔案加解密,確保數據的安全性。希望這篇文章能夠幫助你理解並實作 C# 檔案加密與解密的技術。


參考資料