Python certifi:如何在Python中使用SSL证书

5,779 阅读3分钟

Python certifi Example | How to Use SSL Certificate in Python

certifi软件包在Python中提供了Mozilla的CA绑定。

Python certifi

Python certifi提供了Mozilla精心策划的根证书集合,用于验证SSL证书的可信度,同时验证TLS主机的身份。它是从requests 项目中摘取的。Python requests库默认使用它自己的CA文件,如果安装了certifi包的证书包,则会使用它。

安装Python certifi

要安装 python certifi 包,你必须输入以下命令。

python3 -m pip install certifi

# OR

pip install certifi

如果你已经安装了request库,有100%的机会certifi库也被安装了,但你必须检查一下。所以,如果你打了下面的命令,它要么会告诉我们已经满足了要求,要么会在你的机器上安装。

虽然有可能将你自己的CA捆绑包传递给Requests以覆盖默认的CA,但有几个第三方软件包在引擎下使用Requests,你没有办法告诉他们使用自定义的位置进行验证

如何在 Windows 上安装 Python certifi

要在Microsoft Windows安装 certifi Python

  1. 在搜索栏中输入cmd并点击Enter打开命令行。
  2. 在命令行中输入python3 -m pip install certifi并再次点击Enter。这将为你的默认Python安装程序安装certifi。
  3. 如果你的电脑上同时有Python 2和3版本,前面的命令可能不起作用。在这种情况下,试试pip3 install certifi 命令。现在它已经安装在你的系统中了。

如何在Linux上安装Python certifi

要在Linux安装 certifi Python

  1. 在你的Linux操作系统中打开终端或外壳。
  2. 输入python3 -m pip install certifi,然后点击 Enter。
  3. 如果不成功,尝试使用这个命令:pip3 install certifipython -m pip install certifi

Python certifi.where()

**certifi.where()**函数帮助我们找到Python中已安装的证书授权(CA)捆绑包的引用。

import certifi

print(certifi.where())

输出

/Users/krunal/Library/Python/3.8/lib/python/site-packages/certifi/cacert.pem

你也可以使用以下命令从命令行中找到cacert.pem路径。

 python -m certifi
/Users/krunal/Library/Python/3.8/lib/python/site-packages/certifi/cacert.pem

浏览器和证书颁发机构已经敲定,1024 位密钥对于证书,特别是根证书来说是不可接受的弱点。

出于同样的原因,Mozilla已经从其捆绑的证书中删除了任何弱(即1024位密钥)的证书,取而代之的是来自同一CA的同等强大(即2048位或更高密钥)证书。

注意:Certifi不支持对CA信任存储内容的任何添加/删除或其他修改。

如果你把额外的证书放在PEM捆绑文件中,你可以使用这两个环境变量来覆盖Python OpenSSL和Requests使用的默认的cert存储。

SSL_CERT_FILE=/System/Library/OpenSSL/cert.pem
REQUESTS_CA_BUNDLE=/System/Library/OpenSSL/cert.pem

然而,我们可以在脚本启动时快速检查,并在必要时用指定的 CA 自动更新 CA 捆绑文件。

首先,捕获你的自定义 CA 并将其保存为 PEM;你可以使用 OpenSSL 转换它。

如果你只有一个.cer、.crt、或.derenSSL。

openssl x509 -inform der -in certificate.cer -out certificate.pem

如果你有多个自定义的中间人或根,你可以在完成全部转换后把它们都加入到单一的.pem文件中。

certificate.pem拖到你项目的根目录中。

现在,我们要尝试请求目标URL。 在我们的例子中,它是一个Github的API,如果我们遇到证书错误,就更新Certifi使用的CA捆绑。

import certifi
import requests

try:
    print('Checking connection to Github...')
    test = requests.get('https://api.github.com')
    print('Connection to Github OK.')
except requests.exceptions.SSLError as err:
    print('SSL Error. Adding custom certs to Certifi store...')
    cafile = certifi.where()
    with open('certicate.pem', 'rb') as infile:
        customca = infile.read()
    with open(cafile, 'ab') as outfile:
        outfile.write(customca)
    print('That might have worked.')

输出

Checking connection to Github...
Connection to Github OK.

已解决:ModuleNotFoundError:没有名为 "certifi "的模块

**ModuleNotFoundError:没有名为 "certifi "**的模块是在certifi模块没有正确安装或者你忘记在Python中安装certifi包时产生的。

解决 ModuleNotFoundError:在Python中没有名为 "certifi "的模块的错误,首先在操作系统的shell或终端使用 "python3 -m pip install certifi "或 "pip install certifi "安装certifi库。

这就是Python certifi例子的内容了。