import OpenSSL
CERT_BEGIN = b"-----BEGIN CERTIFICATE-----"
CERT_END = b"-----END CERTIFICATE-----"
PEM = OpenSSL.crypto.FILETYPE_PEM
DER = OpenSSL.crypto.FILETYPE_ASN1
def get_file_code_format(file_path):
"""
:param file_path: file path
:type file_path: str
:exception InvalidFileEncodingFormatError: Invalid revocation certificate list file code format
:return: PEM or DER
:rtype: int
"""
with open(file_path, mode='rb') as cert_file:
text = cert_file.read()
if try_to_parse_cert(text, PEM):
return PEM
elif try_to_parse_cert(text, DER):
return DER
else:
raise Exception(f'InvalidFileEncodingFormatError:{file_path}')
def try_to_parse_cert(cert_text: bytes, code=PEM) -> bool:
try:
OpenSSL.crypto.load_certificate(code, cert_text)
return True
except OpenSSL.crypto.Error:
return False
cert_path = r'D://xxxxxx'
ca_path = r'D://xxxxxx'
cert_code = get_file_code_format(cert_path)
with open(cert_path, mode='rb') as cert_file:
cert_text = cert_file.read()
with open(ca_path, mode='ab') as ca_file:
if cert_code == PEM:
ca_file.write(cert_text.decode())
else:
ca_file.write(CERT_BEGIN + b'\n' + base64.b64encode(cert_text) + b'\n' + CERT_END)
python加载多个根证书,需要先将原证书解析,然后转成pem格式,然后写在同一个文件里面,最后将路径传给相应的参数。
der与pem格式转换
der格式文件以字节读取,然后进行64位转码,最后在开头结尾加上-----BEGIN CERTIFICATE-----和-----END CERTIFICATE-----
使用受信任根证书列表验证
ret = requests.get(r"https://xxxxxxx", verify=ca_path)
python内置的受信任根证书列表位置
python38\Lib\site-packages\certifi\cacert.pem