push garbage
This commit is contained in:
parent
18cdd1ed81
commit
3bc74649ad
7 changed files with 137 additions and 43 deletions
49
src/main/java/ch/fhnw/kry/Decrypt.java
Normal file
49
src/main/java/ch/fhnw/kry/Decrypt.java
Normal file
|
@ -0,0 +1,49 @@
|
|||
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);
|
||||
var ctr = new CTR(key);
|
||||
|
||||
int[] data = strToArray(chiffre);
|
||||
byte[] decryptedData = new byte[data.length * 2];
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue