Python3: 发送带证书的http/https request请求


免责声明 本站所提供的部分内容,为作者提供、网友推荐、互联网整理而来,仅供学习参考,如有侵犯您的版权,请联系我们,本站将在三个工作日内删除。

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

:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.

以下代码实现了p12证书转pem证书,发送带证书的http/https 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")