I am trying to fill a byte array, 2 bytes at a time. My hw is a cryptography hw. I am to find the plain text from the given cipher text using a key. The key is 2 bytes long. The plain text was encrypted with many time pad. The Key is repeated until its as long as the plain text. I got the first 2 bytes of the key, now i just need to repeat it until its as long as the cipher text/plain text.
The cipher text length which is the same as the plain text length is 640138. The key is supposed to be this length as well, but what i got for key length after i applied the solution below was 640144. Doing Math.min below instead of Math.max gives an error String.checkBoundsBeginEnd. I had to convert it to string because the builder is of type StringBuilder. "result" in this instance is key.
How do i make the key as long as the cipher text length?
byte[] cipherText = Files.readAllBytes(Paths.get("src/cipher3.bmp"));
byte[] plainText = new byte[cipherText.length];
byte[] pText = new byte[]{'B', 'M'};
byte[] key = new byte[pText.length];
for(int i = 0; i < pText.length; i++){
key[i] = (byte)(cipherText[i] ^ pText[i]);
}
String keyString = Arrays.toString(key);
System.out.println("The key " + keyString);
System.out.println("First two in ptext"+ Arrays.toString(pText));
System.out.println(plainText.length);
String plainlength = (String) Arrays.toString(new int[]{plainText.length});
System.out.println(plainlength);
StringBuilder builder = new StringBuilder(cipherText.length);
while(builder.length() < cipherText.length){
builder.append(keyString.substring(0, Math.max(keyString.length(), builder.length() -cipherText.length)));
}
String result = builder.toString();
System.out.println(result);
System.out.println(result.length());//this gives 640144
builder.append(keyString.substring(0, Math.max(keyString.length(), builder.length() -cipherText.length)));is supposed to add two bytes at a time, but I do know that you should not be using Strings at all. Instead of StringBuilder, use ByteBuffer, and instead of StringBuilder.append, use ByteBuffer.put.