温馨提示×

linux openssl为何报证书错误

小樊
42
2026-09-04 16:34:38
栏目: 云计算

在 Linux 下使用 OpenSSL(或依赖 OpenSSL 的程序,如 curl、wget、git、Python requests 等) 报“证书错误”,通常不是 OpenSSL 本身有问题,而是证书校验失败。常见原因和对应解释如下:


一、最常见原因

1. 系统缺少 CA 证书(或路径不对)

OpenSSL 默认依赖系统的 CA 证书包(如 /etc/ssl/certs/ca-certificates.crt)。

表现

verify error:num=20:unable to get local issuer certificate

原因

  • 没装 ca-certificates
  • 证书目录为空
  • 程序没指向正确的证书文件

解决

# Debian / Ubuntu
sudo apt update
sudo apt install ca-certificates
sudo update-ca-certificates

# CentOS / RHEL
sudo yum install ca-certificates
sudo update-ca-trust

2. 证书已过期

表现

verify error:num=10:certificate has expired

原因

  • 服务器证书过期
  • 中间证书过期
  • 系统时间错误(非常常见)

检查

date

如果时间不对:

sudo ntpdate pool.ntp.org
# 或
timedatectl set-ntp true

3. 自签名证书 / 私有 CA

表现

self signed certificate
unable to verify the first certificate

原因

  • 服务器用的是自签证书
  • 公司内网证书未被信任

解决方式(任选)

  • 把证书加入系统信任
  • 或临时跳过校验(不推荐生产环境)

临时测试:

curl -k https://example.com
openssl s_client -connect example.com:443 -no_verify

4. 证书链不完整

表现

unable to verify the first certificate

原因

  • 服务器只发了域名证书,没发中间证书

验证

openssl s_client -connect example.com:443

如果 Verify return code: 21unable to verify,通常是链不完整。


5. 域名与证书不匹配

表现

hostname mismatch

原因

  • 访问 IP 而非域名
  • 证书只签了 www.example.com,你访问 example.com

6. OpenSSL 版本太旧

旧版本不支持:

  • 新 TLS 协议
  • 新签名算法(如 SHA-256 以上)
  • 新根证书
openssl version

7. 程序没使用系统证书

例如:

  • Python 用 certifi
  • Java 用自己的 truststore
  • 容器里没挂载 CA

二、快速排查命令

# 查看证书详情
openssl s_client -connect example.com:443

# 查看返回码
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -dates -subject

# 测试 HTTPS
curl -v https://example.com

三、如果你愿意

你可以把具体的报错信息(完整几行)贴出来,我可以帮你精准判断是哪一种原因,并给出对应修复命令。

0