x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 4183

# String XOR Method

Hi,

I'm looking for a method that makes a XOR operation between 2 String with the following signature : String xor(String str, String key); and used like this :

String myStr = "treteterterterterter";
String myKey = "terwb897856304984erzvgtze";

String myCodedStr = xor(myStr,myKey);
String myDecodedStr = xor(myCodedStr, myKey);

Note that myDecodedStr is equals to myStr.

It's quitely URGENT for me, so that's why I give 300 points for the source code.

Thanks
0
baresse
1 Solution

Commented:
Hi baresse,

Try the following method:

public String xor(String str, String key) {
String result = null;
byte[] strBuf = str.getBytes();
byte[] keyBuf = key.getBytes();
int c = 0;
int z = keyBuf.length;
ByteArrayOutputStream baos = new ByteArrayOutputStream(strBuf.length);
for (int i = 0; i < strBuf.length; i++) {
byte bS = strBuf[i];
byte bK = keyBuf[c];
byte bO = (byte)(bS ^ bK);
if (c < z - 1) {
c++;
} else {
c = 0;
}
baos.write(bO);
}
try {
baos.flush();
result = baos.toString();
baos.close();
baos = null;
} catch (IOException ioex) {
}
return result;
}

The idea is to convert the string and the key to byte arrays, then you XOR each byte of the string with the corresponding byte from the key, when you "run-out" of key-bytes you just start over from the start of the key ;)

Regards and good luck,

Doron
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.