setKey method
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 ListnoDecryption
: An optional boolean flag. If set totrue
, 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;
}