HTTPS 协议
剖析 HTTPS 的 TLS/SSL 加密层架构、ClientHello/ServerHello 与密钥派生握手流程、X.509 证书链与 CA 校验机制、生产部署步骤以及与 VPN/SSH 隧道的差异。
学完这一章,你能够
- 剖析 HTTPS 的 TLS/SSL 加密层架构、ClientHello/ServerHello 与密钥派生握手流程、X.509 证书链与 CA 校验机制、生产部署步骤以及与 VPN/SSH 隧道的差异。
HTTPS 架构与 TLS 握手建连流程
HTTPS(HyperText Transfer Protocol Secure,默认 TCP `443` 端口)是 HTTP 的安全扩展,通过在应用层 HTTP 与传输层 TCP 之间嵌入 TLS(及其历史前身 SSL)安全层,对通信全程提供机密性、身份认证与完整性保护,是登录认证、在线支付及敏感 API 交互的行业标配。
HTTPS 会话开始前必须先完成 TLS 握手:首先客户端发送 `ClientHello`,携带随机数、支持的 TLS 版本、密码套件列表与 SNI 域名扩展;服务器回复 `ServerHello` 选定密码套件并发送服务器数字证书;客户端校验该证书的 CA 签名、有效期与绑定域名是否合法;随后双方执行密钥交换(传统 RSA 方式由客户端用服务器公钥加密预主密钥,现代 TLS 1.2/1.3 普遍采用具备前向保密的 ECDHE 临时密钥交换);最后双方利用预主密钥与随机数派生出对称会话密钥,启用加密记录传输。
安全隧道就绪后,客户端与服务器在其上照常交换加密封装的 HTTP 请求与 HTTP 响应,所有请求路径、头部、Cookie 与正文均对链路中间人不可见。
安全特性、证书结构与应用场景
HTTPS 具备四项核心能力:混合加密机制,利用非对称加密/ECDHE 安全协商密钥,再用 AES-GCM 或 ChaCha20-Poly1305 等高速对称算法加密海量 HTTP 数据;基于服务器证书(并可按需启用双向 mTLS 客户端证书)的强身份认证;依托 SHA 系列哈希、HMAC 或 AEAD 认证标签的数据完整性保护;以及与标准 HTTP 请求方法、状态码和头部语义的完全兼容。
凭借防窃听、防服务器伪装与防报文篡改三重防线,HTTPS 已全面覆盖日常网页隐私保护、电子商务在线支付、跨服务 API 通信以及用户登录鉴权等关键业务场景。
HTTPS 的信任根基在于由受信任证书颁发机构(CA)签发的 X.509 服务器证书。证书核心字段包括绑定的域名(CN 与 SAN 扩展)、服务器公钥、生效与过期时间窗以及签发 CA 的数字签名,客户端逐级验签至系统内置根证书后方才信任该站点。
HTTPS 部署流程与加密隧道替代方案
为站点上线 HTTPS 通常遵循三个标准步骤:第一是向权威 CA 申请或通过 ACME 自动化签发有效的服务器证书;第二是在 Web 服务器或反向代理上部署证书链、私钥并配置现代 TLS 1.2/1.3 密码套件;第三是在 80 端口配置 HTTP 到 HTTPS 的 301/308 永久重定向,并结合 HSTS(`Strict-Transport-Security`)头部确保浏览器强制走加密通道。
在非公开 Web 或跨网内网访问场景下,也可按需选用其他加密传输手段,如利用 VPN(虚拟专用网络)在网络层或传输层构建端到端加密隧道,或借助 SSH 隧道将本地端口安全转发至远端服务。本站离线脚本构造并解析了 TLS 5 字节记录层首部与 `ClientHello`(含 SNI 与 TLS 1.3 套件)、演示了密码套件协商、CA 签名/域名/有效期证书校验以及 HKDF-SHA256 密钥派生与 301 重定向配置。
离线解析 TLS 记录层与 ClientHello 帧、密码套件协商、X.509 证书校验及 HKDF 密钥派生
展开查看收起
"""Offline network protocol verification lab for Chapter 12 (https-protocol)."""
import hashlib
import hmac
import json
import struct
VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"
def case_tls_record_header_and_client_hello():
# Build minimal RFC 8446 / 5246 TLS Record (ContentType=22 Handshake, LegacyVersion=0x0303)
# containing Handshake Type=1 (ClientHello) with SNI extension for www.example.com
sni_host = b"www.example.com"
sni_entry = struct.pack("!BH", 0, len(sni_host)) + sni_host
sni_list = struct.pack("!H", len(sni_entry)) + sni_entry
sni_ext = struct.pack("!HH", 0x0000, len(sni_list)) + sni_list
extensions = struct.pack("!H", len(sni_ext)) + sni_ext
client_random = bytes(range(32))
cipher_suites = struct.pack("!HHH", 4, 0x1301, 0x1302) # TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384
ch_body = struct.pack("!H", 0x0303) + client_random + b"\x00" + cipher_suites + b"\x01\x00" + extensions
# Handshake header: 1B type + 3B length
hs_msg = bytes([1]) + len(ch_body).to_bytes(3, "big") + ch_body
tls_record = struct.pack("!BHH", 22, 0x0303, len(hs_msg)) + hs_msg
# Parse back
rec_type, rec_ver, rec_len = struct.unpack("!BHH", tls_record[:5])
hs_type = tls_record[5]
hs_len = int.from_bytes(tls_record[6:9], "big")
body = tls_record[9 : 9 + hs_len]
cs_len = struct.unpack("!H", body[35:37])[0]
suites = list(struct.unpack(f"!{cs_len // 2}H", body[37 : 37 + cs_len]))
expected = {
"record_type_handshake": 22,
"legacy_version": "0x0303",
"record_len_matches": True,
"handshake_type_client_hello": 1,
"offered_suites": ["0x1301", "0x1302"],
"sni_present": True,
}
actual = {
"record_type_handshake": rec_type,
"legacy_version": f"0x{rec_ver:04x}",
"record_len_matches": rec_len == len(hs_msg) and hs_len == len(ch_body),
"handshake_type_client_hello": hs_type,
"offered_suites": [f"0x{s:04x}" for s in suites],
"sni_present": b"www.example.com" in body,
}
return {
"name": "tls_record_header_and_client_hello",
"summary": "打包并解析 TLS 5 字节记录层首部与 ClientHello 握手子帧(含密码套件列表与 SNI 扩展)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tls_cipher_suite_negotiation():
client_offered = [
"TLS_AES_128_GCM_SHA256",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
]
server_preferred = [
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256",
]
selected = next((s for s in server_preferred if s in client_offered), None)
expected = {
"selected_suite": "TLS_CHACHA20_POLY1305_SHA256",
"aead_integrity_included": True,
}
actual = {
"selected_suite": selected,
"aead_integrity_included": selected is not None and ("GCM" in selected or "POLY1305" in selected),
}
return {
"name": "tls_cipher_suite_negotiation",
"summary": "模拟客户端与服务端 TLS 密码套件优先级交集协商并确认 AEAD 加密完整性模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_x509_certificate_chain_validation():
ca_signing_key = b"offline-demo-root-ca-secret"
def issue_cert(san_domains, not_before, not_after, pubkey_hex):
body = json.dumps(
{"san": san_domains, "not_before": not_before, "not_after": not_after, "pubkey": pubkey_hex},
sort_keys=True,
).encode("utf-8")
sig = hmac.new(ca_signing_key, body, hashlib.sha256).hexdigest()
return {"body": body, "sig": sig}
def verify_cert(cert, target_host, now_ts):
calc = hmac.new(ca_signing_key, cert["body"], hashlib.sha256).hexdigest()
if not hmac.compare_digest(calc, cert["sig"]):
return "INVALID_SIGNATURE"
info = json.loads(cert["body"].decode("utf-8"))
if not (info["not_before"] <= now_ts <= info["not_after"]):
return "EXPIRED"
if target_host not in info["san"]:
return "HOSTNAME_MISMATCH"
return "VALID"
cert = issue_cert(["www.example.com", "api.example.com"], 1700000000, 1800000000, "04a1b2c3")
expected = {
"valid_host_in_window": "VALID",
"wrong_host": "HOSTNAME_MISMATCH",
"expired_time": "EXPIRED",
}
actual = {
"valid_host_in_window": verify_cert(cert, "www.example.com", 1750000000),
"wrong_host": verify_cert(cert, "evil.example.net", 1750000000),
"expired_time": verify_cert(cert, "www.example.com", 1900000000),
}
return {
"name": "x509_certificate_chain_validation",
"summary": "离线验证 CA 签名、SAN 域名匹配与有效时间窗三项 HTTPS 服务器证书校验逻辑",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_https_key_derivation_and_hsts_redirect():
# RFC 5869 HKDF-Extract & single-block HKDF-Expand with SHA-256
salt = b"\x00" * 32
ikm = b"shared-ecdhe-pre-master-secret"
prk = hmac.new(salt, ikm, hashlib.sha256).digest()
client_key = hmac.new(prk, b"tls13 c ap traffic\x01", hashlib.sha256).digest()[:16]
server_key = hmac.new(prk, b"tls13 s ap traffic\x01", hashlib.sha256).digest()[:16]
http_url = "http://www.example.com/login"
redirect_resp = {
"status": 301,
"location": http_url.replace("http://", "https://", 1),
"hsts": "max-age=31536000; includeSubDomains",
}
expected = {
"derived_keys_distinct": True,
"key_bits": 128,
"redirect_status": 301,
"redirect_location": "https://www.example.com/login",
}
actual = {
"derived_keys_distinct": client_key != server_key,
"key_bits": len(client_key) * 8,
"redirect_status": redirect_resp["status"],
"redirect_location": redirect_resp["location"],
}
return {
"name": "https_key_derivation_and_hsts_redirect",
"summary": "使用 HKDF-SHA256 派生独立上下行流量密钥,并校验 HTTP 到 HTTPS 的 301 重定向与 HSTS 配置",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_tls_record_header_and_client_hello(),
case_tls_cipher_suite_negotiation(),
case_x509_certificate_chain_validation(),
case_https_key_derivation_and_hsts_redirect(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
必须核对证书的生效/过期有效期(判断当前时间是否在有效时间窗内)以及证书 SAN/CN 绑定的域名是否与正在访问的主机名匹配。