Java和PHP中的XOR密码:不同的结果

假设我有一个简单的文字, 一杯漂亮的奶茶 ,它将与密钥12345进行XOR密码加密。

这个Java代码:

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; } }} 

给我:

加密:UBJdXVZUElBBRRFdVRRYWF5YFEFUUw ==

解密:一杯好喝的奶茶

这个PHP代码:

 <?php $input = "a nice cup of milk tea"; $key = "12345"; $encrypted = XOR_encrypt($input, $key); $decrypted = XOR_decrypt($encrypted, $key); echo "Encrypted: " . $encrypted . "
"; echo "Decrypted: " . $decrypted . "
"; 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

给我:

加密:MTIzNDUxMjM0NTEyMzQ1MTIzNDUxMg ==

解密:

不知道为什么两个结果都不同。 我必须承认,PHP不是我的一杯茶。

顺便说一句,我将它用于玩具项目,因此不需要高安全性。

在PHP加密方法中,您有以下代码:

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

但是, $msg没有在任何地方定义。 那应该是$message