【发布时间】:2016-03-31 17:28:59
【问题描述】:
我有下面的代码,没有任何错误。
- SaveKeyPass.ps1 存储安全密钥(加密)和密码(使用安全密钥加密)
- GetKeyPass.ps1 从文件中获取安全密钥和密码,然后解密安全密钥,最后使用解密的安全密钥解密密码。
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:
如果我将 SaveKeyPass.ps1 中的第一行(仅最后一位从 7 更改为 8)更改为并执行此脚本
$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
我真的不知道发生了什么?在 issue 1 中仅更改了一位数字,因此不确定从何处引发填充异常。在问题 2中,我有 32 字节(256 位)的密钥,但异常是抱怨密钥长度不正确。
任何帮助将不胜感激。感谢阅读!
【问题讨论】:
-
$decryptedSecureKeyFromFile是什么? -
正如 Mathias 指出的那样,您的问题在第 11 行,并且似乎源于您的代码中未引用的运行时变量。
标签: powershell encryption securestring