假设我有一个纯文本a nice cup of milk tea ,它将使用密钥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 . "<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;
}
?>
给我:
加密:MTIzNDUxMjM0NTEyMzQ1MTIzNDUxMg==
解密:
想知道为什么两个结果不同。我必须承认,PHP 不是我喜欢的。
顺便说一句,我将它用于玩具项目,因此不需要高安全性。