架构与系统设计 / 系统课时

渠道通信安全

渠道通信安全

本课完成一套可复用的渠道通信安全方案:请求先规范化,再签名或加密;响应先验签,再解密和解析;证书、密钥与敏感参数统一从受控配置加载,避免明文泄露和处理顺序错误。

学习目标

  • 掌握渠道请求签名、响应验签与恒定时间比较的实现方式
  • 使用 AES-GCM 保护敏感参数,并正确管理随机向量与认证标签
  • 从 PKCS#12 证书库加载私钥和证书,建立可验证的启动检查

安全边界与处理顺序

渠道通信通常同时包含签名、加密、证书和日志脱敏。四者不能随意排列:签名用于确认数据未被篡改,加密用于隐藏内容,证书用于绑定通信身份,日志脱敏用于阻止敏感信息在平台内部二次泄露。

推荐处理顺序是:业务参数规范化,敏感字段加密,对最终报文签名,然后发送;收到响应后先校验签名,再解密敏感字段,最后交给业务解析。验签失败时必须立即终止,不能继续尝试解密或更新订单。

渠道安全处理时序

签名与加密主示例

下面示例使用 HMAC-SHA256 对规范化参数签名,并使用 AES-GCM 加密敏感字段。示例可直接在 JDK 17 及以上运行;生产环境应把密钥放入密钥管理系统或环境变量,不要写入源码和普通配置文件。

java
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class ChannelSecurityDemo {
    private static final SecureRandom RANDOM = new SecureRandom();

    public static void main(String[] args) throws Exception {
        byte[] signKey = "sign-key-for-demo-only-32-bytes!!".getBytes(StandardCharsets.UTF_8);
        byte[] aesKey = "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8);

        Map<String, String> request = new TreeMap<>();
        request.put("amount", "128.00");
        request.put("merchantOrderNo", "M202608030001");
        request.put("cardNo", encryptAesGcm("622202******1234", aesKey));

        String canonical = canonicalize(request);
        String signature = hmacSha256(canonical, signKey);
        boolean signatureValid = verifyHmac(canonical, signature, signKey);
        String plainCardNo = decryptAesGcm(request.get("cardNo"), aesKey);

        System.out.println("signatureValid=" + signatureValid);
        System.out.println("plainCardNo=" + plainCardNo);
    }

    static String canonicalize(Map<String, String> params) {
        return new TreeMap<>(params).entrySet().stream()
                .filter(entry -> entry.getValue() != null && !entry.getValue().isBlank())
                .filter(entry -> !"sign".equals(entry.getKey()))
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
    }

    static String hmacSha256(String content, byte[] key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return Base64.getEncoder().encodeToString(
                mac.doFinal(content.getBytes(StandardCharsets.UTF_8))
        );
    }

    static boolean verifyHmac(String content, String received, byte[] key) throws Exception {
        byte[] expected = Base64.getDecoder().decode(hmacSha256(content, key));
        byte[] actual = Base64.getDecoder().decode(received);
        // 恒定时间比较可降低基于比较耗时推测签名内容的风险。
        return MessageDigest.isEqual(expected, actual);
    }

    static String encryptAesGcm(String plainText, byte[] key) throws Exception {
        byte[] iv = new byte[12];
        RANDOM.nextBytes(iv);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
                new GCMParameterSpec(128, iv));
        byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        byte[] payload = new byte[iv.length + cipherText.length];
        System.arraycopy(iv, 0, payload, 0, iv.length);
        System.arraycopy(cipherText, 0, payload, iv.length, cipherText.length);
        return Base64.getEncoder().encodeToString(payload);
    }

    static String decryptAesGcm(String encoded, byte[] key) throws Exception {
        byte[] payload = Base64.getDecoder().decode(encoded);
        byte[] iv = java.util.Arrays.copyOfRange(payload, 0, 12);
        byte[] cipherText = java.util.Arrays.copyOfRange(payload, 12, payload.length);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
                new GCMParameterSpec(128, iv));
        return new String(cipher.doFinal(cipherText), StandardCharsets.UTF_8);
    }
}

预期输出如下。密文包含随机 IV,因此每次运行都不同,但验签和解密结果应保持一致。

text
signatureValid=true
plainCardNo=622202******1234

规范化规则必须与渠道文档完全一致,包括字符集、字段排序、空值处理、金额格式和 URL 编码。任何一项不同,都会造成“本地计算正确但渠道验签失败”。

证书加载与启动校验

采用 RSA 或双向 TLS 的渠道,通常提供 PKCS#12 证书库。下面是片段示例,依赖调用方传入证书路径、密码和别名;它负责从证书库读取私钥与公钥证书。

java
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

public final class ChannelCertificateLoader {
    private ChannelCertificateLoader() {
    }

    public static Material load(Path path, char[] password, String alias) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (InputStream input = Files.newInputStream(path)) {
            keyStore.load(input, password);
        }

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password);
        X509Certificate certificate =
                (X509Certificate) keyStore.getCertificate(alias);

        if (privateKey == null || certificate == null) {
            throw new IllegalStateException("证书别名不存在或缺少私钥: " + alias);
        }

        // 启动时检查有效期,避免证书过期后才在支付请求中暴露故障。
        certificate.checkValidity();
        return new Material(privateKey, certificate);
    }

    public record Material(PrivateKey privateKey, X509Certificate certificate) {
    }
}

生效验证不应打印私钥、密码或完整证书。启动日志只记录渠道编号、证书别名、序列号后六位和到期时间;测试环境还应执行一次签名自检,确认私钥签名能被证书公钥验证。

敏感参数与失败处理

密钥、证书密码、银行卡号、身份证号和渠道令牌都不得进入普通日志。日志可记录字段是否存在、长度、哈希摘要或末四位,但不能记录可还原的密文上下文与解密结果。

验签失败、证书过期、解密认证失败和时间戳超窗应归类为安全错误,并阻止订单状态推进。网络重试只能重发同一业务请求标识,不能重新生成订单号;签名中的时间戳和随机串是否重建,必须遵循渠道协议。验收时至少覆盖以下检查项:

  • 修改任意请求字段后,渠道侧验签必须失败
  • 使用错误密钥、错误证书别名或过期证书时,应用应在启动或调用前明确报错
  • 同一明文多次加密得到不同密文,但都能正确解密
  • 日志、异常堆栈和监控标签中不出现完整敏感参数
按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

渠道通信安全

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通