[PowerShell] IIS SSL 憑證自動更新全攻略 (V6 解密篇):安全還原加密密碼技術

這篇是 PowerShell 自動化更新 IIS SSL 憑證 V6 版的「解密篇」。在前一篇我們已經將密碼進行 AES 加密,本篇將展示如何在自動化腳本中讀取 Key 與 IV,安全地將密碼還原為明文以供程式使用,徹底告別腳本內寫死明碼的資安風險。
📝 前言:
💡 系列導讀: 這是 V6 版本的第二部分(解密篇)。
定義了名為 Decrypt-DataAndDisplay 的函式,主要用於自動化腳本的驗證與實行階段。解密過程必須使用加密時產生的金鑰與向量。如果您還沒看過加密金鑰的產生方式,請先參考:V6 加密篇
(或者 前往 Blogger 閱讀完整合併版)

這段程式碼主要用於確保自動化腳本能正確從加密檔案中還原回明文密碼,是整個 SSL 憑證自動更新流程中,維持安全性的核心組件。

1. 函式參數詳細說明

解密函式需要完全對應加密時的三個檔案,任何一個不符皆無法還原資料:

參數名稱 功能與用途
$EncryptedFilePath 加密資料來源: 讀取加密過程中產生的 .txt 檔案,其內容為二進位 Byte 陣列。
$KeyFilePath 加密金鑰 (Key): 對稱式加密的鑰匙。解密時必須使用與加密時完全一致的 Base64 字串。
$IVFilePath 初始化向量 (IV): 用於確保加密隨機性。IV 不符會導致解碼失敗或產生亂碼。

2. 程式運作邏輯解析

  • 讀取階段: 程式從指定路徑讀取加密位元組、金鑰與 IV。金鑰與 IV 會從 Base64 格式轉回 Byte 陣列。
  • 物件建立: 使用 System.Security.Cryptography.Aes 類別,並將 Key 與 IV 注入物件建立解密器。
  • 執行還原: 調用 TransformFinalBlock 執行解密運算,最後將結果透過 UTF8.GetString 轉回可讀文字。

3. [程式碼] 解密與驗證工具 (V6)

請將以下內容存為 Decrypt-Tool.ps1 並確保檔案路徑正確:

# ========================================== # PowerShell AES Decryption Tool (V6 Part 2) # ========================================== function Decrypt-DataAndDisplay { param ( [string]$EncryptedFilePath, [string]$KeyFilePath, [string]$IVFilePath ) Write-Host "正在執行 AES 資料解密..." -ForegroundColor Cyan try { # 1. 讀取加密位元組 $EncryptedBytes = [System.IO.File]::ReadAllBytes($EncryptedFilePath) # 2. 讀取金鑰與 IV (從 Base64 轉回) $KeyBase64 = Get-Content -Path $KeyFilePath $IVBase64 = Get-Content -Path $IVFilePath $KeyBytes = [System.Convert]::FromBase64String($KeyBase64) $IVBytes = [System.Convert]::FromBase64String($IVBase64) # 3. 初始化 AES 解密物件 $AesAlg = [System.Security.Cryptography.Aes]::Create() $AesAlg.Key = $KeyBytes $AesAlg.IV = $IVBytes # 4. 執行解密轉換 $decryptor = $AesAlg.CreateDecryptor() $DecryptedBytes = $decryptor.TransformFinalBlock($EncryptedBytes, 0, $EncryptedBytes.Length) # 5. 轉換回字串 $DecryptedText = [System.Text.Encoding]::UTF8.GetString($DecryptedBytes) Write-Host "解密成功!" -ForegroundColor Green Write-Host "還原結果:" -NoNewline; Write-Host $DecryptedText -ForegroundColor Yellow } catch { Write-Host "錯誤:解密失敗,請確認 Key/IV/加密檔是否匹配。" -ForegroundColor Red } finally { if ($AesAlg) { $AesAlg.Dispose() } } } # --- 執行測試 --- $KeyPath = "C:\temp\aes_key.txt" $IVPath = "C:\temp\aes_iv.txt" $EncPath = "C:\temp\encrypted_data.txt" Decrypt-DataAndDisplay -EncryptedFilePath $EncPath -KeyFilePath $KeyPath -IVFilePath $IVPath
⚠️ 安全生產提醒:
在實際的自動化腳本中,解密後的結果應直接存入變數傳遞給 Import-PfxCertificate,請勿使用 Write-Host 顯示在控制台上,以防螢幕紀錄 (Log) 洩漏敏感密碼。

📚 參考資源

留言

自訂樣式 ~ CSS -- 簡約相簿

© Copyright 2021 Design By 灰鴿 | Modified by Sungshu ( Powered by Blogger )