diff --git a/src/main/java/ch/fhnw/kry/SPN.java b/src/main/java/ch/fhnw/kry/SPN.java index 7d2e3c6..8c39bee 100644 --- a/src/main/java/ch/fhnw/kry/SPN.java +++ b/src/main/java/ch/fhnw/kry/SPN.java @@ -62,6 +62,9 @@ public class SPN { entry(15, 15) ); + private static final int BLOCK_LENGTH = 16; + private static final int ROUNDS = 4; + public String decrypt(int key, String chiffre) { return null; @@ -78,11 +81,11 @@ public class SPN { * @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() / 16]; + int[] data = new int[bits.length() / BLOCK_LENGTH]; for (int i = 0; i < data.length; i++) { - int startIdx = i * 16; - String wordBits = bits.substring(startIdx, startIdx + 16); + int startIdx = i * BLOCK_LENGTH; + String wordBits = bits.substring(startIdx, startIdx + BLOCK_LENGTH); int word = Integer.parseInt(wordBits, 2); data[i] = word; } @@ -100,14 +103,14 @@ public class SPN { public int encryptBlock(int key, int x) { x = init(key, x, 0); // initialer Weisschritt - for (int i = 1; i < 4; i++) { // for rounds > 0 && < r + for (int i = 1; i < ROUNDS; i++) { // for rounds > 0 && < r x = substitution(x, SBOX); // run through s-box x = permutation(x); // permutate x ^= k(key, i); // xor with derived round key } x = substitution(x, SBOX); // run through s-box - x ^= k(key, 4); // xor with last round key + x ^= k(key, ROUNDS); // xor with last round key return x; } @@ -120,9 +123,9 @@ public class SPN { * @return Decrypted block. */ public int decryptBlock(int key, int x) { - x = init(key, x, 4); // initialer Weisschritt + x = init(key, x, ROUNDS); // initialer Weisschritt - for (int i = 3; i > 0; i--) { // for rounds > 0 && < r, going in reverse + for (int i = ROUNDS - 1; i > 0; i--) { // for rounds > 0 && < r, going in reverse x = substitution(x, SBOX_REVERSE); // run through reverse s-box x = permutation(x); // permutate x ^= permutation(k(key, i)); // xor with permutated derived round key @@ -144,7 +147,7 @@ public class SPN { * @return Derived key. */ public int k(int key, int i) { - i *= 4; + i *= ROUNDS; int mask = 0xFFFF_0000 >>> i; return (key & mask) >>> ROUND_KEY_LENGTH - i; @@ -174,7 +177,7 @@ public class SPN { public int permutation(int x) { Map blocked = new HashMap<>(); - for (int i = 0; i < 16; i++) { + for (int i = 0; i < BLOCK_LENGTH; i++) { int target = PERMUTATION.get(i); if (!blocked.containsKey(target)) { x = swapBits(x, i, target);