R
R
Roman Tomchenko2022-03-13 17:06:06
Java
Roman Tomchenko, 2022-03-13 17:06:06

What is the cause of the error in the keyExpansion function of the Java AES implementation?

Translated a working AES encryption algorithm from Python to Java.
On startup, we get an Out of Bounds error in the key extension function.

Function text:

public static ArrayList<ArrayList<Integer>> keyExpansion(String key) {
  ArrayList<Integer> keySymbols = new ArrayList<>();
  for (Character c : key.toCharArray())
    keySymbols.add((int) c);
  if (keySymbols.size() < 4 * nk)
    for (int i = 0; i < 4 * nk - keySymbols.size(); i++)
      keySymbols.add(0x01);
  ArrayList<ArrayList<Integer>> keySchedule = new ArrayList<>();
  for (int r = 0; r < 4; r++) {
    keySchedule.add(new ArrayList<>());
    for (int c = 0; c < nk; c++)
      keySchedule.get(r).add(keySymbols.get(r + 4 * c));
  }
  for (int col = nk; col < nb * (nr + 1); col++)
    if (col % nk == 0) {
      ArrayList<Integer> tmp = new ArrayList<>();
      for (int row = 1; row < 4; row++)
        tmp.add(keySchedule.get(row).get(col - 1));
      tmp.add(keySchedule.get(0).get(col - 1));
      for (int j = 0; j < tmp.size(); j++) {
        int sBoxR = tmp.get(j) / 0x10;
        int sBoxC = tmp.get(j) % 0x10;
        int sBoxElem = sBox[16 * sBoxR + sBoxC];
        tmp.set(j, sBoxElem);
      }
      for (int row = 0; row < 4; row++) {
        int s = keySchedule.get(row).get(col - 4) ^ tmp.get(row) ^ rCon[row][col / nk - 1];
        keySchedule.get(row).add(s);
      }
    } else {
      for (int row = 0; row < 4; row++) {
        int s = keySchedule.get(row).get(col - 4) ^ keySchedule.get(row).get(col - 1);
        keySchedule.get(row).add(s);
      }
    }
  return keySchedule;
}


The error comes out in the line: Values ​​nk, nb and nr (4, 4, 10) are preassigned by global variables. Arrays sBox and rCon - too. The key length does not exceed 4 * nk = 16. What could be the problem? In Python, this code works as it should.
keySchedule.get(r).add(keySymbols.get(r + 4 * c));


Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Tomchenko, 2022-03-13
@Widestrip

Answer from @Dmitry Roo
In a loop

for (int i = 0; i < 4 * nk - keySymbols.size(); i++)

we move the upper bound outside, since it is recalculated at each step of the loop
if (keySymbols.size() < 4 * nk) {
  var toAdd = 4 * nk - keySymbols.size();
  for (int i = 0; i < toAdd; i++) {
    keySymbols.add(0x01);
  }
}

D
Dmitry Roo, 2022-03-13
@xez

Obviously because "r + 4 * c" is greater than the length of keySymbols
With r = 0, the values ​​will be 0, 4, 8, 12, etc...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question