encryptAES256CBC static method

Future<String?> encryptAES256CBC(
  1. dynamic data, {
  2. String? key,
  3. String? iv,
})

Asynchronously encrypts data using AES-256 in CBC mode. The method supports providing a custom key and initialization vector (IV).

Implementation

static Future<String?> encryptAES256CBC(
  dynamic data, {
  String? key,
  String? iv,
}) async {
  try {
    if (data == null) return null;

    final secretKey = _fixedPadString(key ?? _defaultKey, 32);
    final secretIV = iv;

    final hashKey = sha256.convert(utf8.encode(secretKey)).bytes;

    final ivBytes = (secretIV == null)
        ? encrypt.IV.fromSecureRandom(16).bytes
        : Uint8List.fromList(utf8.encode(_fixedPadString(secretIV, 16)));

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

    final encodedData = json.encode(data);
    final encrypted = encrypter.encrypt(encodedData, iv: ivValue);

    final combined = Uint8List.fromList(ivValue.bytes + encrypted.bytes);
    return _toBase64Url(combined);
  } catch (e) {
    rethrow;
  }
}