gateio / WebSocket-API

gateio WebSocket-API
56 stars 32 forks source link

Py2 to Py3 Hmac #6

Closed araa47 closed 4 years ago

araa47 commented 5 years ago

Hi, I am unable to recreate the same HMAC signature in python3. In python3 you need to pass it a bytes object since str is not supported anymore as an argument for hmac.

Python2 Example:

# -*- coding: utf-8 -*-
import hmac
import hashlib
import base64

def sign(secret, message):
    msg_hash = hmac.new(secret, message, hashlib.sha512)
    msg_hash = msg_hash.digest() 
    msg_hash = base64.b64encode(msg_hash)
    return msg_hash 

Python3 Example:

# -*- coding: utf-8 -*-
import hmac 
import hashlib 
import base64 

def sign(secret, message):
    message = message.encode('utf-8')
    secret = secret.encode('utf-8')
    msg_hash = hmac.new(secret, message, hashlib.sha256)
    msg_hash = msg_hash.digest()
    msg_hash = base64.b64encode(msg_hash)
    return msg_hash

Now if i run

(sign('jafsdljkahsjhafjklsadlfak','1552960209216' ))

The results are different.

Python2: lFXxSNxoV+wRS0v6sorrFwJGUGkGAUczqMWU869ABmMJwP1+17uqa0YjX8eBZif4kna7P3LAR+gkii/OMauQpg==

Python3: b'+P5Zday6xpB60/RArWMZmExteHSl6zcz0Dc7NpfddlI='

0GCRYPT0 commented 4 years ago

9 I believe my fix should close out this issue. @araa47 do you mind testing out the fix?

revilwang commented 4 years ago

The different result has nothing to do with Python version. You used hashlib.sha256 in Python3 code, which should be hashlib.sha512 instead