Answer the question
In order to leave comments, you need to log in
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;
}
keySchedule.get(r).add(keySymbols.get(r + 4 * c));
Answer the question
In order to leave comments, you need to log in
Answer from @Dmitry Roo
In a loop
for (int i = 0; i < 4 * nk - keySymbols.size(); i++)
if (keySymbols.size() < 4 * nk) {
var toAdd = 4 * nk - keySymbols.size();
for (int i = 0; i < toAdd; i++) {
keySymbols.add(0x01);
}
}
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 questionAsk a Question
731 491 924 answers to any question