2022-03-22 17:21:33 +01:00
|
|
|
package ch.fhnw.kry;
|
|
|
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
|
|
|
import static ch.fhnw.kry.Main.BLOCK_LENGTH;
|
|
|
|
|
|
|
|
public class Decrypt {
|
|
|
|
public String decrypt(String keyString, String chiffre) {
|
|
|
|
int key = Integer.parseInt(keyString, 2);
|
|
|
|
|
|
|
|
int[] data = strToArray(chiffre);
|
|
|
|
byte[] decryptedData = new byte[data.length * 2];
|
2022-03-22 19:38:52 +01:00
|
|
|
int iv = data[0];
|
|
|
|
var ctr = new CTR(iv, key);
|
|
|
|
|
|
|
|
for (int i = 1; i < data.length; i++) {
|
2022-03-22 17:21:33 +01:00
|
|
|
int block = data[i];
|
|
|
|
int decryptedBlock = ctr.decrypt(block, i);
|
|
|
|
|
|
|
|
decryptedData[i * 2] = (byte)(decryptedBlock >>> 8);
|
|
|
|
decryptedData[i * 2 + 1] = (byte)(decryptedBlock & 0x0000_00FF);
|
|
|
|
}
|
|
|
|
|
|
|
|
String decryptedString = new String(decryptedData, StandardCharsets.US_ASCII);
|
|
|
|
|
|
|
|
return decryptedString;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert a bit string into an integer array.
|
|
|
|
*
|
|
|
|
* Because later we only ever look at the lower 16 bits,
|
|
|
|
* we stuff every block of 16 bits into the lower half of an int
|
|
|
|
* (meaning the igh 16 bits of the ints in the array are always 0).
|
|
|
|
*
|
|
|
|
* @param bits Bit string. Its length must be a multiple of 16.
|
|
|
|
* @return int array, with every int's lower 16 bits set to 16 bits of the input string.
|
|
|
|
*/
|
|
|
|
public int[] strToArray(String bits) {
|
|
|
|
int[] data = new int[bits.length() / BLOCK_LENGTH];
|
|
|
|
|
|
|
|
for (int i = 0; i < data.length; i++) {
|
|
|
|
int startIdx = i * BLOCK_LENGTH;
|
|
|
|
String wordBits = bits.substring(startIdx, startIdx + BLOCK_LENGTH);
|
|
|
|
int word = Integer.parseInt(wordBits, 2);
|
|
|
|
data[i] = word;
|
|
|
|
}
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
}
|