Flutter中如何正确加密List<int>类型私钥避免类型不匹配报错?
问题修复方案
错误根因
- 加密工具类
encryptKey方法存在两处核心错误:- 未给入参指定
List<int>类型,存在隐式dynamic类型风险,容易触发方法调用 mismatch encrypter.encryptBytes返回的是Encrypted类实例,不能直接用as List<int>强制转换,两种类型完全不兼容,直接强转会触发类型异常
- 未给入参指定
- 业务代码中对
encryptKey的返回值调用.bytes属性,但你强转后的返回值是List<int>类型,本身不存在bytes属性,进一步触发类型不匹配报错
可行解决方案
第一步:完善加密工具类方法
给所有方法补充明确类型声明,修正encryptKey的返回逻辑:
class AesEncryptionDecryption{ static final key = encrypt.Key.fromLength(32); static final iv = encrypt.IV.fromLength(16); static final encrypter = encrypt.Encrypter(encrypt.AES(key)); // 补充入参和返回值类型声明 static encrypt.Encrypted encryptAES(String text) { final encrypted = encrypter.encrypt(text, iv: iv); return encrypted; } // 明确入参为List<int>,直接返回加密后的Uint8List格式密文 static Uint8List encryptKey(List<int> rawKey) { final encrypted = encrypter.encryptBytes(rawKey, iv: iv); return encrypted.bytes; } static String decryptAES(String base64Text) { print(base64Text); String decrypted = encrypter.decrypt( encrypt.Encrypted.fromBase64(base64Text), iv: iv, ); print(decrypted); return decrypted; } }
第二步:调整业务代码适配修改后的方法
不需要再额外调用.bytes属性,直接接收返回值即可:
var privateKey = await account.keyPair.extractPrivateKeyBytes(); // 直接拿到加密后的Uint8List格式私钥 privateKey = AesEncryptionDecryption.encryptKey(privateKey); final entity = AccountEntity.account(account, privateKey);
额外安全提示
当前代码中用Key.fromLength(32)、IV.fromLength(16)生成的是全0的密钥和IV,无任何加密安全性,生产环境使用时请务必:
- 密钥使用安全随机算法生成后妥善存储,不要硬编码在代码中
- 每次加密都生成随机IV,和密文一起存储,不要固定使用同一个IV
内容的提问来源于stack exchange,提问作者user16560224
相关产品推荐
相关产品推荐

