user3531591
user3531591

Reputation: 61

XOR of two Strings not working when size of strings is big

I am trying to XOR two strings and then again XOR the output with one string to get the other string. Sometimes it is working as expected but sometimes it gives some unexpected result.

    private static byte[] xorData(byte[] data1, byte[] data2) throws    UnsupportedEncodingException{
    String l1s=new String(data1);
    String l2s=new String(data2);
    int l1=data1.length;
    int l2=data2.length;
    if(l1>l2)
    {
        while(l1s.length()!=l2s.length()){
            l2s=l2s+"0";
        }
    }
    if(l1<l2)
    {
        while(l1s.length()!=l2s.length()){
            l1s=l1s+"0";
        }
    }
    data1=l1s.getBytes();
    data2=l2s.getBytes();
    System.out.println("data1 len "+data1.length);
    System.out.println("data2 length "+data2.length);
    byte[] result=new byte[data1.length];
    for(int i=0;i<data1.length;i++){
            result[i]=(byte)(data1[i] ^ data2[i%data2.length]);
        }

    System.out.println("*********final resulttttttt*******************  "+new String(result,"UTF-8"));
    return result;
}

Similar way I will perform XOR with the output of above method and first string to get the second string. Note: To this method I am passing bytes array instead of passing String

Upvotes: 2

Views: 601

Answers (1)

templatetypedef
templatetypedef

Reputation: 372814

The constructor you're using to build your strings is the byte[] constructor for the String type, which I think is doing something other than what you're expecting. That function works by trying to decode the raw bytes as some encoding of Unicode code points rather than as a sequence of individual char values. For example, if your platform is planning on using UTF-8 encodings, it might interpret a series of bytes as an encoding of a single character rather than as multiple individual bytes. As a result, converting to and from String using this constructor will likely mess up your data.

If you want to XOR together all the bytes into a final array, don't go through a String intermediary. Instead, just directly XOR the bytes in the arrays.

It seems like you were primarily using the String type so that you could pad the input arrays to get them up to the same size. If that's the case, rather than routing through Strings, try something like this:

byte[] result = new Byte[Math.max(data1.length, data2.length)];
for (int i = 0; i < result.length; i++) {
    byte first  = (i < data1.length? data1[i] : (byte)0);
    byte second = (i < data2.length? data2[i] : (byte)0);
    result[i] = (byte)(first ^ second);
}

Upvotes: 1

Related Questions