如何在 Netty 管道中动态加载国密 SM2 证书?

解读

在 KairosDB 这类高并发时序数据库的部署环境中,国密合规已成为政务云、能源、运营商等场景的硬性要求。传统 Netty 的 SslContext 只认 JDK 内置的 X.509 证书链,而 SM2 属于非国际标准椭圆曲线,JDK 默认不提供解析能力,因此“动态加载”必须解决两件事:

  1. 让 Netty 识别 SM2 私钥与证书格式;
  2. 在不重启 Netty 服务的前提下,完成证书热替换,保证写入通道 7×24 可用。
    面试官想确认候选人是否同时掌握国密算法适配、Netty 管道运行时重加载、KairosDB 零停服约束三方面的落地经验。

知识点

  • 国密 SM2 证书结构:DER/PEM 中嵌套 SM2 公钥(ECC 曲线 id-sm2p256v1)与 SM3withSM2 签名,需用 BouncyCastle 的 GM 提供者解析。
  • Netty SslContext 构建原理:底层依赖 JDK SSLEngine,默认 SunJSSE 不支持 SM2;需通过自定义 KeyManagerFactory/TrustManagerFactory把 SM2 密钥材料映射成 SSLEngine 可消费的 PrivateKey/X509Certificate 对象。
  • 动态重加载触发点:Netty 的 SslHandler 一旦加入 ChannelPipeline,其 SSLEngine 即与证书快照绑定;要实现热换,必须新建 SslContext并用 replace() 方法把旧的 SslHandler 整体替换,同时保证正在写入的 Metric 批次不受 TCP 连接重置。
  • KairosDB 零停服约束:写入侧使用 Long-Lived HTTP/1.1 keep-alive,热换证书时须借助SSL renegotiation 禁止与ALPN 一致性校验,避免 IoT 设备因握手失败而重传数据点,造成时序漂移。
  • 国密 TLS 套件:GMTLS 协议版本 1.1 对应 CipherSuite ECC_SM4_GCM_SM3,Netty 4.1.93.Final 开始通过 netty-tcnative-boringssl-gsm 提供支持,但需手动启用 GMProvider并注册至 Security.addProvider()。

答案

步骤一:启动阶段注入 BouncyCastle 与 Netty-GMSuite

Security.insertProviderAt(new BouncyCastleProvider(), 1);
Security.insertProviderAt(new GMSuiteProvider(), 2);   // 提供 SM2 KeyFactory

步骤二:自定义 SM2 密钥加载器

public final class SM2KeyStoreLoader {
    private static final String BC = BouncyCastleProvider.PROVIDER_NAME;
    public static PrivateKey loadPrivateKey(Path pemFile) throws Exception {
        PEMParser p = new PEMParser(Files.newBufferedReader(pemFile, UTF_8));
        Object o = p.readObject();
        PrivateKeyInfo keyInfo = (o instanceof PEMKeyPair) ?
                ((PEMKeyPair) o).getPrivateKeyInfo() : (PrivateKeyInfo) o;
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BC);
        return converter.getPrivateKey(keyInfo);
    }
    public static X509Certificate[] loadCertChain(Path pemFile) throws Exception {
        PEMParser p = new PEMParser(Files.newBufferedReader(pemFile, UTF_8));
        List<X509Certificate> list = new ArrayList<>();
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
        for (Object o; (o = p.readObject()) != null; )
            list.add(converter.getCertificate((X509CertificateHolder) o));
        return list.toArray(new X509Certificate[0]);
    }
}

步骤三:构建支持 SM2 的 SslContext

PrivateKey key = SM2KeyStoreLoader.loadPrivateKey(Paths.get("sm2_private.pem"));
X509Certificate[] chain = SM2KeyStoreLoader.loadCertChain(Paths.get("sm2_fullchain.pem"));
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null);
ks.setKeyEntry("sm2", key, new char[0], chain);
kmf.init(ks, new char[0]);
SslContextBuilder builder = SslContextBuilder.forServer(kmf)
        .trustManager(InsecureTrustManagerFactory.INSTANCE) // 内网场景,可替换为真实根证书
        .sslProvider(SslProvider.OPENSSL)                   // 必须走 tcnative 才能识别 GMTLS
        .protocols("GMTLSv1.1")                             // 国密协议版本
        .ciphers(Arrays.asList("ECC_SM4_GCM_SM3"));
SslContext newCtx = builder.build();

步骤四:在 ChannelPipeline 中热替换

public class DynamicSslContextHandler extends ChannelInboundHandlerAdapter {
    private volatile SslContext sslContext;
    public void reloadSslContext(SslContext newCtx) {
        sslContext = newCtx;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.pipeline().addAfter("idleState", "ssl", sslContext.newHandler(ctx.alloc()));
        super.channelActive(ctx);
    }
    public void replaceSslHandler(Channel ch) {
        SslHandler oldHandler = ch.pipeline().get(SslHandler.class);
        if (oldHandler != null) {
            // 1. 先flush未决数据,2. 再替换
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(f -> {
                ch.pipeline().replace(oldHandler, "ssl", sslContext.newHandler(ch.alloc()));
            });
        }
    }
}

运维侧通过监听 Nacos/Apollo 配置变更触发 reloadSslContext(),即可完成毫秒级热换;KairosDB 的 HTTP 接入层继续复用同一条 TCP 连接,写入吞吐无抖动。

拓展思考

  1. 双证书场景:若前端同时服务国际业务与国密业务,可在同一个端口通过SNI 扩展把 server_name 为 *.gm.internal 的流量路由到 SM2 SslContext,其余走 RSA 证书,实现“一端口双轨”。
  2. 性能调优:SM2 签名验签在纯 Java 实现下 QPS 仅为 RSA2048 的 60%,可开启 netty-tcnative 的硬件加速(通过 JNI 调用鲲鹏加速引擎或海光 CSV),使单核 QPS 提升 2.3 倍,满足 KairosDB 百万级数据点/秒的写入压力。
  3. 合规审计:政务云要求对所有密钥使用痕迹做国密 SM3 摘要链,可在热换证书时把旧证书指纹、新证书指纹、操作员角色、时间戳拼接后做一次 SM3 杂凑,写入 KairosDB 自身的 security.audit 指标,方便后续对接密评与等保 2.0 审计系统。