From 55876a7d3348f5d6008896a7e6fb602fbd8ab95f Mon Sep 17 00:00:00 2001 From: Sebastian Hugentobler Date: Mon, 21 Mar 2022 09:38:13 +0100 Subject: [PATCH] add bit string to int array conversion --- src/main/java/ch/fhnw/kry/SPN.java | 23 +++++++++++++++++++++++ src/test/java/ch/fhnw/kry/SPNTest.java | 12 ++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/main/java/ch/fhnw/kry/SPN.java b/src/main/java/ch/fhnw/kry/SPN.java index 33a14a4..7d2e3c6 100644 --- a/src/main/java/ch/fhnw/kry/SPN.java +++ b/src/main/java/ch/fhnw/kry/SPN.java @@ -67,6 +67,29 @@ public class SPN { return null; } + /** + * 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() / 16]; + + for (int i = 0; i < data.length; i++) { + int startIdx = i * 16; + String wordBits = bits.substring(startIdx, startIdx + 16); + int word = Integer.parseInt(wordBits, 2); + data[i] = word; + } + + return data; + } + /** * Encrypt a block with the defined SPN. * diff --git a/src/test/java/ch/fhnw/kry/SPNTest.java b/src/test/java/ch/fhnw/kry/SPNTest.java index 4c18b3f..dfbccd3 100644 --- a/src/test/java/ch/fhnw/kry/SPNTest.java +++ b/src/test/java/ch/fhnw/kry/SPNTest.java @@ -73,4 +73,16 @@ class SPNTest { assertEquals(y, spn.encryptBlock(key, x)); assertEquals(x, spn.decryptBlock(key, y)); } + + @Test + void strToArray() { + var spn = new SPN(); + + String input = "00000100110100100000101110111000000000101000111110001110011111110110000001010001010000111010000000010011011001110010101110110000"; + int[] data = spn.strToArray(input); + + assertEquals(8, data.length); + assertEquals(0x04D2, data[0]); + assertEquals(0x2BB0, data[data.length - 1]); + } }