我需要在JavaScript中使用AES加密数据,然后将其发送到我们的服务器以供PHP解密。是的,我知道,这是不安全的,人们将能够解密它 - 我们使用它作为一种方式,使人们更难以反转和反混淆我们的代码。
我正在使用这个库:
https://github.com/Dexus/js-mcrypt/blob/master/mcrypt.js
我正在使用Rijndael-128和cbc用于AES,块大小为16.我已经验证了这个值对于PHP和& JS。我可以在JS和PHP中使用相同的密钥,IV和rijndael-128 / cbc加密和解密字符串,但由于某种原因,PHP无法解密JS的输出。有人可以帮帮我,指出我做错了吗?
以下是代码:
<script type="text/javascript" src="Serpent.js"></script>
<script type="text/javascript" src="rijndael.js"></script>
<script type="text/javascript" src="mcrypt.js"></script>
<?php
function hex2bin($text)
{
return pack('H*', $text);
}
echo mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
echo "->" . mcrypt_get_key_size('rijndael-128', 'cbc');
$ciphertext_hex = "86B83EB77A6D40CACABAD79F0EA335E8454B1A9974B2D89D43B3EE0E25B649FB19EB88DF7A4490F9AB05F44701F081DD";
$ciphertext = hex2bin($ciphertext_hex);
$key_hex = "31323334353637383930313233343536";
$key = hex2bin($key_hex);
$iv = "1234567890123456";
$cipher = "rijndael-128";
$mode = "cbc";
$plaintext = mcrypt_decrypt($cipher, $key, $ciphertext, $mode, $iv);
echo "<h2>Enc in JS, Dec in PHP</h2>Encrypted: $ciphertext<br /><br />\n\nDecrypted: $plaintext";
echo "<h2>Enc/Dec in PHP</h2>Encrypted: " . ($encd = mcrypt_encrypt($cipher, $key, "this is the message I want to encode", $mode, $iv)) . "<br><br>\n\n";
echo "Decrypted: " . mcrypt_decrypt($cipher, $key, $encd, $mode, $iv);
?>
<div id='js_results'></div>
<script>
var hexdigits='0123456789ABCDEF';
var hexLookup=Array(256);
for(var i=0;i<256;i++)
hexLookup[i]=hexdigits.indexOf(String.fromCharCode(i));
var bin2hex=function(str){
var out='';
for(var i=0;i<str.length;i++)
out+=hexdigits[str.charCodeAt(i)>>4]+hexdigits[str.charCodeAt(i)&15];
return out;
}
var hex2bin=function(str){
var out='';
var part=-1;
for(var i=0;i<str.length;i++){
var t=hexLookup[str.charCodeAt(i)]
if(t>-1){
if(part>-1){
out+=String.fromCharCode(part|t);
part=-1;
}else
part=t<<4;
}
}
return out;
}
var cipher = "<?php echo $cipher; ?>";
var mode = "<?php echo $mode; ?>";
var key = hex2bin("<?php echo $key_hex; ?>");
var iv = "<?php echo $iv; ?>";
var msg = "this is the message I want to encode";
var enc = mcrypt.Encrypt(msg, iv, key, cipher, mode);
var enc_hex = bin2hex(enc);
var enc_hex_static = "<?php echo $ciphertext_hex; ?>";
var enc_static = hex2bin(enc_hex_static);
var dec = mcrypt.Decrypt(enc_static, iv);
document.getElementById('js_results').innerHTML = "<h2>Enc in JS</h2>Encrypted: " + enc + "<br><br>\n\nEnc in Hex: " + enc_hex + "<br><br>\n\nDec: " + dec;
</script>
答案 0 :(得分:0)
将两个字符串转换为使用相同的字符编码,如utf8
答案 1 :(得分:0)
解决方案的一部分是解决为什么很早就会出现编码错误。例如:密文上的hex2bin之后的字符串,与js / php进行比较。我使用不同的函数来测试输出(hex2bin的不同实现)但我无法确定特定位置的错误,而不是你的实际密文在js / php之间是不同的。我试着找一些时间来弄清楚如何解决这个问题。