繁体   English   中英

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

[英]Invalid Content Verification Signature (HMAC in Python)

我需要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部分存在问题。 我的代码有什么问题? 谢谢!

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

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

暂无
暂无

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

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