XOR two lines in JAVA

I am trying to encrypt a string part of which is XOR text with an IV string. After some difficulties, I ended up on stackoverflow where the guy gave the following code:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;

public class StringXORer {

public String encode(String s, String key) {
    return base64Encode(xorWithKey(s.getBytes(), key.getBytes()));
}

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));
}

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    }
    return out;
}

private byte[] base64Decode(String s) {
    try {
        BASE64Decoder d = new BASE64Decoder();
        return d.decodeBuffer(s);
    } catch (IOException e) {throw new RuntimeException(e);}
}

private String base64Encode(byte[] bytes) {
    BASE64Encoder enc = new BASE64Encoder();
    return enc.encode(bytes).replaceAll("\\s", "");

}
}

This seemed to work, with the exception of 2 questions: The result string is getting longer. When you tried to make XOR between "abcdefgh" and "abcdefgh", I got: "aaaaaaaaaaaa". Secondly, the result of two identical lines becomes "aaaa ...." - the string "a" s ....

So, two questions:

  • Why does the given string get longer?
  • Why does the XOR result between identical lines consist of a list of "a" s ...?

This is homework, appreciate any help.

Thanx!

+3
source share
1 answer

, XORing Base64 .

base64Encode(...) new String(...) base64Decode(s) s.getBytes(), XORed. , . XORed \0, .

, getBytes() , , , . UTF-8 >= 128 . ISO-8859-1 1--1 <= 255 . , new String(...) , .

+2

All Articles