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

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

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

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