XOR cipher in Java & PHP: different results

cryptography, encryption, java, php

Solution

In your PHP encryption method, you have the following code:

for ($i = 0; $i < $ml; $i++){
  $newmsg = $newmsg . ($msg[$i] ^ $key[$i % $kl]);
}

However, `$msg` is not defined anywhere. That should be `$message`.

Problem

Let's say I have a plain text a nice cup of milk tea, which is going to be XOR cipher-ed with key 12345. This Java code: ``` import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; public class XORTest { public static void main(String args[]){ String plaintext = "a nice cup of milk tea"; String key = "12345"; String encrypted = xor_encrypt(plaintext, key); String decrypted = xor_decrypt(encrypted, key); System.out.println("Encrypted: "+encrypted); System.out.println("Decrypted: "+decrypted); } public static String xor_encrypt(String message, String key){ try { if (message==null || key==null ) return null; char[] keys=key.toCharArray(); char[] mesg=message.toCharArray(); BASE64Encoder encoder = new BASE64Encoder(); int ml=mesg.length; int kl=keys.length; char[] newmsg=new char[ml]; for (int i=0; i<ml; i++){ newmsg[i]=(char)(mesg[i]^keys[i%kl]); } mesg=null; keys=null; String temp = new String(newmsg); return new String(new BASE64Encoder().encodeBuffer(temp.getBytes())); } catch ( Exception e ) { return null; } } public static String xor_decrypt(String message, String key){ try { if (message==null || key==null ) return null; BASE64Decoder decoder = new BASE64Decoder(); char[] keys=key.toCharArray(); message = new String(decoder.decodeBuffer(message)); char[] mesg=message.toCharArray(); int ml=mesg.length; int kl=keys.length; char[] newmsg=new char[ml]; for (int i=0; i<ml; i++){ newmsg[i]=(char)(mesg[i]^keys[i%kl]); } mesg=null; keys=null; return new String(newmsg); } catch ( Exception e ) { return null; } }} ``` gives me: Encrypted: UBJdXVZUElBBRRFdVRRYWF5YFEFUUw== Decrypted: a nice cup of milk tea And this PHP code: ``` <?php $input = "a nice cup of milk tea"; $key = "12345"; $encrypted = XOR_encrypt($input, $key); $decrypted = XOR_decrypt($encrypted, $key); echo "Encrypted: " . $encrypted . "<br>"; echo "Decrypted: " . $decrypted . "<br>"; function XOR_encrypt($message, $key){ $ml = strlen($message); $kl = strlen($key); $newmsg = ""; for ($i = 0; $i < $ml; $i++){ $newmsg = $newmsg . ($msg[$i] ^ $key[$i % $kl]); } return base64_encode($newmsg); } function XOR_decrypt($encrypted_message, $key){ $msg = base64_decode($encrypted_message); $ml = strlen($msg); $kl = strlen($key); $newmsg = ""; for ($i = 0; $i < $ml; $i++){ $newmsg = $newmsg . ($msg[$i] ^ $key[$i % $kl]); } return $newmsg; } ?> ``` gives me: Encrypted: MTIzNDUxMjM0NTEyMzQ1MTIzNDUxMg== Decrypted: Wonder why both results are different. I must admit before that PHP is not my cup of tea. BTW, I use this for a toy project, so high security is not needed.

Original source