使用 .pem 文件的 Flutter grpc 凭据

Flutter grpc credentials using .pem file

我有一个 Flutter 应用需要通过 grpc 使用安全客户端通道与服务器通信。

要尝试创建客户端通道,我正在使用:

 final _channel = ClientChannel(_hostAddress,
      port: _port,
      options:
          const ChannelOptions(credentials: ChannelCredentials.secure(
            certificates: ??? ???
          )));

对于 certificates 部分,我仅有的是 .pem 文件中的证书。

puv.dev 页面 here 上的文档完全没有用,因为它只是指出证书参数是一个 List of int

如何从 .pem 文件转到 int 列表?

由于Dart没有byte类型,所以byte数组是List或者Uint8List。我想如果你打开你的 .pem 文件并以字节的形式读取文件的内容,你将得到你的 int

列表
Future<Uint8List> readCert() async {
  final File f = File('cert.pem');
  final bytes = await f.readAsBytes();
  return bytes;
}

尽管 @alex_z 的答案对于其他情况可能是正确的,但它看起来是正确的方法(如果证书文件在某处是资产,就像我的情况一样)是做以下事情:

final cert = await rootBundle.load('assets/certificate.pem');

final certAsList = cert.buffer
        .asUint8List(cert.offsetInBytes, cert.lengthInBytes)
        .map((uint8) => uint8.toInt())
        .toList();

像这样传给ChannelCredentials没问题