我正在尝试创建与安全主机的HTTPS连接,即使我有PEM证书(我已经从JKS keystore文件导入了它),我仍然收到此错误。
[SSL:TLSV13_ALERT_CERTIFICATE_REQUIRED] TLsv13警告证书要求
因此,这是请求:
import requests
r = requests.patch("https://selfsigned_host:8080/myapp/v1/service/id/123", json={'another_field':'987654321'},verify='C:\\my_selfsigned_host.pem')
我已通过使用这个Gist中的解决方案来解决此问题。
import contextlib
import OpenSSL.crypto
import os
import requests
import ssl
import tempfile
import urllib3.contrib.pyopenssl
@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
''' Decrypts the .pfx file to be used with requests. '''
with tempfile.NamedTemporaryFile(suffix='.pem',delete=False) as t_pem:
f_pem = open(t_pem.name, 'wb')
pfx = open(pfx_path, 'rb').read()
p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password)
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()
yield t_pem.name
我可以重复使用我的PFX证书来发起请求:
with pfx_to_pem('C:\\my_cert.pfx', 'my_pass') as cert:
r = requests.patch(url,json=body,cert=cert, verify=False, headers=headers)
这个解决方案完美地实现了我的期望,但是否有人想要改进它呢?