openssl x509 是日常运维中最常用的证书查看工具。本文聚焦于查看和解析证书信息,不涉及证书生成。
基本语法#
1
|
openssl x509 [options] -in <certificate file>
|
常用查看命令#
查看证书完整信息#
1
|
openssl x509 -in cert.pem -text -noout
|
输出包含:版本、序列号、签名算法、颁发者、有效期、主体、公钥、扩展信息。
只查看关键字段#
1
2
3
4
5
6
7
8
9
10
11
|
# 查看主体(Subject)
openssl x509 -in cert.pem -subject -noout
# 查看颁发者(Issuer)
openssl x509 -in cert.pem -issuer -noout
# 查看有效期
openssl x509 -in cert.pem -dates -noout
# 查看序列号
openssl x509 -in cert.pem -serial -noout
|
查看公钥信息#
1
|
openssl x509 -in cert.pem -pubkey -noout
|
查看指纹(Fingerprint)#
1
2
3
4
5
|
# SHA-256 指纹(推荐)
openssl x509 -in cert.pem -fingerprint -sha256 -noout
# SHA-1 指纹(已弃用,仅作兼容)
openssl x509 -in cert.pem -fingerprint -sha1 -noout
|
实际示例#
查看一个真实的系统证书:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
$ openssl x509 -in /etc/ssl/certs/ca-certificates.crt -text -noout | head -25
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 6828503384748696800 (0x5ec3b7a6437fa4e0)
Signature Algorithm: sha1WithRSAEncryption
Issuer: CN = ACCVRAIZ1, OU = PKIACCV, O = ACCV, C = ES
Validity
Not Before: May 5 09:37:37 2011 GMT
Not After : Dec 31 09:37:37 2030 GMT
Subject: CN = ACCVRAIZ1, OU = PKIACCV, O = ACCV, C = ES
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)
|
检查证书是否过期#
1
2
3
4
5
|
# 查看过期时间
openssl x509 -in cert.pem -enddate -noout
# 输出示例
notAfter=Mar 26 12:00:00 2026 GMT
|
结合脚本检查:
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash
# 检查证书是否在 30 天内过期
CERT_FILE="/path/to/cert.pem"
EXPIRE_DATE=$(openssl x509 -in "$CERT_FILE" -enddate -noout | cut -d= -f2)
EXPIRE_EPOCH=$(date -d "$EXPIRE_DATE" +%s)
NOW_EPOCH=$(date +%s)
DAYS_LEFT=$(( (EXPIRE_EPOCH - NOW_EPOCH) / 86400 ))
if [ $DAYS_LEFT -lt 30 ]; then
echo "警告:证书将在 $DAYS_LEFT 天后过期!"
fi
|
查看远程服务器证书#
不需要下载证书文件,直接查看:
1
2
|
# 查看远程 HTTPS 证书
openssl s_client -connect secdoc.jazor.net:443 -servername secdoc.jazor.net 2>/dev/null | openssl x509 -text -noout
|
输出格式转换#
1
2
3
4
5
|
# PEM 转 DER(二进制格式)
openssl x509 -in cert.pem -outform DER -out cert.der
# DER 转 PEM
openssl x509 -in cert.der -inform DER -outform PEM -out cert.pem
|
| 需求 |
命令 |
| 查看完整信息 |
openssl x509 -in cert.pem -text -noout |
| 查看有效期 |
openssl x509 -in cert.pem -dates -noout |
| 查看主体/颁发者 |
openssl x509 -in cert.pem -subject -issuer -noout |
| 查看指纹 |
openssl x509 -in cert.pem -fingerprint -sha256 -noout |
| 查看远程证书 |
openssl s_client -connect host:443 | openssl x509 -text -noout |
参考来源#