RSA签名方式(华为,金立,联想,oppo,三星,支付宝)
import base64
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA, SHA256, MD5
def rsa_sign(pri_key, data, sign_type='RSA'):
"""
:param pri_key: 私钥
:param data: 待签名数据
:param sign_type: 的签名方式
:return:
"""
key = RSA.importKey(pri_key)
if sign_type == 'RSA256':
h = SHA256.new(data)
elif sign_type == 'MD5':
h = MD5.new(data.encode('utf-8'))
else:
h = SHA.new(data)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
return base64.b64encode(signature)
def rsa_verify(pub_key, data, sign, sign_type='RSA'):
"""
:param pub_key: 公钥
:param data: 待签名数据
:param sign: 需要验签的签名
:param sign_type: 的签名方式
:return:
"""
key = RSA.importKey(pub_key)
if sign_type == 'RSA256':
h = SHA256.new(data)
elif sign_type == 'MD5':
h = MD5.new(data.encode('utf-8'))
else:
h = SHA.new(data)
verifier = PKCS1_v1_5.new(key)
return verifier.verify(h, base64.b64decode(sign))
MD5签名方式:(百度,阿里九游,魅族,360,vivo,微信)
import hashlib
md5Sign = str(hashlib.md5(sign_str).hexdigest()).lower()
Hmac-SHA1签名方式:(米大师(应用宝),小米)
from hashlib import sha1
import hmac
import base64
使用HMAC-SHA1加密算法,使用Step2中得到的密钥对Step1中得到的源串加密
my_sign = hmac.new(app_key, sign_str, sha1).digest()
将加密后的字符串经过Base64编码
my_sign = base64.b64encode(my_sign)