Created
May 14, 2022 13:47
-
-
Save Forgo7ten/6ce752442fa80c82141197afdad05b1c to your computer and use it in GitHub Desktop.
python requests发送网络请求携带证书(服务端证书校验)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
# 将p12转换为pem,导入OpenSSL包,单使用pem不用该模块 | |
import OpenSSL | |
# pip install requests pyOpenSSL==22.0.0 | |
url = "https://180.76.60.244:18443/api/app5" | |
body = {"page": 2} | |
header = { | |
"Content-Type": | |
"application/x-www-form-urlencoded", | |
"Content-Length": | |
"57", | |
"User-Agent": | |
"Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; Pixel Build/OPM1.171019.011) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30" | |
} | |
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 | |
# 携带p12证书发送请求,本质上也是将p12证书转换为pem证书 | |
# 传入url,数据,头部,证书名,证书密码 | |
def with_p12(url, data, header, certname, pwd): | |
if (certname != ""): | |
cert = p12_to_pem(certname, pwd) | |
else: | |
cert = None | |
requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数 | |
s = requests.session() | |
s.keep_alive = False # 关闭多余连接 | |
r = s.post(url, data=body, headers=header, cert=cert, verify=False) | |
print("with p12:\n", r.text) | |
# 携带pem证书发送请求 | |
def with_pem(): | |
r = requests.post(url, data=body, cert="./client.pem", verify=False) | |
print("with pem:\n", r.text) | |
if __name__ == "__main__": | |
# 忽略警告 | |
requests.packages.urllib3.disable_warnings() | |
# 使用p12证书 | |
with_p12(url, body, header, "yrx", "r0ysue") | |
# 使用pem证书 | |
with_pem() | |
### | |
""" | |
PEM证书格式 | |
-----BEGIN PRIVATE KEY----- | |
... | |
-----END PRIVATE KEY----- | |
-----BEGIN CERTIFICATE----- | |
... | |
-----END CERTIFICATE----- | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment