我有一段时间使用加密包来解密来自服务器的消息,这些消息是我在一切工作正常之前加密的,但是当我从 pubspec.yaml 文件中清理我的包时,会出现此错误:
无效参数:无效或损坏的填充块
这很令人困惑,我认为问题根本不是来自于清洁包装。
我的代码:
import 'package:encrypt/encrypt.dart' as encrypt;
class EncryptMessages{
static encryptWithAESKey(String data) {
encrypt.Key aesKey = encrypt.Key.fromLength(16);
final encrypter = encrypt.Encrypter(encrypt.AES(aesKey));
encrypt.Encrypted encryptedData =
encrypter.encrypt(data, iv: encrypt.IV.fromLength(16)); ///allZerosOfLength
return encryptedData.base64;
}
static decryptWithAESKey(String data) {
encrypt.Key aesKey = encrypt.Key.fromLength(16);
final encrypter = encrypt.Encrypter(encrypt.AES(aesKey));
encrypt.Encrypted encrypted = encrypt.Encrypted.fromBase64(data);
String decryptedData =
encrypter.decrypt(encrypted, iv: encrypt.IV.fromLength(16)); ///allZerosOfLength
return decryptedData;
}
}
使用加密:^5.0.3
我尝试将软件包版本更改为^5.0.1,^5.0.2
我尝试了allZerosOfLength
我尝试填充到“PKCS7”
我也面临同样的错误
原因:IV值不是恒定的,每次运行时都会产生新的值。 要解密数据,我们需要使用与加密数据相同的 IV。
解决方案:
代码
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorage {
SecureStorage._();
static final SecureStorage _instance = SecureStorage._();
factory SecureStorage() {
return _instance;
}
final _storage = const FlutterSecureStorage();
late encrypt.Key encryptionKey;
late encrypt.IV iv;
Future<void> init() async {
await _getKey();
await _getIV();
}
Future<void> _getKey() async {
String? key = await _storage.read(key: 'encryptionKey');
if (key == null) {
key = encrypt.Key.fromLength(32).base64; // Create a new key if not exists
await _storage.write(key: 'encryptionKey', value: key);
}
encryptionKey = encrypt.Key.fromBase64(key);
}
Future<void> _getIV() async {
String? iv64 = await _storage.read(key: 'encryptionIV');
if (iv64 == null) {
iv64 = encrypt.IV.fromLength(16).base64; // Create a new IV if not exists
await _storage.write(key: 'encryptionIV', value: iv64);
}
iv = encrypt.IV.fromBase64(iv64);
}
String encryptData(String data) {
final encrypter = encrypt.Encrypter(encrypt.AES(encryptionKey));
final encrypted = encrypter.encrypt(data, iv: iv);
return encrypted.base64;
}
String decryptData(String encryptedData) {
final encrypter = encrypt.Encrypter(encrypt.AES(encryptionKey));
return encrypter.decrypt64(encryptedData, iv: iv);
}
}