网上没看到有python写的算支付宝公钥证书与根证书序列号得,只有java与php,我python怎么能没有呢 整上!
安装pyOpenSSL
pip install pyOpenSSL
# coding=utf-8
# author wangdada
import OpenSSL
import hashlib
import redef md5(string):return hashlib.md5(string.encode('utf-8')).hexdigest()# 应用公钥证书序列号
def get_app_cert_cn(cert_str=None):cert_str = cert_str or open("appCertPublicKey_2021001117612947.crt").read()cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_str)try:res = cert.get_signature_algorithm()# 根据其他语言算法 应该剔除不是sha加密的部分python2 可以用r'sha.+WithRSAEncryption' 但是python3必须是b'sha.+WithRSAEncryption'if not re.match(b'sha.+WithRSAEncryption', res):return Noneexcept:return Nonecert_issue = cert.get_issuer()op = ''b = list(cert_issue.get_components())# 证书签发机构排序方式应该是倒序的for i in range(len(b)):a = list(b[len(b) - 1 - i])# 在Python3中直接读取的a[0]为bytes,会影响加密结果,进行decode,兼容python2opp = "{}={}".format(a[0].decode(), a[1].decode())op = op + opp + ','return md5(op[:-1] + str(cert.get_serial_number()))# 根证书序列号
def get_root_cn_sn():root_cert = open("alipayRootCert.crt").read()cert_list = root_cert.split('-----BEGIN CERTIFICATE-----')root_cert_sn = ''for i in cert_list:# print i, len(i)if not len(i):continuecert_sn = get_app_cert_cn('-----BEGIN CERTIFICATE-----'+i)if cert_sn is not None:root_cert_sn = root_cert_sn + cert_sn + '_'return root_cert_sn[:-1]if __name__ == "__main__":print "根证书sn:", get_root_cn_sn()print "应用证书sn:", get_app_cert_cn()
运行环境python2.7, python3修改一下打印方式就行