2011-11-04 51 views
0

我試圖使用SHA1 64位編碼密碼來訪問Web服務,但我不確定如何在PowerShell中對其進行編碼。如何使用PowerShell v2加密和編碼密碼?

我試着使用: PS C:\ Program Files文件(x86)的\的PowerGUI> $密碼= 「這裏沒有顯示密碼」

PS C:\Program Files (x86)\PowerGUI> $bytes = System.Text.Encoding]::Unicode.GetBytes($password) 

PS C:\Program Files (x86)\PowerGUI> $encodedString = [Convert]::ToBase64CharArray($bytes) 

但我得到這個回:

找不到該「ToBase64CharArray」的過載和參數計數:「1」。 在行:1字符:46 + $ encodedString = [變換] :: ToBase64CharArray < < < <($字節) + CategoryInfo:NotSpecified:(:) [],MethodException + FullyQualifiedErrorId:MethodCountCouldNotFindBest

我對於PowerShell新功能,所以這可能不是正確的代碼使用。我試圖修改我在網上找到的一個例子。

任何想法如何使用SHA1加密和base64編碼在PowerShell中做到這一點?


好了,這個工程的編碼,感謝喬納森這部分:

$str = "pwd" 
$bytes = [System.Text.Encoding]::Unicode.GetBytes($str) 
$encodedStr = [Convert]::ToBase64String($bytes) 

# and the result: 
Write-Host $encodedStr 
cAB3AGQA 

我注意到函數調用::是空白敏感。這適用於加密部分。

$Sha1provider = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider 
$hashBytes = $Sha1provider.ComputeHash($bytes) 
Write-Host $hashBytes 
114 168 243 129 97 21 246 249 22 4 38 215 241 185 174 86 116 201 7 7 

回答

1

Convert.ToBase64CharArray方法沒有隻有一個參數的重載。

http://msdn.microsoft.com/en-us/library/3d0e5t57.aspx

你可能想要做的:

$encodedString = [Convert]::ToBase64String($bytes); 
write-host $encodedString 

注意,base64編碼是不是SHA1編碼。看看這裏:http://blog.logiclabz.com/c/function-to-encrypt-string-in-c-net-using-sha1-algorithm.aspx

此外,你不一定要將C#代碼轉換爲Powershell。

您可以使用Add-Type在腳本中包含C#代碼。

PS:我想你知道編碼不是加密嗎? http://www.blesta.com/2009/07/26/encoding-vs-encryption/