encrypt static method

String encrypt(
  1. String data, {
  2. String? key,
  3. int round = 10_000,
})

Encrypts the given data string with an optional key. Returns base64-encoded string containing both IV and encrypted data.

Implementation

static String encrypt(String data, {String? key, int round = 10_000}) {
  final encryptionKey = key ?? _defaultKey;
  final keyBytes = utf8.encode(encryptionKey);
  final dataBytes = utf8.encode(data);

  final random = Random.secure();
  final iv = List<int>.generate(16, (_) => random.nextInt(256));
  final derivedKey = _deriveKey(keyBytes, iv, round);
  final encryptedBytes = _encryptBytes(dataBytes, derivedKey, iv);

  final combined = Uint8List.fromList(iv + encryptedBytes);

  return base64Encode(combined);
}