Python3 Hmac/Hashlib加解密

Python3 Hmac/Hashlib加解密

简介

hashlib模块实现了md5,sha1,sha224,sha256,sha384,sha512等算法,可以通过hashlib.algorithms_available查看

hmac模块实现了hmac算法,需要一个key来进行加密

hashlib : 不可逆加密 
hmac : 不可逆键值对方式加密

代码

# -*- coding: utf-8 -*-
import hashlib
import hmac
import base64
from urllib.parse import unquote, urlencode


class EncryptionHmac(object):
    def __init__(self):
        pass

    @staticmethod
    def get_md5_hex(value):
        m2 = hashlib.md5()
        m2.update(value.encode('utf-8'))
        return m2.hexdigest()

    @staticmethod
    def get_encrypt_hmac_sha1(secret, data):
        return str(base64.b64encode(hmac.new(bytes(secret, 'utf-8'),
                                             bytes(data, 'utf-8'), hashlib.sha1).digest()),
                   'utf-8')

    # 入参json, 按key排序,再转成query形式的参数。 eg.  apple=100&appKey=xxxx
    # unquote忽略转义,需要保留转义请取掉unquote
    def generate_sign(self, app_secret, data, encrypt_method='hmac-sha1' ):
        s = unquote(urlencode([(k, data[k]) for k in sorted(data.keys())]))
        if encrypt_method == "hmac-sha1":
            sign = self.get_encrypt_hmac_sha1(app_secret, s)
        else:
            s += app_secret
            sign = self.get_md5_hex(s)
        print("SIGN is : {}".format(sign))
        return sign


if __name__ == '__main__':

    app_key = "3f82df082747de1ea85f95c4c9f53c97"
    app_secret = "e2afd6d564854cb79e320ef1226bdb4a"
    param = {'nonceStr': '8B9yTWlx', 'appKey': app_key, 'apple': 100}
    sign = EncryptionHmac().generate_sign(app_secret, param)
    print(sign)


猜你喜欢

转载自blog.csdn.net/sf376566817/article/details/85161607