decrypt method
Decrypts a combined string produced by encrypt.
combined must be in the format ivBase64:ciphertextBase64 — exactly
what EncryptedPayload.combined contains and what you stored in Firestore.
Throws CryptoException if the format is invalid, the key is wrong, or the data has been tampered with.
Implementation
String decrypt(String combined) {
if (combined.isEmpty) {
throw const CryptoException(message: 'Cannot decrypt an empty string.');
}
try {
final payload = EncryptedPayload.fromCombined(combined);
final iv = enc.IV.fromBase64(payload.iv);
final cipherText = enc.Encrypted.fromBase64(payload.cipherText);
final encrypter = enc.Encrypter(enc.AES(_key, mode: enc.AESMode.cbc));
return encrypter.decrypt(cipherText, iv: iv);
} on ArgumentError catch (e) {
throw CryptoException(message: e.message.toString(), cause: e);
} catch (e, st) {
throw CryptoException(
message:
'Decryption failed. '
'The key may be wrong or the data has been tampered with.',
cause: e,
stackTrace: st,
);
}
}