expandKey method

void expandKey(
  1. List<int> key,
  2. List<int> encKey, [
  3. List<int>? decKey
])

Implementation

void expandKey(List<int> key, List<int> encKey, [List<int>? decKey]) {
  final nk = key.length ~/ 4;
  final n = encKey.length;

  for (int i = 0; i < nk; i++) {
    encKey[i] = readUint32BE(key, i * 4);
  }

  for (int i = nk; i < n; i++) {
    int t = encKey[i - 1];
    if (i % nk == 0) {
      t = _subw(_rotw(t)) ^ (_powx[i ~/ nk - 1] << 24);
    } else if (nk > 6 && i % nk == 4) {
      t = _subw(t);
    }
    encKey[i] = encKey[i - nk] ^ t;
  }

  if (decKey != null) {
    // Derive decryption key from encryption key.
    // Reverse the 4-word round key sets from enc to produce dec.
    // All sets but the first and last get the MixColumn transform applied.
    for (int i = 0; i < n; i += 4) {
      final ei = n - i - 4;
      for (int j = 0; j < 4; j++) {
        int x = encKey[ei + j];
        if (i > 0 && i + 4 < n) {
          x = _td0[_sbox0[(x >> 24) & mask8]] ^
              _td1[_sbox0[(x >> 16) & mask8]] ^
              _td2[_sbox0[(x >> 8) & mask8]] ^
              _td3[_sbox0[x & mask8]];
        }
        decKey[i + j] = x;
      }
    }
  }
}