无效的内容验证签名(Python中的HMAC)

时间:2018-02-16 17:10:26

标签: php python api

我需要PHP帮助Python 3+代码转换。通过Auth and examples部分的https://icobench.com/developers链接,您可以找到使用网站API工作的类的代码。

我已经编写了Python类,但它无法正常工作。

import html
import io
import json
import hashlib
import hmac
import pycurl


class ICObenchAPI:
    private_key = ''
    public_key = ''
    api_url = 'https://icobench.com/api/v1/'
    result = None

    def get_icos(self, parameter='all', data=''):
        return self.send('icos/{0}'.format(parameter), data)

    def get_ico(self, ico_id, data=''):
        return self.send('ico/{0}'.format(str(ico_id)), data)

    def get_other(self, parameter):
        return self.send('other/{0}'.format(parameter), '')

    def get_people(self, parameter='registered', data=''):
        return self.send('people/{0}'.format(parameter), data)

    def send(self, action, data):
        data_json = json.dumps(data)
        print("data_json: ", data_json)

        #$sig = base64_encode(hash_hmac('sha384', $dataJson, $this->privateKey, true));

        signature = hmac.new(self.private_key.encode('utf-8'), msg=data_json.encode('utf-8'), digestmod=hashlib.sha384).hexdigest()

        print("signature: ", signature)
        headers = [
            'Content-Type: application/json',
            'Content-Length: {0}'.format(len(data_json)),
            'X-ICObench-Key: {0}'.format(self.public_key),
            'X-ICObench-Sig: {0}'.format(signature)
        ]
        print("headers: ", headers)
        buffer = io.BytesIO()
        action_url = self.api_url + action
        print("action_url: ", action_url)
        ch = pycurl.Curl()
        ch.setopt(pycurl.URL, action_url)
        ch.setopt(pycurl.POSTFIELDS, data_json)
        ch.setopt(pycurl.SSL_VERIFYPEER, False)
        ch.setopt(pycurl.HTTPHEADER, headers)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.perform()
        reply = buffer.getvalue().decode('UTF-8')
        ff = reply
        reply = json.loads(reply)
        if reply['error'] is not None:
            self.result = reply['error']
            return False
        elif reply['message'] is not None:
            self.result = reply['message']
            return True
        elif reply is not None:
            self.result = json.dumps(reply)
            return True
        else:
            self.result = html.escape(ff)
            return False

    def get_result(self):
        return self.result

服务器已在回答:

  

无效的内容验证签名

我认为HMAC部分的问题。我的代码出了什么问题?谢谢!

1 个答案:

答案 0 :(得分:0)

问题是编码!正确使用HMAC的方法:

hm = hmac.new(bytes(self.private_key, "ascii"), bytes(data_json, "utf-8"), hashlib.sha384)
signature = base64.b64encode(hm.digest()).decode('utf-8')