aesEncrypt function

Uint8List aesEncrypt(
  1. dynamic data,
  2. dynamic key, {
  3. bool isDataHexa = true,
  4. bool isKeyHexa = true,
})

Encrypt a data for a given public key using AES algorithm @param {String | Uint8List} data Data to encrypt @param {String | Uint8List} key Symmetric key

Implementation

Uint8List aesEncrypt(
  dynamic data,
  dynamic key, {
  bool isDataHexa = true,
  bool isKeyHexa = true,
}) {
  if (data is! Uint8List && data is! String) {
    throw "'data' must be a string or Uint8List";
  }

  if (key is! Uint8List && key is! String) {
    throw "'key' must be a string or Uint8List";
  }

  if (data is String) {
    if (isDataHexa && !isHex(data)) {
      throw const FormatException("'data' must be an hexadecimal string");
    }

    if (isDataHexa) {
      data = Uint8List.fromList(hexToUint8List(data));
    } else {
      data = Uint8List.fromList(utf8.encode(data));
    }
  }

  if (key is String) {
    if (isKeyHexa && !isHex(key)) {
      throw const FormatException("'key' must be an hexadecimal string");
    }

    if (isKeyHexa) {
      key = Uint8List.fromList(hexToUint8List(key));
    } else {
      throw "'key' must be an hexadecimal string";
    }
  }

  final keyPair = crypto_keys.KeyPair.symmetric(
    crypto_keys.SymmetricKey(keyValue: Uint8List.fromList(key)),
  );
  final iv = Uint8List.fromList(
    List<int>.generate(12, (int i) => Random.secure().nextInt(256)),
  );
  final encrypter = keyPair.publicKey!
      .createEncrypter(crypto_keys.algorithms.encryption.aes.gcm);
  final v = encrypter.encrypt(data, initializationVector: iv);

  final result = concatUint8List(
    <Uint8List>[v.initializationVector!, v.authenticationTag!, v.data],
  );
  return result;
}