Search code examples
javaencryptionxor

Length of Strings regarding XOR operation for byte array


I am creating an encryption algorithm and is to XOR two strings. While I know how to XOR the two strings the problem is the length. I have two byte arrays one for the plain text which is of a variable size and then the key which is of 56 bytes lets say. What I want to know is what is the correct method of XORing the two strings. Concatenate them into one String in Binary and XOR the two values? Have each byte array position XOR a concatenated Binary value of the key and such. Any help is greatly appreciated.

Regards, Milinda


Solution

  • To encode just move through the array of bytes from the plain text, repeating the key as necessary with the mod % operator. Be sure to use the same character set at both ends. Conceptually we're repeating the key like this, ignoring encoding.

    hello world, there are sheep
    secretsecretsecretsecretsecr
    

    Encrypt

    String plainText = "hello world, there are sheep";
    Charset charSet = Charset.forName("UTF-8");
    byte[] plainBytes = plainText.getBytes(charSet);
    String key = "secret";
    byte[] keyBytes = key.getBytes(charSet);
    
    byte[] cipherBytes = new byte[plainBytes.length];
    for (int i = 0; i < plainBytes.length; i++) {
    
        cipherBytes[i] = (byte) (plainBytes[i] ^ keyBytes[i
                % keyBytes.length]);
    }
    String cipherText = new String(cipherBytes, charSet);
    System.out.println(cipherText);
    

    To decrypt just reverse the process.

    // decode
    for (int i = 0; i < cipherBytes.length; i++) {
    
        plainBytes[i] = (byte) (cipherBytes[i] ^ keyBytes[i
                % keyBytes.length]);
    }
    plainText = new String(plainBytes, charSet); // <= make sure same charset both ends
    System.out.println(plainText);