You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Dio(HttpClient)配置自签名信任证书失败问题

Flutter Dio配置自签名证书报错CERT_ALREADY_IN_HASH_TABLE解决方案

错误原因

报错CERT_ALREADY_IN_HASH_TABLE的核心原因有两个:

  1. 创建SecurityContext时设置了withTrustedRoots: true,会加载系统内置的所有可信根证书,当你再次添加自签名证书时,若该证书已存在于系统根证书列表或重复添加,就会触发冲突。
  2. 代码中没有返回修改后的HttpClient,导致你的证书配置根本没有生效。

解决方案

方案1:仅信任指定的自签名证书(不依赖系统根证书)

这种方式适合只需要信任特定自签名证书的场景,避免系统根证书干扰:

(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
  // 创建不包含系统根证书的SecurityContext
  SecurityContext securityContext = SecurityContext(withTrustedRoots: false);
  // 加载assets中的自签名证书
  securityContext.setTrustedCertificates('assets/ca-cert.crt');
  HttpClient httpClient = HttpClient(context: securityContext);
  return httpClient; // 必须返回修改后的HttpClient
};

注意:此场景下不需要设置badCertificateCallback返回true,因为我们已经通过setTrustedCertificates信任了目标证书,回调返回true会跳过所有证书验证,存在安全风险。

方案2:同时信任系统根证书和自签名证书

如果需要保留系统默认的可信根证书,同时添加自定义自签名证书,可以这样处理:

(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
  // 使用默认SecurityContext,包含系统所有可信根证书
  SecurityContext securityContext = SecurityContext.defaultContext;
  try {
    // 添加自签名证书,捕获重复添加的异常
    securityContext.setTrustedCertificates('assets/ca-cert.crt');
  } catch (e) {
    print("证书加载异常(可能已存在): $e");
  }
  HttpClient httpClient = HttpClient(context: securityContext);
  return httpClient;
};

额外注意事项

  • 确保assets/ca-cert.crt已在pubspec.yaml中声明,否则无法加载:
flutter:
  assets:
    - assets/ca-cert.crt
  • 若证书格式不正确(比如不是PEM格式),也可能触发加载异常,确保你的证书是正确的PEM格式。

内容的提问来源于stack exchange,提问作者user22311704

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:45:07