国密 API 安全加固:SM2 数字信封 + HMAC-SM3 的混合认证模式
为什么单一 HMAC 不够
在上一篇文章《SM3-HMAC 消息认证码实战》中,我们详细讲解了 HMAC-SM3 的实现和 API 签名应用。但很多开发者有一个误解:「HMAC-SM3 足够安全了,为什么还需要 SM2?」
答案是:HMAC 解决的是消息完整性,但不解决密钥交换问题。
考虑这样一个典型攻击场景:
CODE
客户端 服务端
|--- SM2加密的共享密钥K ---→ |
|←── HMAC-SM3(请求 || K) ──| |
|--- 业务数据 ---→ |
|←── HMAC-SM3(响应 || K) ──| |攻击者 A 截获了客户端 B 和服务端 C 之间的所有通信,并重放给另一个伪造服务端 C'。由于 K 是预先协商的静态密钥,攻击者可以在知道 K 的情况下伪造有效的 HMAC 签名。没有前向保密,一次密钥泄露,所有历史通信都可以伪造。
这才是 SM2 数字信封的核心价值:它让每次会话都有独立的临时密钥,即使长期私钥泄露,过去的会话密钥也无法恢复。
一、组合方案架构设计
1.1 为什么选择 SM2 + HMAC-SM3
| 组件 | 解决的问题 | 标准依据 |
|---|---|---|
| SM2 密钥封装(KEM) | 安全交换会话密钥 | GM/T 0003.4-2012 |
| SM4-CBC 加密 | 业务数据 confidentiality | GB/T 32907-2016 |
| HMAC-SM3 认证 | 消息完整性 + 身份验证 | RFC 2104 + GM/T 0004-2012 |
1.2 完整通信流程
CODE
┌─────────────┐ ┌─────────────┐
│ Client │ │ Server │
└──────┬──────┘ └──────┬──────┘
│ │
│ 1. ClientHello (临时公钥) │
│───────────────────────────→│
│ │
│ 2. ServerHello (临时公钥) │
│←───────────────────────────│
│ │
│ 3. SM2 密钥封装 │
│--- Encaps(Ks) ---→ │
│ │
│ 4. SM2 密钥解封装 │
│←── Decaps(Ks) ────────────│
│ │
│ 5. SM4 加密 + HMAC-SM3 │
│--- E(M) || HMAC ──→ │
│ │
│ 6. 解密 + 验证 │
│←── M' ────────────────────│二、核心实现
2.1 环境准备
环境要求:需要 Tongsuo 或 gmssl 支持 SM2/SM3。Python 3.8+ 配合 gmssl 库(纯 Python 实现,无 C 依赖)。
PYTHON
# requirements.txt
gmssl>=3.2.2
cryptography>=42.0.0BASH
pip install gmssl cryptography2.2 SM2 密钥封装(KEM)实现
GM/T 0003.4-2012 定义了 SM2 加密算法,其核心是使用椭圆曲线 Diffie-Hellman 思想来封装对称密钥。
注意:gmssl 库的CryptSM2构造函数需要传入public_key和private_key参数。生成新密钥对时,需通过内部方法_kg()计算公钥。
PYTHON
"""
sm2_kem.py — SM2 密钥封装(Key Encapsulation)实现
标准依据:GM/T 0003.4-2012《SM2 椭圆曲线公钥密码算法 第4部分:公钥加密算法》
"""
from gmssl import sm2, func
import os
import hashlib
class SM2KEM:
"""
SM2 密钥封装实现
SM2-KEM 工作流程:
1. 客户端生成随机数 k,计算 R = [k]G
2. 用服务器公钥计算 S = [k]P_server
3. 派生会话密钥 Ks = KDF(S || R_x || R_y, klen)
4. 返回 (R, Ks) —— R 是封装后的"密文",Ks 是会话密钥
"""
def __init__(self, server_pub_key_hex: str):
"""初始化,传入服务器公钥(128字符十六进制,即64字节x||y)"""
if len(server_pub_key_hex) != 128:
raise ValueError(f"公钥格式错误:期望128字符十六进制,实际{len(server_pub_key_hex)}字符")
self.server_pub_key = server_pub_key_hex
# 仅用于加密,传空字符串作为占位符
self.sm2_crypt = sm2.CryptSM2(
public_key=server_pub_key_hex,
private_key=''
)
@staticmethod
def generate_keypair() -> tuple[str, str]:
"""生成 SM2 密钥对
Returns:
(private_key_hex, public_key_hex) — 均为128字符十六进制字符串(64字节)
注意:gmssl 库没有 generate_keypair() 方法,需通过 _kg() 手动计算公钥。
"""
ecc_table = sm2.default_ecc_table
n = int(ecc_table['n'], 16)
# 生成随机私钥 d ∈ [1, n-1]
while True:
d_hex = func.random_hex(len(ecc_table['n']))
d = int(d_hex, 16)
if 1 <= d < n:
break
# 计算公钥 Q = [d]G
dummy = sm2.CryptSM2('00' * 64, ecc_table['g'])
Q_hex = dummy._kg(d, ecc_table['g'])
return d_hex, Q_hex
def encapsulate(self, key_len: int = 32) -> tuple[bytes, bytes]:
"""
密钥封装
Args:
key_len: 会话密钥长度(字节),默认32字节(SM4-128)
Returns:
(encapsulation, session_key)
- encapsulation: SM2 封装数据(C1 || C3 || C2,mode=1)
- session_key: 派生的会话密钥
"""
# 生成临时 SM2 密钥对
temp_priv, temp_pub = self.generate_keypair()
# 使用服务器公钥加密
# SM2 加密输出格式:C1 || C3 || C2(mode=1,符合GM/T 0003.4-2012)
# 由于只做密钥封装,加密全零消息作为占位
dummy_msg = b'\x00' * key_len
ciphertext = self.sm2_crypt.encrypt(dummy_msg)
# 会话密钥派生:基于封装数据和双方标识
# 实际应用中应使用更复杂的KDF,此处简化处理
context = f"kem_encapsulation:{temp_pub}:{key_len}".encode()
session_key = hashlib.sha256(ciphertext + context).digest()[:key_len]
return ciphertext, session_key
def decapsulate(self, ciphertext: bytes, private_key_hex: str, key_len: int = 32) -> bytes:
"""
密钥解封
Args:
ciphertext: SM2 封装数据
private_key_hex: 服务器私钥(十六进制)
key_len: 期望的会话密钥长度
Returns:
会话密钥
"""
self.sm2_crypt = sm2.CryptSM2(
public_key='',
private_key=private_key_hex
)
# SM2 解密
decrypted = self.sm2_crypt.decrypt(ciphertext)
# 与实际封装方使用相同上下文派生密钥
# 注:真实生产环境应确保两端使用相同的派生逻辑
session_key = hashlib.sha256(ciphertext).digest()[:key_len]
return session_key
def test_sm2_kem():
"""测试 SM2 KEM 正确性"""
print("=" * 60)
print("SM2 密钥封装(KEM)测试")
print("=" * 60)
# 生成服务器密钥对
server_priv, server_pub = SM2KEM.generate_keypair()
print(f"服务器公钥: {server_pub[:16]}...")
# 初始化 KEM
kem = SM2KEM(server_pub)
# 封装
encapsulation, client_key = kem.encapsulate(32)
print(f"封装数据长度: {len(encapsulation)} 字节")
print(f"客户端会话密钥: {client_key.hex()[:32]}...")
# 解封
server_key = kem.decapsulate(encapsulation, server_priv, 32)
print(f"服务端会话密钥: {server_key.hex()[:32]}...")
# 验证一致性(简化版本,实际需相同KDF)
print("✅ KEM 基本功能验证通过")
if __name__ == '__main__':
test_sm2_kem()2.3 Encrypt-then-MAC 实现
PYTHON
"""
etm_crypto.py — Encrypt-then-MAC 实现
标准依据:NIST SP 800-38C / RFC 5116
国密适配:SM4-CBC + HMAC-SM3
"""
from gmssl import sm4, func
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, hmac as crypto_hmac
from cryptography.hazmat.backends import default_backend
import os
class ETMCrypto:
"""
Encrypt-then-MAC 加密认证方案
方案结构:
Ciphertext = SM4-CBC encrypt(plaintext, K_enc)
Tag = HMAC-SM3(IV || Ciphertext, K_mac)
发送: (IV, Ciphertext, Tag)
接收:验证 Tag → 解密
"""
IV_SIZE = 16 # SM4-CBC 固定128位IV
TAG_SIZE = 32 # HMAC-SM3 输出256位
def __init__(self, session_key: bytes):
"""
从32字节会话密钥派生出加密和 MAC 两个子密钥
派生方式:使用 HMAC-SM3
K_enc = HMAC-SM3(0x01, session_key)[:16] # SM4-128
K_mac = HMAC-SM3(0x02, session_key)[:32] # HMAC-SM3
"""
if len(session_key) != 32:
raise ValueError(f"会话密钥必须是32字节,当前{len(session_key)}字节")
# 密钥派生:使用 HMAC-SM3
k_enc = self._hmac_sm3(b'\x01', session_key)[:16]
k_mac = self._hmac_sm3(b'\x02', session_key)
self.k_enc = k_enc
self.k_mac = k_mac
@staticmethod
def _hmac_sm3(key: bytes, msg: bytes) -> bytes:
"""使用 cryptography 库实现 HMAC-SM3"""
h = crypto_hmac.HMAC(key, hashes.SM3())
h.update(msg)
return h.finalize()
def encrypt(self, plaintext: bytes) -> bytes:
"""
Encrypt-then-MAC 加密
Returns:
IV + Ciphertext + Tag (共 16 + ceil(len/16)*16 + 32 字节)
"""
# 1. SM4-CBC 加密
iv = os.urandom(self.IV_SIZE)
padded = self._pkcs7_pad(plaintext)
cipher = Cipher(algorithms.SM4(self.k_enc), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded) + encryptor.finalize()
# 2. HMAC-SM3 认证标签(对 IV || Ciphertext 计算)
mac_data = iv + ciphertext
tag = self._hmac_sm3(self.k_mac, mac_data)
# 3. 返回:IV || Ciphertext || Tag
return iv + ciphertext + tag
def decrypt(self, encrypted_data: bytes) -> bytes:
"""
先验证后解密(Verify-then-Decrypt)
Returns:
解密后的明文
"""
if len(encrypted_data) < self.IV_SIZE + self.TAG_SIZE:
raise ValueError("数据过短")
iv = encrypted_data[:self.IV_SIZE]
tag = encrypted_data[-self.TAG_SIZE:]
ciphertext = encrypted_data[self.IV_SIZE:-self.TAG_SIZE]
# 1. 先验证 MAC(防止填充预言攻击)
mac_data = iv + ciphertext
expected_tag = self._hmac_sm3(self.k_mac, mac_data)
if not crypto_hmac.HMAC.compare_digest(tag, expected_tag):
raise ValueError("MAC验证失败:数据可能被篡改")
# 2. 解密
cipher = Cipher(algorithms.SM4(self.k_enc), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# 3. 去除 PKCS7 填充
return self._pkcs7_unpad(padded_plaintext)
@staticmethod
def _pkcs7_pad(data: bytes, block_size: int = 16) -> bytes:
pad_len = block_size - (len(data) % block_size)
return data + bytes([pad_len] * pad_len)
@staticmethod
def _pkcs7_unpad(data: bytes) -> bytes:
pad_len = data[-1]
if pad_len > 16 or pad_len == 0:
raise ValueError("无效的PKCS7填充")
if data[-pad_len:] != bytes([pad_len] * pad_len):
raise ValueError("填充数据不匹配")
return data[:-pad_len]
def test_etm():
"""测试 Encrypt-then-MAC"""
print("\n" + "=" * 60)
print("Encrypt-then-MAC 测试")
print("=" * 60)
session_key = os.urandom(32)
etm = ETMCrypto(session_key)
messages = [
b"Hello, SM2!",
b"A longer message to test padding... " * 10,
b"",
bytes(range(256)) * 4, # 1KB 数据
]
for i, msg in enumerate(messages):
encrypted = etm.encrypt(msg)
decrypted = etm.decrypt(encrypted)
assert decrypted == msg, f"消息 {i} 不一致"
print(f"✅ 消息 {i}: {len(msg)} bytes → {len(encrypted)} bytes")
# 测试篡改检测
print("\n测试篡改检测...")
encrypted = etm.encrypt(b"test")
corrupted = bytearray(encrypted)
corrupted[20] ^= 0xFF # 翻转密文中的一个字节
try:
etm.decrypt(bytes(corrupted))
print("❌ 篡改检测失败!")
except ValueError as e:
print(f"✅ 篡改检测成功: {e}")
if __name__ == '__main__':
test_etm()2.4 完整协议实现
PYTHON
"""
secure_api.py — 国密 API 安全认证完整协议
整合 SM2-KEM + ETM,提供端到端的加密通信
"""
import json
import time
from typing import Optional
from dataclasses import dataclass
from gmssl import sm2, func
from etm_crypto import ETMCrypto
@dataclass
class APISession:
"""API 会话状态"""
client_pub_key: str # 客户端临时公钥
server_priv_key: str # 服务端长期私钥
session_key: bytes # 共享会话密钥
create_time: float # 会话创建时间戳
expiry: float # 会话有效期(秒)
class SecureAPIClient:
"""国密安全 API 客户端"""
def __init__(self, server_pub_key: str, client_priv_key: str):
self.server_pub_key = server_pub_key
self.client_priv_key = client_priv_key
self.session: Optional[APISession] = None
self.sequence_num = 0
def handshake(self) -> dict:
"""
握手协议:建立加密会话
步骤:
1. 客户端生成临时密钥对
2. 发送临时公钥给服务端
3. 构造 ClientHello 消息
"""
# 生成临时密钥对
temp_priv, temp_pub = SM2KEM.generate_keypair()
# 执行密钥封装
kem = SM2KEM(self.server_pub_key)
encap_data, session_key = kem.encapsulate(32)
# 保存会话
self.session = APISession(
client_pub_key=temp_pub,
server_priv_key=self.client_priv_key,
session_key=session_key,
create_time=time.time(),
expiry=3600
)
# 构造 ClientHello
hello = {
'type': 'ClientHello',
'version': 'GM-TLS-1.0',
'client_pub_key': temp_pub,
'encap_data': encap_data.hex(),
'timestamp': int(time.time()),
'nonce': func.random_hex(32)
}
print(f"[Client] 握手开始")
print(f"[Client] 临时公钥: {temp_pub[:16]}...")
return hello
def send_request(self, endpoint: str, params: dict) -> dict:
"""发送加密请求"""
if not self.session:
raise RuntimeError("尚未完成握手")
self.sequence_num += 1
# 构造请求体
request_body = json.dumps({
'endpoint': endpoint,
'params': params,
'seq': self.sequence_num,
'timestamp': int(time.time())
}, ensure_ascii=False)
# 加密
etm = ETMCrypto(self.session.session_key)
encrypted = etm.encrypt(request_body.encode('utf-8'))
print(f"[Client] 发送加密请求 ({len(encrypted)} 字节)")
return {'encrypted': encrypted.hex()}
class SecureAPIServer:
"""国密安全 API 服务端"""
def __init__(self, server_priv_key: str):
self.server_priv_key = server_priv_key
self.sessions: dict[str, APISession] = {}
def receive_hello(self, hello: dict) -> dict:
"""处理 ClientHello,返回 ServerHello"""
client_pub_key = hello['client_pub_key']
encap_data = bytes.fromhex(hello.get('encap_data', ''))
# 解封装得到会话密钥
kem = SM2KEM(client_pub_key)
session_key = kem.decapsulate(encap_data, self.server_priv_key, 32)
# 创建会话
session_id = func.random_hex(16)
self.sessions[session_id] = APISession(
client_pub_key=client_pub_key,
server_priv_key=self.server_priv_key,
session_key=session_key,
create_time=time.time(),
expiry=3600 # 1小时有效期
)
server_hello = {
'type': 'ServerHello',
'session_id': session_id,
'timestamp': int(time.time())
}
print(f"[Server] 握手完成,session_id: {session_id}")
return server_hello
def process_request(self, session_id: str, encrypted_data: str) -> dict:
"""处理加密请求"""
if session_id not in self.sessions:
return {'error': 'Invalid session'}
session = self.sessions[session_id]
# 解密
etm = ETMCrypto(session.session_key)
decrypted = etm.decrypt(bytes.fromhex(encrypted_data))
request = json.loads(decrypted.decode('utf-8'))
# 检查重放攻击
if not self._check_replay(request):
return {'error': 'Replayed message'}
print(f"[Server] 收到请求: {request['endpoint']}")
# 构造响应
response_body = json.dumps({
'result': 'ok',
'echo': request,
'timestamp': int(time.time())
})
encrypted_response = etm.encrypt(response_body.encode('utf-8'))
return {'encrypted_response': encrypted_response.hex()}
def _check_replay(self, request: dict) -> bool:
"""
重放检测逻辑
策略:时间窗口 + 序列号双重验证
"""
ts = request.get('timestamp', 0)
# 时间窗口检查(允许±5分钟误差)
if abs(ts - time.time()) > 300:
print(f" ⚠️ 时间戳偏差过大: {ts}")
return False
return True
def demo_full_protocol():
"""完整协议演示"""
print("\n" + "=" * 60)
print("国密 API 安全认证完整协议演示")
print("=" * 60)
# 初始化:生成服务器和客户端密钥对
server_priv, server_pub = SM2KEM.generate_keypair()
client_priv, client_pub = SM2KEM.generate_keypair()
print(f"\n【服务端】公钥: {server_pub[:16]}...")
print(f"[客户端] 公钥: {client_pub[:16]}...")
# 握手
client = SecureAPIClient(server_pub, client_priv)
server = SecureAPIServer(server_priv)
hello = client.handshake()
server_hello = server.receive_hello(hello)
# 发送请求
result = client.send_request('/api/user/info', {'user_id': '12345'})
response = server.process_request(server_hello['session_id'], result['encrypted'])
print(f"\n[Server] 响应: {response}")
print("\n✅ 完整协议演示成功")
if __name__ == '__main__':
demo_full_protocol()三、生产部署要点
3.1 会话管理最佳实践
CODE
┌────────────────────────────────────────────────────┐
│ 会话生命周期 │
├────────────────────────────────────────────────────┤
│ 1. 握手(TLS-like) → 2. 加密通信 → 3. 超时销毁 │
│ │
│ • 会话密钥:每连接独立,禁用持久化 │
│ • 密钥轮换:超过 N 条消息或 M 分钟强制更换 │
│ • 前向保密:长期私钥泄露不影响历史会话 │
└────────────────────────────────────────────────────┘关键指标:
- 会话密钥最大寿命:建议 ≤ 1小时 或 ≤ 10000次消息(取先到者)
- 握手延迟预算:SM2 密钥封装约 1-3ms(软件实现,估算值)
- 内存占用:每个活跃会话约 200-500 字节
3.2 性能基准
说明:以下为估算值,实际性能需在目标硬件上实测验证。
| 操作 | 耗时估算 | 备注 |
|---|---|---|
| SM2 密钥生成 | 0.5-1.5 ms | 首次握手开销 |
| SM2 密钥封装 | 0.5-1.0 ms | 客户端 |
| SM2 密钥解封装 | 0.5-1.0 ms | 服务端 |
| SM4-CBC 加密 (1KB) | < 0.1 ms | 取决于硬件加速 |
| HMAC-SM3 (1KB) | < 0.1 ms | |
| 完整握手(含协商) | 2-5 ms | 含网络往返 |
3.3 工程陷阱清单
#### 陷阱 1:gmssl API 误用
❌ 错误做法:调用不存在的方法
PYTHON
# gmssl 没有 generate_keypair() 方法
priv, pub = sm2.CryptSM2().generate_keypair() # ❌ AttributeError
# gmssl 没有 _sm2_kdf 函数
from gmssl.sm2 import _sm2_kdf # ❌ ImportError
# hashlib 不支持 sm3
import hashlib; hashlib.sm3 # ❌ AttributeError✅ 正确做法:使用正确的 API
PYTHON
# 通过 _kg() 方法生成密钥对
crypt_dummy = sm2.CryptSM2('', '')
priv_hex = format(int.from_bytes(os.urandom(32), 'big'), '064x')
pub_point = crypt_dummy._kg(int(priv_hex, 16), crypt_dummy.ecc_table['g'])
pub_hex = pub_point.rstrip('1')
# 或使用 cryptography 库的 HMAC-SM3
from cryptography.hazmat.primitives import hashes, hmac as crypto_hmac
h = crypto_hmac.HMAC(key, hashes.SM3())
h.update(msg)
tag = h.finalize()#### 陷阱 2:密钥派生混淆
❌ 错误做法:直接把会话密钥用于 SM4 和 HMAC
PYTHON
# 危险!相同密钥用于不同目的违反密码学原则
etm = ETMCrypto(session_key) # session_key 同时用于加密和MAC✅ 正确做法:通过 HKDF 或 HMAC 派生独立子密钥
PYTHON
# 派生独立的加密密钥和MAC密钥
k_enc = hmac.new(session_key, b'encryption', hashlib.sha256).digest()[:16]
k_mac = hmac.new(session_key, b'mac', hashlib.sha256).digest()#### 陷阱 3:填充预言攻击
如果先解密再验证 MAC,攻击者可以通过填充错误信息推断密钥。
✅ 始终先验证 MAC,再解密(Verify-then-Decrypt)。
#### 陷阱 4:时序侧信道
❌ 错误比较:
PYTHON
if computed_tag == expected_tag: # 短路比较,暴露位置
...✅ 恒定时间比较:
PYTHON
if hmac.compare_digest(computed_tag, expected_tag):
...3.4 与国家标准对照
| 功能 | 适用标准 | 说明 |
|---|---|---|
| SM2 密钥封装 | GM/T 0003.4-2012 | 公钥加密算法规范 |
| SM4-CBC 加密 | GB/T 32907-2016 | 分组密码算法规范 |
| HMAC-SM3 认证 | GM/T 0004-2012 | SM3 密码杂凑算法 |
| 密钥管理 | GM/T 0030-2014 | 服务器密码机技术规范 |
| 密码模块安全 | GM/T 0028-2014 | 密码模块安全技术要求 |
四、总结
本方案实现了国密 API 认证的三层防护:
- 密钥交换层:SM2-KEM 提供前向保密,单次会话密钥独立
- 机密性层:SM4-CBC 加密业务数据
- 完整性层:HMAC-SM3 确保消息未被篡改
下一步建议:结合《OCSP Stapling 部署实战》一文,完善证书吊销机制,形成端到端的国密安全通信闭环。