2017-11-27 1 views
1

私はキーを使ってPowershellでハッシュを作成しようとしていますが、私はPythonでそれをやっているときとは違った結果を得ているようです。Powershellのキーを使ったハッシュ

私はAPI呼び出しのために生成しているその署名です。

$nonce = "20" 
$clientid = "mdfgfgkjl3456" 
$apikey = "asdkjasdkljsomekey" 
$message = $nonce + $clientid + $apikey 
$secret = "dsdklfjsdfkljsomesecret" 

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256 
     $hmacsha.key = [Text.Encoding]::ASCII.GetBytes($secret) 
     $signature = 
$hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message)) 
     $signature = ([Convert]::ToBase64String($signature)).ToUpper() 
     $signature 

PowerShellが実行され、それは次いで、Pythonコードを別の署名を生成する:私は次の通りである有し

nonce   = "20" 
client_id  = "mdfgfgkjl3456" 
api_key  = "asdkjasdkljsomekey" 
message  = nonce + client_id + api_key 
secret  = "dsdklfjsdfkljsomesecret" 
secret_bytes = bytes(secret , 'latin-1') 
message_bytes = bytes(message , 'latin-1') 

signature = hmac.new(
    secret_bytes, 
    msg=message_bytes, 
    digestmod=hashlib.sha256 
).hexdigest().upper() 

Powershellのコードを次のように私が使用

ザPythonコードであります。追加の操作を実行するPowerShellのバージョンで

+1

とまったく同じ形式を生成します(私は信じて)デフォルトの文字に対し:へのPowerShellのバージョンが

変更PowershellのエンコーディングはUTF-16です –

+0

ありがとうBryce私は両方のText.EncodingのためにUTF8に変更しましたが、私はまだ正しい結果を得ていません: '([Text.Encoding] :: UTF8.GetBytes($)メッセージ)) ' – Gee1983

+0

あなたのPythonインスタンスをエンコードしているテキストを調べることをお勧めします。奇妙なものを使用している場合は、powershellに同じものを使用させる必要があります。 –

答えて

1

- Base64文字列をバイト配列に変換 - 大文字に変換する前に:

$signature = ([Convert]::ToBase64String($signature)).ToUpper() 

Pythonの一方は、16進文字列に配列を変換します。

$nonce = "20" 
$clientid = "mdfgfgkjl3456" 
$apikey = "asdkjasdkljsomekey" 
$message = $nonce + $clientid + $apikey 
$secret = "dsdklfjsdfkljsomesecret" 

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256 
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($secret) 
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message)) 
$signature = -join($signature |ForEach-Object ToString X2).ToUpper() 
$signature 

-join($signature |ForEach-Object ToString X2).ToUpper() Python用のデフォルトの文字エンコーディングがUTF-8であるので、これはある.hexdigest().upper()

+0

マティアスが私の問題を解決してくれてありがとう、ありがとう。 – Gee1983

関連する問題