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

Flutter实现明文RSA加密时parseKeyFromFile报文件异常如何解决

问题原因
  • parseKeyFromFile方法的入参要求是本地文件系统的文件路径,方法内部会根据传入的路径自行读取文件内容、解析密钥。
  • 你的代码中已经通过rootBundle.loadString读取到了pem文件的完整公钥文本,却把这段公钥文本当成文件路径传给了parseKeyFromFile,系统会把整段公钥字符串作为文件路径去查找文件,必然触发文件不存在的错误。错误日志中显示的待打开文件路径就是完整的公钥内容,可以直接印证这个问题。
修复方法

你已经提前拿到了pem格式的公钥字符串,不需要再调用IO相关的文件读取解析方法,直接使用密钥解析器从字符串内容解析公钥即可,修正后的代码如下:

import 'package:encrypt/encrypt.dart';

void encrypt(BuildContext context) async {
  print("Hiiiis==> ${enteredMobileOtp.value}");
  // 读取assets中公钥pem内容的逻辑保留
  final publicPem = await rootBundle.loadString('assets/test/public.pem');
  print("Hiiiis==> ${publicPem}");
  // 直接从pem字符串解析公钥,移除原parseKeyFromFile调用
  final publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;
  print("HII==> ${enteredMobileOtp.value}");
  final plainText = enteredMobileOtp.value;
  final encrypter = Encrypter(RSA(publicKey: publicKey));
  final encrypted = encrypter.encrypt(plainText);
  print("Hii=====> ${encrypted.base64}");
}

注意:如果原来导入了package:encrypt/encrypt_io.dart用于使用parseKeyFromFile,修复后可以移除该导入,避免无用依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:18:14