decryptAES256CBC static method

Future decryptAES256CBC(
  1. String? encryptedData, {
  2. String? key,
})

Asynchronously decrypts a encrypted string using AES-256 in CBC mode.

Implementation

static Future<dynamic> decryptAES256CBC(
  String? encryptedData, {
  String? key,
}) async {
  try {
    if (encryptedData == null || encryptedData.isEmpty) return null;

    final secretKey = _fixedPadString(key ?? _defaultKey, 32);
    final hashKey = sha256.convert(utf8.encode(secretKey)).bytes;

    final combined = _fromBase64Url(encryptedData);

    final iv = encrypt.IV(combined.sublist(0, 16));
    final ciphertext = combined.sublist(16);

    final encrypter = encrypt.Encrypter(
      encrypt.AES(
        encrypt.Key(Uint8List.fromList(hashKey)),
        mode: encrypt.AESMode.cbc,
        padding: 'PKCS7',
      ),
    );

    final decrypted = encrypter.decrypt(
      encrypt.Encrypted(ciphertext),
      iv: iv,
    );

    return json.decode(decrypted);
  } catch (e) {
    rethrow;
  }
}