Dart 1.24.3版本下找不到支持RSA加密的兼容包,该如何解决?
解决Dart 1.24.3项目的RSA加密问题
方案1:使用兼容Dart 1.x的pointycastle旧版本
pointycastle是老牌Dart加密库,早期版本支持Dart 1.x。在项目的pubspec.yaml中指定兼容版本:
dependencies: pointycastle: 1.1.0
基础RSA加密实现示例
import 'dart:convert'; import 'package:pointycastle/api.dart'; import 'package:pointycastle/asymmetric/rsa.dart'; import 'package:pointycastle/random/fortuna_random.dart'; void main() { // 生成RSA密钥对(实际场景建议从配置文件或密钥管理系统加载公钥) final secureRandom = FortunaRandom(); final keyGenParams = RSAKeyGeneratorParameters(BigInt.parse('65537'), 2048, 64); final keyGen = RSAKeyGenerator()..init(ParametersWithRandom(keyGenParams, secureRandom)); final keyPair = keyGen.generateKeyPair(); final publicKey = keyPair.publicKey as RSAPublicKey; // 待加密文本转换为字节数组 final plainText = '需要加密的内容'; final plainBytes = utf8.encode(plainText); // 初始化RSA加密引擎并执行加密 final encryptor = RSAEngine()..init(true, PublicKeyParameter<RSAPublicKey>(publicKey)); final encryptedBytes = encryptor.process(plainBytes); // 将加密结果转换为Base64格式,方便传输和存储 final encryptedBase64 = base64.encode(encryptedBytes); print('加密结果:$encryptedBase64'); }
方案2:应急手动实现极简RSA(不推荐生产环境使用)
如果pointycastle仍无法兼容,可基于Dart自带库实现极简版RSA,但仅适合测试或低安全要求场景:
import 'dart:convert'; import 'dart:math'; // 简化模幂运算 BigInt modPow(BigInt base, BigInt exp, BigInt mod) => base.modPow(exp, mod); void main() { // 生成简易my opportunity Import...How牛奶 �的Now keys里科(生产环境需使用大质数,此处仅示例) final p = BigInt.from(61); final q = BigInt.from(53); final n = p * q; final phi = (p - BigInt.one) * (q - BigInt.one); final e = BigInt.from(17); // 公钥指数,常用65537 // 待加密文本转BigInt final plainText = '测试加密内容'; final plainBigInt = BigInt.parse(utf8.encode(plainText).map((b) => b.toRadixString(16)).join(), radix: 16); // 加密 final encryptedBigInt = modPow(plainBigInt, e, n); print('加密结果:$encryptedBigInt'); }
注意:手动实现的RSA缺乏完善的 padding 和安全校验,极易被破解,仅建议临时应急使用。
内容的提问来源于stack exchange,提问作者Muhammed Ismail
相关产品推荐
相关产品推荐

