aesEncrypt function

Uint8List aesEncrypt(
  1. dynamic data,
  2. dynamic key
)

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) {
  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 (isHex(data)) {
      data = Uint8List.fromList(hexToUint8List(data));
    } else {
      data = Uint8List.fromList(utf8.encode(data));
    }
  }

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

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

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