XOR - Explaining of 3 lines [closed]

邮差的信 提交于 2020-01-30 13:34:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!