gpt4 book ai didi

python - 在 Powershell 中使用 key 进行哈希

转载 作者:行者123 更新时间:2023-12-01 02:24:45 25 4
gpt4 key购买 nike

我正在尝试使用 key 在 Powershell 中创建哈希,但与使用 Python 执行此操作相比,我似乎得到了不同的结果。

它是我为 API 调用生成的签名。

我使用的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代码如下:

$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 代码不同。

最佳答案

在 PowerShell 版本中,您需要执行一项附加操作 - 将字节数组转换为 Base64 字符串 - 在将其转换为大写之前:

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

另一方面,Python 将数组转换为十六进制字符串。

将 powershell 版本更改为:

$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() 将生成与 .hexdigest().upper() 完全相同的格式

关于python - 在 Powershell 中使用 key 进行哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47518260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com