Skip to content

Instantly share code, notes, and snippets.

@lifuzu
Created October 14, 2013 19:48
Show Gist options
  • Save lifuzu/6981087 to your computer and use it in GitHub Desktop.
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
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;
}
}
@lifuzu
Copy link
Author

lifuzu commented Oct 14, 2013

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

@runhwguo
Copy link

cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment