XOR Hex String in JAVA of different lengths

I have two lines

String s1="426F62"; String s2="457665"; 

Strings are represented in hexadecimal notation. I want them XOR. XORing usually character by character gives the correct result for other than F XOR 6 (it gives 112, the answer should be 9)

Please tell me the correct way to implement it in JAVA

EDIT: Convert to int and xoring. But like xor, when two lines have different lengths.

+8
java cryptography
source share
4 answers

Instead of XORing Unicode representations, just convert each character to the number that it represents in hexadecimal, XOR, and then convert it back to hex. You can still do this one character at a time:

 public String xorHex(String a, String b) { // TODO: Validation char[] chars = new char[a.length()]; for (int i = 0; i < chars.length; i++) { chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i))); } return new String(chars); } private static int fromHex(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } throw new IllegalArgumentException(); } private char toHex(int nybble) { if (nybble < 0 || nybble > 15) { throw new IllegalArgumentException(); } return "0123456789ABCDEF".charAt(nybble); } 

Note that this should work as long as the strings (if they are the same length), and you never need to worry about negative values ​​- you will always get the XORing result of each pair of characters.

+13
source share

Try the following:

 String s1 = "426F62"; String s2 = "457665"; int n1 = Integer.parseInt(s1, 16); int n2 = Integer.parseInt(s2, 16); int n3 = n1 ^ n2; String s3 = String.format("%06x", n3); 

Why do you store hexadecimal values ​​as strings? it would be much better to represent hexadecimal numbers as integers or lengths.

+4
source share

The fact that it gives the correct result is an artifact of a particular character encoding for numbers and letters. You must convert the numbers to BigInteger , XOR them and convert back to String :

 BigInteger i1 = new BigInteger(s1, 16); BigInteger i2 = new BigInteger(s2, 16); BigInteger res = i1.xor(i2); String s3 = res.toString(16); 

EDIT (in response to John Skeet's comment): Using BigInteger instead of int to solve a four-byte problem.

+2
source share

Another option that may be useful depending on the size of the lines

 String s1="426F62"; String s2="457665"; BigInteger one = new BigInteger(s1, 16); BigInteger two = new BigInteger(s2, 16); BigInteger three = one.xor(two); 
0
source share

All Articles