Fix CTR decryption.

Off by one error in respect to the y blocks.
This commit is contained in:
Sebastian Hugentobler 2022-03-22 21:07:04 +01:00
parent e04a341fc6
commit e1c2d7df7d
Signed by: shu
GPG key ID: BB32CF3CA052C2F0
7 changed files with 105 additions and 45 deletions

View file

@ -3,6 +3,11 @@ package ch.fhnw.kry;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import static ch.fhnw.kry.Main.BLOCK_LENGTH;
/**
* Implementation of CTR mode for decryption.
*/
public class CTR {
private final SPN spn = new SPN();
private final int iv;
@ -13,10 +18,11 @@ public class CTR {
this.key = key;
}
public int getIV() {
return iv;
}
/**
* Generate a 16 bit long initialisation vector.
*
* @return Generated initialisation vector.
*/
public static int generateIV() {
Random random = ThreadLocalRandom.current();
byte[] r = new byte[2];
@ -25,10 +31,22 @@ public class CTR {
return r[0] << 8 & r[1];
}
public int decrypt(int block, int idx) {
int e = (iv + idx) % (1 << 16);
e = spn.decryptBlock(key, e);
public int getIV() {
return iv;
}
return block ^ e;
/**
* Decrypt a block in CTR mode.
*
* @param block Encrypted block (only lower 16 bits get looked at).
* @param idx Block index.
* @param y Y at index idx.
* @return Decrypted block (in the lower 16 bits of the int).
*/
public int decrypt(int block, int idx, int y) {
int e = (iv + idx) % (1 << BLOCK_LENGTH); // iv + i mod 2^16
e = spn.encryptBlock(key, e); // yes, we need the encryption function, as this is CTR
return y ^ e;
}
}