[PowerShell] IIS SSL 憑證自動更新教學 (V5 加密篇):安全保護私鑰密碼

這篇是 PowerShell 自動化更新 IIS SSL 憑證 V5 版的「加密篇」。為了解決腳本中明文儲存密碼的資安風險,本篇教學將展示如何利用 .NET Framework 的 AES 類別生成金鑰與 IV,並將敏感資料安全加密為二進位檔案。
📝 前言:
💡 系列導讀:這是 V5 版本的基礎構件(加密篇)。
在自動化流程中,如何安全地處理 PFX 憑證密碼是關鍵。本篇將介紹如何利用 PowerShell 隨機生成 AES 金鑰,並將憑證私鑰密碼轉換為加密檔案,以供自動化腳本調用。

🚀 新版發布:IIS SSL 自動化腳本 V6 (完整版)

您目前觀看的是 V5 加密邏輯教學。為了提升自動化穩定度,我已釋出最新的 V6 完整版,整合了金鑰管理與自動解密流程。

👉 點此前往:[PowerShell] IIS SSL 憑證自動更新全攻略 (V6)

這段程式碼的主要功能是用來加密一個使用者輸入的憑證私鑰密碼,並將加密後的結果存儲到指定的文件中。

1. 函式參數詳細說明

本工具需要定義三個關鍵變數來完成加密作業:

參數名稱 功能與用途
$Password 要加密的密碼: 使用者輸入的敏感資訊(如私鑰密碼),程式會將其轉換為 SecureString 後加密。
$KeyFilePath 加密金鑰路徑: 程式隨機生成的 AES 金鑰儲存位置。這把「鑰匙」是未來解鎖密碼的唯一憑證,須嚴格管控。
$EncryptedPasswordFilePath 加密後密碼路徑: 輸出的加密內容檔案。即使此檔案流出,沒有相對應的 Key 也無法還原內容。

2. 程式運作邏輯

加密流程遵循以下四大步驟:

  • 生成金鑰: 使用 Get-Random 搭配 1..32 陣列產生 32 bytes (256-bit) 的 AES 隨機金鑰。
  • 安全輸入: 使用 Read-Host -AsSecureString 確保密碼輸入過程中不以明文顯示。
  • 資料轉換: 透過 ConvertFrom-SecureString 搭配指定的 AES Key 執行加密。
  • 持久化儲存: 將金鑰與加密後的密碼字串分別輸出至指定的 TXT 檔案。

3. [程式碼] 加密工具腳本

請將以下內容存為 Encrypt-Tool-V5.ps1 並執行:

# --- 定義加密函數 --- function Encrypt-Password { param ( [string]$Password, [string]$KeyFilePath, [string]$EncryptedPasswordFilePath ) Write-Host "正在加密憑證私鑰密碼..." -ForegroundColor Cyan # 從檔案讀取 Key 並轉回 Byte 陣列 $Key = [System.Convert]::FromBase64String((Get-Content $KeyFilePath)) # 執行加密作業 $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force $EncryptedPassword = $SecurePassword | ConvertFrom-SecureString -Key $Key # 儲存加密結果 $EncryptedPassword | Out-File -FilePath $EncryptedPasswordFilePath -Force Write-Host "成功:密碼已加密並存儲至 $EncryptedPasswordFilePath" -ForegroundColor Green } # --- 主程式執行區 --- $KeyFilePath = "c:\temp\encryption_key.txt" $EncryptedPasswordFilePath = "c:\temp\encrypted_password.txt" # 1. 生成隨機 AES-256 金鑰並儲存 $AES_Key = [System.Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Minimum 0 -Maximum 256 })) $AES_Key | Out-File -FilePath $KeyFilePath -Force Write-Host "已生成加密金鑰:$KeyFilePath" -ForegroundColor Yellow # 2. 提示輸入密碼 (以安全星號顯示) $SecureIn = Read-Host -Prompt "請輸入要加密的憑證私鑰密碼" -AsSecureString $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureIn)) # 3. 呼叫函式執行加密 Encrypt-Password -Password $Password -KeyFilePath $KeyFilePath -EncryptedPasswordFilePath $EncryptedPasswordFilePath

📚 參考資源

留言

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

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