XOR operation with two strings in java

The Solution to XOR operation with two strings in java is

You want something like this:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;

public class StringXORer {

    public String encode(String s, String key) {
        return base64Encode(xorWithKey(s.getBytes(), key.getBytes()));

    public String decode(String s, String key) {
        return new String(xorWithKey(base64Decode(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;

    private byte[] base64Decode(String s) {
        try {
            BASE64Decoder d = new BASE64Decoder();
            return d.decodeBuffer(s);
        } catch (IOException e) {throw new RuntimeException(e);}

    private String base64Encode(byte[] bytes) {
        BASE64Encoder enc = new BASE64Encoder();
        return enc.encode(bytes).replaceAll("\\s", "");


The base64 encoding is done because xor'ing the bytes of a string may not give valid bytes back for a string.

~ Answered on 2011-11-02 16:06:17

Most Viewed Questions: