decryptString method
Decrypt data using AES-256-CTR.
Implementation
String decryptString(String encryptedText) {
final encryptedData = base64.decode(encryptedText);
// Validate minimum length (at least IV = 16 bytes)
if (encryptedData.length < 16) {
throw ArgumentError('Invalid encrypted data: too short');
}
// Extract IV and encrypted bytes
final iv = encryptedData.sublist(0, 16);
final encryptedBytes = encryptedData.sublist(16);
// Handle empty string case (no encrypted data, just IV)
if (encryptedBytes.isEmpty) {
return '';
}
// Setup AES cipher in CTR mode
final cipher = CTRStreamCipher(AESEngine());
final params = ParametersWithIV(KeyParameter(_key), iv);
cipher.init(false, params); // false = decrypt
final decryptedBytes = cipher.process(Uint8List.fromList(encryptedBytes));
try {
return utf8.decode(decryptedBytes);
} catch (e) {
throw ArgumentError('Failed to decrypt: invalid key or corrupted data');
}
}