52 lines
1.2 KiB
Java
52 lines
1.2 KiB
Java
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;
|
|
private final int key;
|
|
|
|
public CTR(int iv, int key) {
|
|
this.iv = iv;
|
|
this.key = key;
|
|
}
|
|
|
|
/**
|
|
* Generate a 16 bit long initialisation vector.
|
|
*
|
|
* @return Generated initialisation vector.
|
|
*/
|
|
public static int generateIV() {
|
|
Random random = ThreadLocalRandom.current();
|
|
byte[] r = new byte[2];
|
|
random.nextBytes(r);
|
|
|
|
return r[0] << 8 & r[1];
|
|
}
|
|
|
|
public int getIV() {
|
|
return iv;
|
|
}
|
|
|
|
/**
|
|
* Decrypt a block in CTR mode.
|
|
*
|
|
* @param block Encrypted block (only lower 16 bits get looked at).
|
|
* @param idx Block index.
|
|
* @return Decrypted block (in the lower 16 bits of the int).
|
|
*/
|
|
public int decrypt(int block, int idx) {
|
|
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 block ^ e;
|
|
}
|
|
}
|