peakchao

搜索

peakchao

peakchao

前端开发工程师 | Go 爱好者

联系方式

HTTPS 完全指南:原理、证书与实践

peakchao 2025-12-13 05:20 11 次浏览 0 条评论

HTTPS 的由来

互联网安全的演进

在互联网发展初期,HTTP(超文本传输协议)被设计用于在 Web 浏览器和服务器之间传输数据。然而,HTTP 协议在设计时并没有考虑安全性,所有数据都以明文形式传输。

┌─────────────────────────────────────────────────────────────┐
│                    HTTP 传输示意图                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   [用户浏览器]  ──── 明文数据 ────►  [Web 服务器]          │
│        │                                    │               │
│        │         GET /login                 │               │
│        │         username=admin             │               │
│        │         password=123456            │               │
│        │                                    │               │
│        └──────── 🔓 可被窃听 ────────────────┘               │
│                                                             │
│   ⚠️  中间人可以轻易截获敏感信息!                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

HTTPS 的诞生

1994 年,网景公司(Netscape)开发了 SSL(Secure Sockets Layer,安全套接层) 协议,用于在 HTTP 协议之上提供加密通信。这就是 HTTPS(HTTP Secure)的起源。

HTTPS 发展时间线:

年份事件
1994Netscape 发布 SSL 1.0(内部使用,未公开)
1995SSL 2.0 发布(存在安全漏洞)
1996SSL 3.0 发布
1999TLS 1.0 发布(基于 SSL 3.0)
2006TLS 1.1 发布
2008TLS 1.2 发布(目前广泛使用)
2018TLS 1.3 发布(当前最新版本)

注意:虽然我们常说“SSL 证书“,但现代系统实际使用的是 TLS 协议。SSL 已被弃用,但“SSL“这个名称仍然被广泛使用。


HTTPS 解决了什么问题

HTTPS 主要解决了三个核心安全问题:

1. 数据窃听(Eavesdropping)

问题:HTTP 以明文传输数据,任何位于用户和服务器之间的人都可以读取传输的内容。

┌────────────────────────────────────────────────────────────┐
│                     数据窃听攻击                           │
├────────────────────────────────────────────────────────────┤
│                                                            │
│   [用户] ──── "密码是123456" ────► [服务器]               │
│              │                                             │
│              ▼                                             │
│         [黑客窃听]                                         │
│         "哈哈,密码是123456!"                             │
│                                                            │
└────────────────────────────────────────────────────────────┘

HTTPS 解决方案:使用对称加密算法(如 AES)加密所有传输数据,即使被截获也无法解读。

┌────────────────────────────────────────────────────────────┐
│                   HTTPS 加密保护                           │
├────────────────────────────────────────────────────────────┤
│                                                            │
│   [用户] ──── "X#$@!&*^%$#" ────► [服务器]                │
│              │                                             │
│              ▼                                             │
│         [黑客窃听]                                         │
│         "???看不懂..."                                  │
│                                                            │
└────────────────────────────────────────────────────────────┘

2. 数据篡改(Tampering)

问题:攻击者可以在传输过程中修改数据内容。

示例场景

  • 用户访问银行网站,转账 100 元
  • 中间人将金额修改为 10000 元
  • 服务器收到篡改后的请求

HTTPS 解决方案:使用消息认证码(MAC)确保数据完整性,任何篡改都会被检测到。

3. 身份伪造(Impersonation)

问题:用户无法确认他们访问的网站是否真的是目标网站,可能访问到钓鱼网站。

┌────────────────────────────────────────────────────────────┐
│                     中间人攻击                             │
├────────────────────────────────────────────────────────────┤
│                                                            │
│   [用户] ──────────────────────► [假银行网站]             │
│        "我要登录银行"                   │                  │
│                                         │                  │
│                                         ▼                  │
│                                 [黑客获取密码]             │
│                                         │                  │
│                                         ▼                  │
│                                    [真银行网站]            │
│                                                            │
└────────────────────────────────────────────────────────────┘

HTTPS 解决方案:使用数字证书验证服务器身份,确保用户连接到正确的网站。

HTTPS 的三大安全保障

安全特性说明实现技术
机密性数据加密,防止窃听对称加密(AES、ChaCha20)
完整性数据防篡改消息认证码(HMAC)
身份认证验证服务器真实身份数字证书、CA 体系

HTTPS 的工作原理

TLS 握手过程

HTTPS 连接建立的核心是 TLS 握手,这是一个在客户端和服务器之间协商加密参数的过程。

TLS 1.2 握手流程

┌─────────────────────────────────────────────────────────────────────┐
│                        TLS 1.2 握手过程                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   客户端 (浏览器)                           服务器                  │
│       │                                        │                    │
│       │ ──── 1. ClientHello ─────────────────► │                    │
│       │      (支持的加密套件、随机数)          │                    │
│       │                                        │                    │
│       │ ◄─── 2. ServerHello ───────────────── │                    │
│       │      (选择的加密套件、随机数)          │                    │
│       │                                        │                    │
│       │ ◄─── 3. Certificate ───────────────── │                    │
│       │      (服务器证书)                      │                    │
│       │                                        │                    │
│       │ ◄─── 4. ServerKeyExchange ─────────── │                    │
│       │      (密钥交换参数)                    │                    │
│       │                                        │                    │
│       │ ◄─── 5. ServerHelloDone ───────────── │                    │
│       │                                        │                    │
│       │ ──── 6. ClientKeyExchange ──────────► │                    │
│       │      (预主密钥)                        │                    │
│       │                                        │                    │
│       │ ──── 7. ChangeCipherSpec ───────────► │                    │
│       │                                        │                    │
│       │ ──── 8. Finished ───────────────────► │                    │
│       │                                        │                    │
│       │ ◄─── 9. ChangeCipherSpec ──────────── │                    │
│       │                                        │                    │
│       │ ◄─── 10. Finished ─────────────────── │                    │
│       │                                        │                    │
│       │ ════════ 加密通信开始 ════════════════ │                    │
│       │                                        │                    │
└─────────────────────────────────────────────────────────────────────┘

TLS 1.3 握手流程(简化)

TLS 1.3 将握手往返次数从 2-RTT 减少到 1-RTT,显著提升了性能:

┌─────────────────────────────────────────────────────────────────────┐
│                        TLS 1.3 握手过程                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   客户端                                       服务器               │
│       │                                           │                 │
│       │ ──── ClientHello + KeyShare ────────────► │                 │
│       │                                           │                 │
│       │ ◄─── ServerHello + KeyShare ───────────── │                 │
│       │ ◄─── EncryptedExtensions ──────────────── │                 │
│       │ ◄─── Certificate ──────────────────────── │                 │
│       │ ◄─── CertificateVerify ────────────────── │                 │
│       │ ◄─── Finished ─────────────────────────── │                 │
│       │                                           │                 │
│       │ ──── Finished ──────────────────────────► │                 │
│       │                                           │                 │
│       │ ═══════════ 加密通信开始 ═════════════════ │                 │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

密钥交换原理

HTTPS 使用非对称加密来安全地交换对称加密密钥

  1. 非对称加密(RSA、ECDHE):用于密钥交换,安全但慢
  2. 对称加密(AES、ChaCha20):用于数据传输,快速高效
┌────────────────────────────────────────────────────────────────┐
│                       混合加密机制                             │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│   1. 密钥交换阶段(非对称加密)                                │
│   ┌─────────────────────────────────────────────────────┐     │
│   │  客户端生成随机数 → 用服务器公钥加密 → 发送给服务器  │     │
│   │  服务器用私钥解密 → 双方计算出相同的会话密钥        │     │
│   └─────────────────────────────────────────────────────┘     │
│                                                                │
│   2. 数据传输阶段(对称加密)                                  │
│   ┌─────────────────────────────────────────────────────┐     │
│   │  双方使用会话密钥进行 AES 加密通信                   │     │
│   │  速度快,适合大量数据传输                           │     │
│   └─────────────────────────────────────────────────────┘     │
│                                                                │
└────────────────────────────────────────────────────────────────┘

证书验证过程

浏览器如何验证服务器证书的有效性:

┌────────────────────────────────────────────────────────────────┐
│                     证书验证流程                               │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│   1. 检查证书是否在有效期内                                    │
│      └─► 检查 Not Before 和 Not After 时间                    │
│                                                                │
│   2. 检查证书域名是否匹配                                      │
│      └─► Common Name (CN) 或 Subject Alternative Name (SAN)   │
│                                                                │
│   3. 验证证书链                                                │
│      └─► 服务器证书 → 中间证书 → 根证书(预装在系统中)        │
│                                                                │
│   4. 验证数字签名                                              │
│      └─► 使用上级证书的公钥验证签名                           │
│                                                                │
│   5. 检查证书吊销状态                                          │
│      └─► OCSP 或 CRL 检查                                     │
│                                                                │
│   ✅ 全部通过 → 显示安全锁标志                                 │
│   ❌ 任一失败 → 显示安全警告                                   │
│                                                                │
└────────────────────────────────────────────────────────────────┘

SSL/TLS 证书详解

证书类型

按验证级别分类

类型全称验证内容适用场景颁发时间
DVDomain Validation仅验证域名所有权个人网站、博客分钟级
OVOrganization Validation验证域名 + 组织信息企业网站1-3 天
EVExtended Validation严格验证组织身份银行、电商1-2 周

按域名数量分类

类型说明示例
单域名证书仅保护一个域名www.example.com
多域名证书 (SAN)保护多个不同域名example.com, example.org
通配符证书保护一个域名及其所有子域名*.example.com

证书文件格式

格式扩展名说明
PEM.pem, .crt, .cerBase64 编码,最常用
DER.der, .cer二进制格式
PKCS#12.p12, .pfx包含证书和私钥
PKCS#7.p7b, .p7c证书链格式

证书内容解读

# 查看证书内容
openssl x509 -in certificate.crt -text -noout

输出示例:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 04:00:00:00:00:01:15:4b:5a:c3:94
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=BE, O=GlobalSign nv-sa, CN=GlobalSign RSA OV SSL CA 2018
        Validity
            Not Before: Jan  1 00:00:00 2024 GMT
            Not After : Jan  1 00:00:00 2025 GMT
        Subject: C=CN, ST=Beijing, L=Beijing, O=Example Inc, CN=www.example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public-Key: (2048 bit)
        X509v3 extensions:
            X509v3 Subject Alternative Name:
                DNS:www.example.com, DNS:example.com
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment

自签名证书的创建

自签名证书适用于:

  • 本地开发和测试环境
  • 内部服务之间的通信
  • 学习和实验目的

⚠️ 注意:自签名证书不受浏览器信任,会显示安全警告。生产环境请使用 CA 签发的证书。

方法一:使用 OpenSSL 一行命令

# 生成自签名证书和私钥(有效期 365 天)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout server.key \
  -out server.crt \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCompany/CN=localhost"

参数说明:

参数说明
req证书请求和生成工具
-x509输出自签名证书而非 CSR
-nodes私钥不加密(No DES)
-days 365证书有效期
-newkey rsa:2048生成 2048 位 RSA 密钥
-keyout私钥输出文件
-out证书输出文件
-subj证书主题信息

方法二:分步创建(推荐)

步骤 1:生成私钥

# 生成 RSA 私钥
openssl genrsa -out server.key 2048

# 或生成 ECC 私钥(更安全、更快)
openssl ecparam -genkey -name prime256v1 -out server.key

步骤 2:创建证书签名请求(CSR)

openssl req -new -key server.key -out server.csr \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCompany/OU=IT/CN=localhost"

CSR 字段说明:

字段含义示例
C国家代码CN
ST省份/州Beijing
L城市Beijing
O组织名称MyCompany
OU部门名称IT
CN通用名称(域名)localhost

步骤 3:生成自签名证书

openssl x509 -req -days 365 \
  -in server.csr \
  -signkey server.key \
  -out server.crt

方法三:创建带 SAN 的证书(支持多域名/IP)

创建配置文件 san.cnf

[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
req_extensions = req_ext

[dn]
C = CN
ST = Beijing
L = Beijing
O = MyCompany
OU = IT
CN = localhost

[req_ext]
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = *.localhost
DNS.3 = myapp.local
IP.1 = 127.0.0.1
IP.2 = 192.168.1.100

生成证书:

# 生成私钥和证书
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout server.key \
  -out server.crt \
  -config san.cnf \
  -extensions req_ext

方法四:创建本地 CA 并签发证书

适用于需要在多个服务间建立信任的场景。

步骤 1:创建根 CA

# 创建 CA 目录结构
mkdir -p ca/{certs,crl,newcerts,private}
touch ca/index.txt
echo 1000 > ca/serial

# 生成 CA 私钥
openssl genrsa -aes256 -out ca/private/ca.key 4096

# 生成 CA 证书
openssl req -new -x509 -days 3650 -key ca/private/ca.key \
  -out ca/certs/ca.crt \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCA/CN=My Root CA"

步骤 2:使用 CA 签发服务器证书

# 生成服务器私钥
openssl genrsa -out server.key 2048

# 生成 CSR
openssl req -new -key server.key -out server.csr \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCompany/CN=myserver.local"

# 使用 CA 签发证书
openssl x509 -req -days 365 \
  -in server.csr \
  -CA ca/certs/ca.crt \
  -CAkey ca/private/ca.key \
  -CAcreateserial \
  -out server.crt

步骤 3:信任 CA 证书

macOS:

sudo security add-trusted-cert -d -r trustRoot \
  -k /Library/Keychains/System.keychain ca/certs/ca.crt

Ubuntu/Debian:

sudo cp ca/certs/ca.crt /usr/local/share/ca-certificates/
sudo update-ca-certificates

CentOS/RHEL:

sudo cp ca/certs/ca.crt /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust

使用 mkcert 快速创建本地开发证书

mkcert 是一个简化本地 HTTPS 开发的工具。

# macOS 安装
brew install mkcert

# Ubuntu
sudo apt install libnss3-tools
wget https://github.com/FiloSottile/mkcert/releases/download/v1.4.4/mkcert-v1.4.4-linux-amd64
chmod +x mkcert-v1.4.4-linux-amd64
sudo mv mkcert-v1.4.4-linux-amd64 /usr/local/bin/mkcert

# 安装本地 CA
mkcert -install

# 生成证书
mkcert localhost 127.0.0.1 ::1 myapp.local

# 输出:
# Created a new certificate valid for the following names:
#  - "localhost"
#  - "127.0.0.1"
#  - "::1"
#  - "myapp.local"
# The certificate is at "./localhost+3.pem" and the key at "./localhost+3-key.pem"

免费 SSL 证书申请工具

Let’s Encrypt 介绍

Let’s Encrypt 是一个免费、自动化、开放的证书颁发机构(CA),由互联网安全研究组(ISRG)运营。

特点:

  • ✅ 完全免费
  • ✅ 自动化申请和续期
  • ✅ 被所有主流浏览器信任
  • ✅ 支持通配符证书
  • ⚠️ 证书有效期 90 天(需定期续期)

acme.sh(推荐)

acme.sh 是一个纯 Shell 脚本实现的 ACME 客户端,支持多种 CA 和 DNS 服务商。

安装 acme.sh

# 方式一:在线安装
curl https://get.acme.sh | sh -s email=your@email.com

# 方式二:从 GitHub 安装
git clone https://github.com/acmesh-official/acme.sh.git
cd acme.sh
./acme.sh --install -m your@email.com

# 安装后重新加载 shell
source ~/.bashrc

HTTP 验证方式(Webroot 模式)

适用于已有 Web 服务器运行的情况:

# 申请证书(指定网站根目录)
acme.sh --issue -d example.com -d www.example.com -w /var/www/html

# 参数说明:
# --issue      申请证书
# -d           域名(可指定多个)
# -w           Web 根目录(用于放置验证文件)

Standalone 模式

acme.sh 自己启动临时 HTTP 服务器进行验证:

# 需要先停止占用 80 端口的服务
acme.sh --issue -d example.com --standalone

# 使用其他端口
acme.sh --issue -d example.com --standalone --httpport 8888

DNS 验证方式(推荐)

适用于申请通配符证书或服务器无法访问的情况。

手动 DNS 验证:

# 申请证书(手动添加 DNS TXT 记录)
acme.sh --issue -d example.com -d '*.example.com' --dns --yes-I-know-dns-manual-mode-enough-go-ahead-please

# 脚本会输出需要添加的 DNS 记录
# 添加记录后,运行续期命令
acme.sh --renew -d example.com --yes-I-know-dns-manual-mode-enough-go-ahead-please

自动 DNS 验证(API 方式):

以阿里云 DNS 为例:

# 设置 API 密钥(会自动保存)
export Ali_Key="your_access_key_id"
export Ali_Secret="your_access_key_secret"

# 申请证书
acme.sh --issue -d example.com -d '*.example.com' --dns dns_ali

支持的 DNS 服务商(部分):

DNS 服务商参数
阿里云 DNSdns_ali
腾讯云 DNSdns_dp
Cloudflaredns_cf
GoDaddydns_gd
AWS Route53dns_aws
Google Cloud DNSdns_gcloud
Namesilodns_namesilo

完整列表参见:DNS API 支持列表

安装证书到指定位置

# 安装证书
acme.sh --install-cert -d example.com \
  --key-file /etc/nginx/ssl/example.com.key \
  --fullchain-file /etc/nginx/ssl/example.com.crt \
  --reloadcmd "systemctl reload nginx"

# 参数说明:
# --key-file        私钥保存路径
# --fullchain-file  证书链保存路径
# --reloadcmd       证书更新后执行的命令

证书续期

acme.sh 会自动设置 cron 任务进行续期,也可以手动续期:

# 手动续期单个证书
acme.sh --renew -d example.com

# 强制续期
acme.sh --renew -d example.com --force

# 续期所有证书
acme.sh --renew-all

其他常用命令

# 查看已申请的证书
acme.sh --list

# 查看证书信息
acme.sh --info -d example.com

# 撤销证书
acme.sh --revoke -d example.com

# 删除证书
acme.sh --remove -d example.com

# 升级 acme.sh
acme.sh --upgrade

# 开启自动升级
acme.sh --upgrade --auto-upgrade

Certbot

Certbot 是 EFF(电子前沿基金会)开发的官方 Let’s Encrypt 客户端。

安装 Certbot

# Ubuntu
sudo apt update
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx

# macOS
brew install certbot

申请证书(Nginx)

# 自动配置 Nginx
sudo certbot --nginx -d example.com -d www.example.com

# 仅获取证书,不修改配置
sudo certbot certonly --nginx -d example.com -d www.example.com

申请证书(Apache)

sudo certbot --apache -d example.com -d www.example.com

申请证书(Standalone)

# 需要停止占用 80/443 端口的服务
sudo certbot certonly --standalone -d example.com

申请通配符证书

# 需要 DNS 验证
sudo certbot certonly --manual --preferred-challenges dns \
  -d example.com -d '*.example.com'

证书续期

# 测试续期
sudo certbot renew --dry-run

# 实际续期
sudo certbot renew

Certbot 会自动创建 cron 任务或 systemd timer 进行定期续期。

其他免费 SSL 工具

1. Caddy Server

Caddy 是一个现代化的 Web 服务器,内置自动 HTTPS 功能:

# Caddyfile
example.com {
    root * /var/www/html
    file_server
}

启动后自动申请和配置 SSL 证书。

2. Traefik

Traefik 是一个云原生的反向代理,支持自动 HTTPS:

# traefik.yml
entryPoints:
  web:
    address: ":80"
  websecure:
    address: ":443"

certificatesResolvers:
  letsencrypt:
    acme:
      email: your@email.com
      storage: /etc/traefik/acme.json
      httpChallenge:
        entryPoint: web

3. ZeroSSL

ZeroSSL 提供免费的 SSL 证书,支持 Web 界面申请:

  • 免费额度:3 个 90 天证书
  • 支持 REST API
  • 可与 acme.sh 配合使用
# 使用 acme.sh 从 ZeroSSL 申请证书
acme.sh --set-default-ca --server zerossl
acme.sh --issue -d example.com --dns dns_ali

4. SSL For Free

SSL For Free 提供 Web 界面的免费证书申请服务。

各工具对比

特性acme.shCertbotCaddy
语言ShellPythonGo
安装简单需包管理器二进制文件
依赖Python 环境
通配符支持
DNS API100+有限N/A
自动续期
跨平台
Docker 支持

Nginx 配置 HTTPS

基本 HTTPS 配置

server {
    listen 80;
    server_name example.com www.example.com;
    
    # HTTP 重定向到 HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    # SSL 证书配置
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # SSL 配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # SSL 会话缓存
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    # 网站根目录
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

高级安全配置

server {
    listen 443 ssl http2;
    server_name example.com;

    # 证书
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # 使用更安全的 DH 参数
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;

    # 协议和加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/nginx/ssl/chain.pem;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # 安全 Headers
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # 其他配置...
}

生成 DH 参数:

openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048

验证配置

# 检查 Nginx 配置语法
sudo nginx -t

# 重载 Nginx 配置
sudo systemctl reload nginx

# 使用 SSL Labs 测试
# https://www.ssllabs.com/ssltest/

常见问题与排查

证书相关问题

1. 证书过期

# 检查证书过期时间
openssl x509 -in certificate.crt -noout -dates

# 输出示例:
# notBefore=Jan  1 00:00:00 2024 GMT
# notAfter=Apr  1 00:00:00 2024 GMT

2. 证书链不完整

# 检查证书链
openssl s_client -connect example.com:443 -showcerts

# 验证证书链
openssl verify -CAfile chain.pem certificate.crt

3. 域名不匹配

# 查看证书包含的域名
openssl x509 -in certificate.crt -noout -text | grep -A1 "Subject Alternative Name"

连接问题排查

# 测试 HTTPS 连接
curl -vI https://example.com

# 测试特定 TLS 版本
openssl s_client -connect example.com:443 -tls1_2
openssl s_client -connect example.com:443 -tls1_3

# 检查端口是否开放
nc -zv example.com 443

# 查看完整握手过程
openssl s_client -connect example.com:443 -debug

常见错误及解决方案

错误可能原因解决方案
ERR_CERT_DATE_INVALID证书过期续期证书
ERR_CERT_COMMON_NAME_INVALID域名不匹配检查证书 SAN
ERR_CERT_AUTHORITY_INVALID自签名或不受信任的 CA使用受信任的 CA
ERR_SSL_VERSION_OR_CIPHER_MISMATCHTLS 版本或加密套件不兼容更新服务器配置
SSL_HANDSHAKE_FAILURE握手失败检查证书和私钥匹配

最佳实践

1. 证书管理

  • ✅ 使用自动续期工具(acme.sh、Certbot)
  • ✅ 设置证书过期提醒
  • ✅ 使用证书链而非单个证书
  • ✅ 安全存储私钥(权限 600)
  • ❌ 不要在代码仓库中提交私钥

2. 安全配置

  • ✅ 仅启用 TLS 1.2 和 TLS 1.3
  • ✅ 禁用不安全的加密套件
  • ✅ 启用 HSTS(HTTP Strict Transport Security)
  • ✅ 使用 OCSP Stapling
  • ✅ 定期更新服务器软件
# 禁用 SSL 3.0、TLS 1.0、TLS 1.1
ssl_protocols TLSv1.2 TLSv1.3;

# HSTS
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

3. 性能优化

  • ✅ 启用 HTTP/2
  • ✅ 使用 ECDSA 证书(比 RSA 更快)
  • ✅ 配置 SSL 会话缓存
  • ✅ 使用 TLS 1.3(0-RTT)
# 启用 HTTP/2
listen 443 ssl http2;

# 会话缓存
ssl_session_cache shared:SSL:50m;
ssl_session_timeout 1d;

4. 监控和测试

  • ✅ 使用 SSL Labs 测试配置
  • ✅ 定期扫描证书漏洞
  • ✅ 监控证书过期时间
  • ✅ 测试不同客户端的兼容性

参考资料

官方文档

学习资源

检测工具

相关规范


本文更新日期:2024年12月

如果这篇文章对你有帮助,欢迎点赞和分享!有任何问题,欢迎在评论区讨论。

评论 (0)

请先登录后再发表评论

暂无评论,来发表第一条评论吧!