发送带证书的request请求

python3 的requests请求支持携带的证书种类是pem,如果拥有的证书不是pem,需要先转为pem

# 以下代码实现了p12证书转pem证书,发送带证书的request请求。
import requests, OpenSSL
 
def p12_to_pem(certname, pwd):
    pem_name = certname + ".pem"
    f_pem = open(pem_name, 'wb')
    p12file = certname + ".p12"
    p12 = OpenSSL.crypto.load_pkcs12(open(p12file, 'rb').read(), pwd)
    f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
    f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
    ca = p12.get_ca_certificates()
    if ca is not None:
        for cert in ca:
            f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
    f_pem.close()
    return pem_name
 
def post_cert_request(url,data,header,certname,pwd):
    if(certname!=""):
        cert = p12_to_pem(certname,pwd)
    else:
        cert = None
    r = requests.post(url, data=data, headers=header, cert=cert)
    print(r.content)
 
if __name__=="__main__":
    post_cert_request("url","data","header","certname","pwd")

你可能感兴趣的:(发送带证书的request请求)