這段程式碼定義了一個名為 Decrypt-DataAndDisplay 的函式,主要用於自動化腳本的「驗證階段」,確保我們產生的金鑰檔能正確還原回明碼密碼。
函式參數詳細說明
為了確保解密過程順利,本函式需要傳入三個關鍵的檔案路徑參數:
| 參數名稱 | 功能與用途 |
|---|---|
| $EncryptedFilePath (加密後的資料來源) |
這是我們在上一篇加密過程中產生的 .txt 檔案。程式會讀取這個檔案中的 Byte 陣列內容,準備進行還原。 |
| $KeyFilePath (加密金鑰 Key) |
相當於保險箱的鑰匙。AES 是對稱式加密,解密時必須讀取與加密時完全相同的 Base64 金鑰字串,否則無法解鎖。 |
| $IVFilePath (初始化向量 IV) |
這是為了增加加密隨機性而產生的數據。解密演算法必須使用與加密時相同的 IV,才能正確對齊並還原資料,否則解出來的資料會是亂碼或報錯。 |
程式運作邏輯
- 讀取階段:程式首先從指定的路徑讀取加密檔、Key 與 IV。其中 Key 與 IV 會從 Base64 格式轉換回原本的 Byte 陣列。
- 建立解密器:使用 .NET Framework 的
System.Security.Cryptography.Aes類別,並填入對應的 Key 與 IV 建立解密物件。 - 執行還原:使用
TransformFinalBlock方法將加密的 Byte 陣列還原,最後轉碼為 UTF-8 字串顯示。
[程式碼] 解密與驗證腳本
請將以下內容存為 Decrypt-Tool.ps1 並執行:
# ==========================================
# PowerShell AES Decryption Tool (V6 Part 2)
# ==========================================
# 定義函數:解密資料並輸出顯示
function Decrypt-DataAndDisplay {
param (
[string]$EncryptedFilePath, # 加密後的檔案路徑
[string]$KeyFilePath, # 加密金鑰檔案路徑
[string]$IVFilePath # 初始化向量檔案路徑
)
Write-Host "正在進行資料解密..." -ForegroundColor Cyan
try {
# 1. 讀取加密後的位元組陣列
$EncryptedBytes = [System.IO.File]::ReadAllBytes($EncryptedFilePath)
# 2. 讀取金鑰和初始化向量 (Base64)
$KeyBase64 = Get-Content -Path $KeyFilePath
$IVBase64 = Get-Content -Path $IVFilePath
# 3. 轉換為位元組陣列
$KeyBytes = [System.Convert]::FromBase64String($KeyBase64)
$IVBytes = [System.Convert]::FromBase64String($IVBase64)
# 4. 建立 AES 解密物件
$AesAlg = [System.Security.Cryptography.Aes]::Create()
$AesAlg.Key = $KeyBytes
$AesAlg.IV = $IVBytes
# 5. 建立解密器並執行
$decryptor = $AesAlg.CreateDecryptor($AesAlg.Key, $AesAlg.IV)
$DecryptedBytes = $decryptor.TransformFinalBlock($EncryptedBytes, 0, $EncryptedBytes.Length)
# 6. 轉回 UTF-8 文字
$DecryptedText = [System.Text.Encoding]::UTF8.GetString($DecryptedBytes)
Write-Host "解密結果:" -ForegroundColor Green
Write-Host $DecryptedText -ForegroundColor Yellow
} catch {
Write-Host "解密過程中發生錯誤: $_" -ForegroundColor Red
} finally {
if ($AesAlg) { $AesAlg.Dispose() }
if ($decryptor) { $decryptor.Dispose() }
}
}
# --- 測試與執行 ---
# 設定檔案路徑 (需與加密時一致)
$KeyFilePath = "C:\temp\aes_key.txt"
$IVFilePath = "C:\temp\aes_iv.txt"
$EncryptedFilePath = "C:\temp\encrypted_data.txt"
# 呼叫解密函式
Decrypt-DataAndDisplay -EncryptedFilePath $EncryptedFilePath -KeyFilePath $KeyFilePath -IVFilePath $IVFilePath
這段程式碼主要利用了 .NET 中的加密 API (Aes 類別) 來實現 AES 解密的功能,並使用 PowerShell 來處理檔案讀取和顯示。
(參考資料: ChatGPT 問答測試結果)
請先 登入 以發表留言。