2016-03-30 17 views
0

我有下面的代碼工作沒有任何錯誤。SecureString與SecureKey問題

  1. SaveKeyPass.ps1被存儲的安全密鑰(加密)和密碼(使用securekey加密)
  2. 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位)密鑰,但例外是抱怨不正確的密鑰長度。

任何幫助,將不勝感激。謝謝閱讀!

+2

'$ decryptedSecureKeyFromFile'是什麼? –

+0

由於Mathias指出你的問題在第11行,似乎源於代碼中未引用的運行時變量。 – Djarid

回答

0

感謝馬丁和Djarid的地方,我已經改正了線路11 SaveKeyPass.ps1到

$encryptedPassword = ConvertFrom-SecureString $SecurePassword -SecureKey $secureKey 

其中已解決問題 完全第2期部分。 對於問題2:

我注意到,1個字符在鍵/數字是16位(可能在我的64臺機器),其意思是「12345678912345671234567891234567」是512個比特,而不是256位,我以爲思維1個字符/數字是8個字節。因此這違反了密鑰的最大長度要求並失敗。

這意味着如果我在密鑰中提供8,12,16個字符,它們分別是128位,192位和256位。

+0

它與您的機器無關。 PowerShell內的字符串是.NET的System.String類的16位Unicode實例。 –