python的加密与解密_加签与验签

在与第三方服务对接时,加密与解密,加签与验签是这个过程中的关键一步一般情况下,对接服务中会有两对公私钥。使用对方公钥进行加密,使用自己私钥进行加签。传回来的数据,使用自己的私钥解密,使用对方的公钥验签。
 

加密与解密
1 import base64
2 from Crypto.PublicKey import RSA
3 from Crypto.Hash import SHA
4 from Crypto.Cipher import PKCS1_v1_5
5 from Crypto.Signature import PKCS1_v1_5 as SIGN_PKCS
6   
7 PUB_KEY = RSA.importKey(open('rsa_public_key.pem','r').read())
8 PRI_KEY = RSA.importKey(open('rsa_private_key.pem','r').read())

加密代码:

 1 def split_data(l, n):
 2     for i in range(0, len(l), n):
 3         yield l[i: i+n]
 4          
 5 def encrypt(params):
 6     raw = params.encode('utf-8')
 7     cipher = PKCS1_v1_5.new(PUB_KEY)
 8     # 加密超长字节117个字节一加密
 9     content = b''.join([cipher.encrypt(x) for x in chunks(raw, 117)])
10     return base64.b64encode(content)

解密代码:

1 def decrypt(data):
2     raw = data.encode('utf-8')
3     decrypt = PKCS1_v1_5.new(PRI_KEY).decrypt
4     # 解密超长字符128一解密
5     content = b''.join(decrypt(x, object()) for x in chunks(raw, 128))
6     return content.decode()

 

 

加签代码:

1 def signer(data):
2     signstr = data.encode('utf-8')
3     sign = SIGN_PKCS.new(PRI_KEY).sign(SHA.new(signstr))
4     return base64.b64encode(sign)

解签代码:

1 def verify_sign(unsign, raw_sign):
2     """
3      unsign: 签名
4      raw_sign: 待验证签名
5     """
6     assert SIGN_PKCS.new(PUB_KEY).verify(SHA.new(unsign.encode('utf-8')), raw_sign)

如果您有什么想法,欢迎评论留言哦

posted @ 2018-12-12 11:20  24小时编程自习室  阅读(837)  评论(1)    收藏  举报