简体   繁体   English

在 Python 中生成 SHA256 HMAC 签名

[英]Generate SHA256 HMAC signature in Python

I'm trying to generate a SHA256 HMAC signature for a FTX websocket.我正在尝试为 FTX websocket 生成 SHA256 HMAC 签名。 I am using the params fromt he official example https://docs.ftx.com/#private-channels .我正在使用官方示例https://docs.ftx.com/#private-channels中的参数。

It should generate d10b5a67a1a941ae9463a60b285ae845cdeac1b11edc7da9977bef0228b96de9它应该生成 d10b5a67a1a941ae9463a60b285ae845cdeac1b11edc7da9977bef0228b96de9

but I am getting ad38fa3566de972abb736bc0db2f7cd39daa48b14421e168422303bf2f03c6de但我得到了 ad38fa3566de972abb736bc0db2f7cd39daa48b14421e168422303bf2f03c6de

here is what I tried:这是我尝试过的:

import hmac
import hashlib
import base64

time = '1557246346499'
secret = 'Y2QTHI23f23f23jfjas23f23To0RfUwX3H42fvN-'


digest = hmac.new(bytes(time, 'UTF-8'),
                bytes(secret, 'UTF-8'), hashlib.sha256)
signature = digest.hexdigest()
print(signature)

There are two mistakes: first, hmac.new() takes the arguments in the reverse order: hmac.new(secret, msg, digestmod) , and second, the message should be <time>websocket_login :有两个错误:首先, hmac.new()以相反的顺序获取 arguments: hmac.new(secret, msg, digestmod) ,其次,消息应该是<time>websocket_login

import hmac
import hashlib

time = '1557246346499'
secret = 'Y2QTHI23f23f23jfjas23f23To0RfUwX3H42fvN-'


digest = hmac.new(
    secret.encode(), 
    f'{time}websocket_login'.encode(),
    hashlib.sha256
)
signature = digest.hexdigest()
print(signature)

I'm not familiar with these things, but your code differs from the one I found in Python encoded message with HMAC-SHA256 , message and key seem to be swapped.我对这些东西不熟悉,但是您的代码与我在使用 HMAC-SHA256 编码的 Python 编码消息中找到的代码不同,消息和密钥似乎已交换。
That would be a duplicate only, however another thing is that the documentation you link says那只是重复的,但是另一件事是您链接的文档说

sign : SHA256 HMAC of the following string, using your API secret: <time>websocket_login sign :以下字符串的 SHA256 HMAC,使用您的 API 密码: <time>websocket_login

So it's not 1557246346499 , but 1557246346499websocket_login what you need.因此,您需要的不是1557246346499 ,而是1557246346499websocket_login

Put together:放在一起:

import hmac
import hashlib

time = '1557246346499websocket_login'
secret = 'Y2QTHI23f23f23jfjas23f23To0RfUwX3H42fvN-'


signature = hmac.new(bytes(secret , 'latin-1'), msg = bytes(time , 'latin-1'), digestmod = hashlib.sha256).hexdigest()
print(signature)

Generates the expected output.生成预期的 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM