1. 程式人生 > >Python3 Hmac/Hashlib加解密

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)