Python Handle Certification Sign/Verify

项目需要对接快钱网关,由于官方的开发中心中只有C#/Java/PHP的Demo,于是只能自己捣鼓一个Python的版本。他们的分账网关是通过证书对传输数据进行加密验证的,因此在代码中需要对证书进行解析,网上搜了一遍把我导向了rsaM2Crypto之类的库,折腾了一天发现根本解决不了问题,最后在ipython里各种Tab各种尝试发现其实通过pyOpenSSL就可以完成对证书的公私钥加密验证操作。

私钥加密
1
2
3
4
5
6
7
import contextlib
import OpenSSL

with contextlib.closing(open('demo.pem')) as f:
private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, f.read())

sign_str = OpenSSL.crypto.sign(private_key, 'Top Level Secrect', 'sha1'))
公钥解密
1
2
3
4
5
6
7
8
9
10
11
import contextlib
import OpenSSL

with contextlib.closing(open('demo.cer')) as f:
certificate = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
public_key = certificate.get_pubkey()

sign_str = 'Signature returned by sign function'
data_str = 'Data to be verified'

OpenSSL.crypto.verify(certificate, sign_str, data_str, 'sha1')

最后放个快钱API接口的Python DEMO