decryptText method
Decrypts a hexadecimal string encryptedWithIV that was encrypted using encryptText.
The method assumes that the last 32 characters (16 bytes) represent the IV in hex, and the rest is the encrypted data.
Example:
final decrypted = manager.decryptText(encrypted);
Throws Exception if the input is invalid or too short.
Returns the original decrypted plaintext.
Implementation
String decryptText(String encryptedWithIV) {
// Validate input length: must contain at least an IV (32 hex chars)
if (encryptedWithIV.length < crypto.ivLength * 2) {
throw Exception("Invalid encrypted text (too short)");
}
// Extract IV and encrypted data from hex string
final ivHex = encryptedWithIV
.substring(encryptedWithIV.length - 32); // Last 32 chars = IV
final encryptedHex = encryptedWithIV.substring(
0, encryptedWithIV.length - 32); // Remaining = data
// Convert IV and encrypted data from hex back to bytes
final iv = encrypt.IV(crypto.hexToBytes(ivHex));
final encryptedBytes = crypto.hexToBytes(encryptedHex);
// Derive AES key again (must match the one used during encryption)
final key = encrypt.Key(crypto.deriveKey());
// Create AES decrypter
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7'),
);
// Decrypt the encrypted bytes using the extracted IV
return encrypter.decrypt(encrypt.Encrypted(encryptedBytes), iv: iv);
}