1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| function Protect-File { param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Key )
$keyBytes = [System.Security.Cryptography.SHA256]::Create().ComputeHash( [System.Text.Encoding]::UTF8.GetBytes($Key) ) $aes = [System.Security.Cryptography.Aes]::Create() $aes.Key = $keyBytes $aes.GenerateIV()
$plainBytes = [System.IO.File]::ReadAllBytes($Path)
$encryptor = $aes.CreateEncryptor() $encryptedBytes = $encryptor.TransformFinalBlock($plainBytes, 0, $plainBytes.Length)
$output = New-Object byte[] ($aes.IV.Length + $encryptedBytes.Length) [System.Array]::Copy($aes.IV, $output, $aes.IV.Length) [System.Array]::Copy($encryptedBytes, 0, $output, $aes.IV.Length, $encryptedBytes.Length)
$encPath = $Path + ".enc" [System.IO.File]::WriteAllBytes($encPath, $output) Write-Host "已加密:$Path => $encPath" -ForegroundColor Green }
function Unprotect-File { param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Key, [string]$OutputPath )
$keyBytes = [System.Security.Cryptography.SHA256]::Create().ComputeHash( [System.Text.Encoding]::UTF8.GetBytes($Key) ) $allBytes = [System.IO.File]::ReadAllBytes($Path)
$aes = [System.Security.Cryptography.Aes]::Create() $aes.Key = $keyBytes
$iv = New-Object byte[] ($aes.BlockSize / 8) [System.Array]::Copy($allBytes, $iv, $iv.Length) $aes.IV = $iv
$cipherBytes = New-Object byte[] ($allBytes.Length - $iv.Length) [System.Array]::Copy($allBytes, $iv.Length, $cipherBytes, 0, $cipherBytes.Length)
$decryptor = $aes.CreateDecryptor() $decryptedBytes = $decryptor.TransformFinalBlock($cipherBytes, 0, $cipherBytes.Length)
$outPath = if ($OutputPath) { $OutputPath } else { $Path -replace '\.enc$', '' } [System.IO.File]::WriteAllBytes($outPath, $decryptedBytes) Write-Host "已解密:$Path => $outPath" -ForegroundColor Green }
Protect-File -Path "C:\MyApp\appsettings.json" -Key "Production-Key-2025" Unprotect-File -Path "C:\MyApp\appsettings.json.enc" -Key "Production-Key-2025"
|