我有下面的代碼工作沒有任何錯誤。SecureString與SecureKey問題
- SaveKeyPass.ps1被存儲的安全密鑰(加密)和密碼(使用securekey加密)
- GetKeyPass.ps1會從文件中的安全密鑰和密碼進行解密,安全密鑰,並在最後的解密密碼使用解密的securekey。
SaveKeyPass.ps1
$key = "1234567891234567"
$textPassword = "securekey-textpassword"
$securePassword = ConvertTo-SecureString $textPassword -AsPlainText -Force
$secureKey = ConvertTo-SecureString $Key -AsPlainText -Force
$encryptedKey = ConvertFrom-SecureString $SecureKey -Key (1..16)
$encryptedPassword = ConvertFrom-SecureString $SecurePassword -SecureKey $decryptedSecureKeyFromFile
$encryptedKey | Out-File "C:\temp\securekey-enckey.txt"
$encryptedPassword | Out-File "C:\temp\securekey-encpass.txt"
Write-Host "Key: $Key"
Write-Host "Text Password: $textPassword"
Write-Host "Encrypted Password: $encryptedPassword"
Write-Host "Encrypted Key: $encryptedKey"
GetKeyPass.ps1
$key = ""
$textPassword = ""
$encryptedPasswordFromFile = ""
$encryptedKeyFromFile = ""
$secureDecryptedPassword = ""
$BSTR1= ""
$BSTR2= ""
$encryptedKeyFromFile = Get-Content "C:\temp\securekey-enckey.txt"
$encryptedPasswordFromFile = Get-Content "C:\temp\securekey-encpass.txt"
$secureDecryptedKey = ConvertTo-SecureString $encryptedKeyFromFile -Key (1..16)
$secureDecryptedPassword = ConvertTo-SecureString $encryptedPasswordFromFile -SecureKey $secureDecryptedKey
$BSTR1 = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureDecryptedPassword)
$textPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR1)
$BSTR2 = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureDecryptedKey)
$key = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR2)
Write-Host "Key: $key"
Write-Host "Text Password: $textPassword"
Write-Host "Encrypted Password: $encryptedPasswordFromFile"
Write-Host "Encrypted Key: $encryptedKeyFromFile"
問題1:
如果我改變第一線(僅最後一位從7變爲8)SaveKeyPass.ps1並執行該腳本
$key = "1234567891234568"
,隨後執行GetKeyPass.ps1我得到這個錯誤
ConvertTo-SecureString : Padding is invalid and cannot be removed. At [**]:11 char:28
問題2:
如果我改變第一線在SaveKeyPass.ps1(密鑰長度從16個字節改爲32個字節)並執行這個腳本
$key = "12345678912345671234567891234567"
,隨後執行GetKeyPass.ps1我得到這個錯誤
The specified key is not valid. Valid key length settings are either 128 bits, 192 bits, or 256 bits. At [**]:11 char:28
我對正在發生的事情真的很無能?在問題1只有一個數字被改變,所以不知道從填充異常拋出的位置。在問題2我有32字節(256位)密鑰,但例外是抱怨不正確的密鑰長度。
任何幫助,將不勝感激。謝謝閱讀!
'$ decryptedSecureKeyFromFile'是什麼? –
由於Mathias指出你的問題在第11行,似乎源於代碼中未引用的運行時變量。 – Djarid