Created
October 14, 2013 19:48
-
-
Save lifuzu/6981087 to your computer and use it in GitHub Desktop.
XOR in Java:
Compile it: javac -cp commons-codec-1.8/commons-codec-1.8.jar StringXORer.java
Run it: java -cp ".:commons-codec-1.8/commons-codec-1.8.jar" StringXORer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.codec.binary.Base64; | |
public class StringXORer { | |
public static void main(String[] args) { | |
StringXORer x = new StringXORer(); | |
String a="hello"; | |
String b="world"; | |
System.out.println(a); | |
System.out.println(b); | |
String c = x.encode(a, b); | |
System.out.println(c); | |
String d = x.decode(c, b); | |
System.out.println(d); | |
} | |
public String encode(String s, String key) { | |
return Base64.encodeBase64String(xorWithKey(s.getBytes(), key.getBytes())); | |
} | |
public String decode(String s, String key) { | |
return new String(xorWithKey(Base64.decodeBase64(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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile it:
javac -cp commons-codec-1.8/commons-codec-1.8.jar StringXORer.java
Run it:
java -cp ".:commons-codec-1.8/commons-codec-1.8.jar" StringXORer