aesDecrypt function

Uint8List aesDecrypt(
  1. dynamic cipherText,
  2. dynamic key
)

Implementation

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

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

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

  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 = cipherText.sublist(0, 12);
  final Uint8List tag = cipherText.sublist(12, 12 + 16);
  final Uint8List encrypted = cipherText.sublist(28, cipherText.length);
  final crypto_keys.Encrypter<crypto_keys.Key> encrypter = keyPair.privateKey!
      .createEncrypter(crypto_keys.algorithms.encryption.aes.gcm);
  final Uint8List decrypted = encrypter.decrypt(crypto_keys.EncryptionResult(
      encrypted,
      initializationVector: iv,
      authenticationTag: tag));

  return decrypted;
}