setKey method

  1. @override
AES setKey(
  1. List<int> key, [
  2. bool noDecryption = false
])
override

Initializes the AES cipher with the provided encryption key.

This method sets the encryption key for the AES cipher instance, allowing it to be used for both encryption and decryption. The method enforces key size constraints and securely expands the key into internal key schedules for encryption and decryption if required.

Parameters:

  • key: The encryption key as a List
  • noDecryption: An optional boolean flag. If set to true, it disables decryption functionality by securely wiping the decryption key schedule.

Throws:

  • ArgumentException if the provided key size is invalid or if the instance was previously initialized with a different key size.

Returns:

  • The same AES instance after key initialization, supporting method chaining.

Implementation

@override
AES setKey(List<int> key, [bool noDecryption = false]) {
  if (key.length != 16 && key.length != 24 && key.length != 32) {
    throw const ArgumentException(
        "AES: wrong key size (must be 16, 24, or 32)");
  }
  if (_keyLen != key.length) {
    throw const ArgumentException("AES: initialized with different key size");
  }

  _encKey ??= List<int>.filled(key.length + 28, 0, growable: false);
  if (noDecryption) {
    if (_decKey != null) {
      zero(_decKey!);
      _decKey = null;
    }
  } else {
    _decKey ??= List<int>.filled(key.length + 28, 0, growable: false);
  }
  _lib.expandKey(key, _encKey!, _decKey);
  return this;
}