使用 Certbot 和 DNS-01 挑战获取 SSL 证书

2025-11-03#SSL证书#Certbot

Certbot 是一个免费且开源的工具,用于自动申请和使用 Let's Encrypt 证书。它支持多种验证方法,其中 DNS-01 挑战允许用户通过在域名的 DNS 记录中添加特定的 TXT 记录来证明对域名的控制权。这种方法特别适用于需要为通配符域名(如 *.example.com)获取证书的场景;也适用于哪些无法启用 HTTP 验证的环境。

安装 🔗

certbot 是用 Python 编写的工具。如果机器上已经有 Python 环境。那么可在创建虚拟环境后,使用 pip 安装:

pip install certbot

当然,也可使用 uv 等现代工具安装。

获取证书 🔗

使用 DNS-01 挑战获取证书时,需要指定 --manual--preferred-challenges dns 参数。例如,获取 example.com*.example.com 的证书:

certbot certonly --manual --preferred-challenges dns -d example.com -d *.example.com

cerbot 程序在运行过程中会提示输入邮箱,但可以跳过。运行完毕后,会显示需要添加到 DNS 记录中的 TXT 记录内容。然后将该记录添加到域名的 DNS 配置中,等待 DNS 记录生效。生效后,按回车继续,Certbot 会验证该记录并颁发证书。

默认情况下,证书会保存在 /etc/letsencrypt/live/example.com/ 目录下。但如果没有管理员权限,那么可以使用 --config-dir--work-dir--logs-dir 参数指定其他目录。例如:

certbot certonly --manual --preferred-challenges dns \
  -d example.com -d *.example.com \
  --config-dir ~/letsencrypt/config \
  --work-dir ~/letsencrypt/work \
  --logs-dir ~/letsencrypt/logs

另外,certbot 支持使用插件自动管理 DNS 记录,从而简化 DNS-01 挑战的过程。

将证书转换成 pfx 格式 🔗

在某些情况下,可能需要将证书转换成 pfx 格式以供 Windows 或其他系统使用。比如当上传自定义证书到 Azure Application Gateway, Azure Key Vaults 时,就必须使用带密码的 pfx 格式。可以使用 OpenSSL 工具进行转换:

openssl pkcs12 -export -out ~/letsencrypt/cert.pfx \
  -inkey ~/letsencrypt/live/example.com/privkey.pem \
  -in ~/letsencrypt/live/example.com/fullchain.pem

运行期间会提示输入导出密码。

其他工具 🔗

除了 Certbot 外,还有其他一些工具也支持通过 DNS-01 挑战获取 SSL 证书。例如:

  • lego:一个用 Go 语言编写的 ACME 客户端,支持多种 DNS 提供商的 API。