Performs XOR operation between two Strings. - Java java.lang

Java examples for java.lang:String Algorithm

Description

Performs XOR operation between two Strings.

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Main {
    /**/*from   w  ww. ja  va 2  s.co  m*/
     * Performs XOR operation between two Strings. Converts the Strings to an
     * array of bytes and performs the xor operation in each byte of the arrays.
     */
    public static String stringXor(String strMessage, String strKey) {

        String result = null;
        byte[] messageBuf = strMessage.getBytes();
        byte[] keyBuf = strKey.getBytes();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(
                messageBuf.length);

        int c = 0;

        for (int i = 0; i < messageBuf.length; i++) {
            byte messageByte = messageBuf[i];
            byte keyByte = keyBuf[c];

            //byte xorByte = (byte)(messageByte ^ keyByte);
            byte xorByte = (byte) (messageByte ^ keyByte);

            if (c < keyBuf.length - 1) {
                c++;
            } else {
                c = 0;
            }

            baos.write(xorByte);
        }

        try {
            baos.flush();
            result = baos.toString();
            baos.close();
            baos = null;
        } catch (IOException e) {
            System.out.println("Exception: " + e);
        }

        return result;
    }
}

Related Tutorials