[PowerShell] IIS SSL 憑證自動更新教學 (V5 解密篇):安全還原加密密碼
這篇是 PowerShell 自動化更新 IIS SSL 憑證 V5 版的「解密篇」。在前一篇我們已經將密碼進行 AES 加密,本篇將展示如何在自動化腳本中讀取 Key 與 IV,安全地將密碼還原為明文以供程式使用,徹底告別腳本內寫死明碼的資安風險。
📝 前言:
💡 系列導讀:這是 V5 版本的核心組件(解密篇)。
如果您還沒看過加密金鑰的產生方式,請先參考 V5 加密篇。本篇將介紹如何從加密文件中還原私鑰密碼,確保自動化腳本能正確匯入 PFX 憑證。
🚀 新版發布:IIS SSL 自動化腳本 V6 (完整版)
您目前觀看的是單一函式的解密教學。為了提升自動化穩定度,我已釋出最新的 V6 完整版,整合了金鑰下載、自動解密與 IIS 綁定流程。
👉 點此前往:[PowerShell] IIS SSL 憑證自動更新全攻略 (V6)這段程式碼的主要功能是解密之前加密過的憑證私鑰密碼,並將結果還原為可用字串。以下是解密流程的技術細節:
1. Decrypt-Password 函式邏輯
函式運作分為以下五個關鍵步驟:
- 參數接收: 接收
$KeyFilePath(AES 金鑰路徑) 與$EncryptedPasswordFilePath(加密檔案路徑)。 - 金鑰載入: 從檔案讀取 Base64 字串,並還原為 32 bytes 的二進位金鑰。
- 加密內容讀取: 取得
ConvertFrom-SecureString產生的加密字串。 - 安全性還原: 使用
ConvertTo-SecureString指令配合 AES 金鑰還原為 PowerShell 的SecureString對象。 - 明碼轉換: 利用
Marshal類別將安全字串轉回普通字串,以便於後續匯入憑證時使用。
2. [Code] 解密工具程式碼
請將以下內容存為 Decrypt-Tool.ps1 並確保金鑰與加密檔案已存在於對應路徑:
# --- 定義解密函數 ---
function Decrypt-Password {
param (
[string]$KeyFilePath,
[string]$EncryptedPasswordFilePath
)
Write-Host "正在執行憑證私鑰解密程序..." -ForegroundColor Cyan
try {
# 1. 讀取並還原 AES 金鑰
$Key = [System.Convert]::FromBase64String((Get-Content $KeyFilePath))
# 2. 讀取加密後的密碼內容
$EncryptedPassword = Get-Content -Path $EncryptedPasswordFilePath
# 3. 解密回 SecureString
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword -Key $Key
# 4. 將 SecureString 轉回明碼字串
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword))
Write-Host "成功:憑證私鑰密碼已還原。" -ForegroundColor Green
return $Password
} catch {
Write-Host "失敗:解密過程中發生錯誤,請檢查金鑰是否正確。" -ForegroundColor Red
return $null
}
}
# --- 執行範例 ---
$KeyPath = "c:\temp\encryption_key.txt"
$EncPasswordPath = "c:\temp\encrypted_password.txt"
$OriginalPassword = Decrypt-Password -KeyFilePath $KeyPath -EncryptedPasswordFilePath $EncPasswordPath
# 僅供測試顯示,生產環境建議直接傳遞變數不顯示
if ($OriginalPassword) {
Write-Host "還原後的密碼為: $OriginalPassword" -ForegroundColor Yellow
}
🛡️ 安全建議:
雖然解密後的密碼已還原,但在生產環境中,應避免使用Write-Host顯示解密後的密碼。建議將結果直接傳遞給Import-PfxCertificate函式使用。
留言
張貼留言