encrypt method
Encrypts plainText with AES-256-CBC and a fresh random 16-byte IV.
Every call produces a different ciphertext even for the same input, because the IV is re-randomised each time.
The returned EncryptedPayload.combined string is what you store in
Firestore — format: ivBase64:ciphertextBase64.
Throws CryptoException if plainText is empty or encryption fails.
Implementation
EncryptedPayload encrypt(String plainText) {
if (plainText.isEmpty) {
throw const CryptoException(message: 'Cannot encrypt an empty string.');
}
try {
final iv = enc.IV.fromSecureRandom(16);
final encrypter = enc.Encrypter(enc.AES(_key, mode: enc.AESMode.cbc));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return EncryptedPayload.create(
iv: iv.base64,
cipherText: encrypted.base64,
combined: '${iv.base64}:${encrypted.base64}',
);
} catch (e, st) {
throw CryptoException(
message: 'Encryption failed.',
cause: e,
stackTrace: st,
);
}
}