问题
We are doing a school project where we need to explain code line by line. We need to explain the following 3 lines:
// TODO: This is where the magic of XOR is happening. Are you able to explain what is going on?
for (int i = 0; i < rawString.length(); i++) {
thisIsEncrypted.append((char) (rawString.charAt(i) ^ key[i % key.length]));
}
Can anyone help us? It is the last lines we need to be done.
Thank you in advance! :-)
Best regards, Casper
回答1:
If you look at the bitwise operation XOR it does that:
0^0 = 0
1^0 = 1
0^1 = 1
1^1 = 0
This makes it very useful for encryption because if you have :
original_value ^ key = encrypted_value
Then encrypted_value can be converted back to the original_value by XORing with the same key:
encrypted_value ^ key = original_value
So in your example you have a raw string and then encrypted string and to encrypt it for each character in the raw script it uses XOR with a character from the key. Since the key length is different from the raw string length it uses modulus (%) to get the corresponding position of the key. For example if they key is 3 characters long every third char in the original string will be encoded with the same char from the key.
Basically doing the opposite call will transfer your encrypted string back to the raw one. To demonstrate with example:
String rawString="Give me A on my homework!";
char[] key="OH no!".toCharArray();
StringBuilder thisIsEncrypted=new StringBuilder();
for (int i = 0; i < rawString.length(); i++) {
thisIsEncrypted.append((char) (rawString.charAt(i) ^ key[i % key.length]));
}
// Now we have encrypted it - lets decrypt
rawString=thisIsEncrypted.toString();
thisIsEncrypted=new StringBuilder();
for (int i = 0; i < rawString.length(); i++) {
thisIsEncrypted.append((char) (rawString.charAt(i) ^ key[i % key.length]));
}
System.out.println("This was encrypted and then decrypted: "+thisIsEncrypted);
来源:https://stackoverflow.com/questions/53481953/xor-explaining-of-3-lines