python受信任根证书列表篇——多个根证书生成受信任根证书列表,request加载受信任列表正常访问

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值