encryptWithPassword function
Encrypts the plainText with the given password and salt using AES-CBC.
The input data is converted to JSON and then encrypted. A random 16-byte IV (Initialization Vector) is generated and prepended to the encrypted data.
If the password is empty, the data is returned as UTF-8 encoded JSON
without any actual encryption.
The encryption process is run in a separate Isolate to avoid blocking the main thread.
Implementation
Future<Uint8List> encryptWithPassword(
dynamic plainText,
String password,
String salt,
) async {
return Isolate.run(() {
if (password.isEmpty) return utf8.encode(jsonEncode(plainText));
final key = encrypt.Key(deriveKey(password, salt));
final iv = encrypt.IV.fromLength(16);
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc),
);
final encrypted = encrypter.encrypt(jsonEncode(plainText), iv: iv);
return Uint8List.fromList(iv.bytes + encrypted.bytes);
});
}