Search code examples
javastringencryptionxor

When encrypting 2 Strings with XOR in Java, what is key[i % key.length]


I'm trying to understand "encrypting" 2 Strings with XOR in Java, I've found pretty clear example but I can't understand why they are doing this:

input.charAt(i) ^ key[i % key.length]

How in "human readable way" to descirbe key[i % key.length], e.g. they are taking next chat from input and XOR-ing it with ...?

Whole method for "encrypting" with XOR is:

private static String encryptDecrypt(String input) {
    char[] key = {'K', 'C', 'Q'}; //Can be any chars, and any length array
    StringBuilder output = new StringBuilder();

    for(int i = 0; i < input.length(); i++) {
        output.append((char) (input.charAt(i) ^ key[i % key.length]));
    }

    return output.toString();
}

Solution

  • Rather than XOR each character with the same value the algorithm uses a list of values. This way if your string is EE (for example) then the output encrypted string would contain two different characters, rather than the same character for each E. In this case the string would contain the characters with code 14 and 6. The idea here is to prevent the same character always be encrypted with the same value.

    The expression key[i % key.length] is used to select the next key from the array, and will wrap around to the first key when i goes past the end of that array.