我想把“消息”作为json数据发送给php。但是“消息”必须是一个字符串。如果我在Javascript中“串化”我的json数据,并用"CryptoJS.AES.encrypt“对它们进行加密,我不能在PHP中获得单个内容,因为"json_decode”总是返回NULL。
我使用了"json_last_error“,它返回了3。当我用"utf8_encode”对它进行编码并对它们进行json_encode时,它返回0。
"mcrypt_decrypt“是PHP AES解密器。
我真的不知道该怎么办。请提前帮助我,谢谢!
//JAVASCRIPT
var encrypted = CryptoJS.AES.encrypt(
JSON.stringfy({'message':'message','messageA':'messageA','messageB':'messageB'}),
key512Bits500Iterations, {iv:iv});
var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
var iv_base64 = encrypted.iv.toString(CryptoJS.enc.Base64);
var key_base64 = encrypted.key.toString(CryptoJS.enc.Base64);
$.ajax({
url: 'http://localhost/workspace/messageAppl.php',
type: 'POST',
data: {
'data_base64':data_base64,
'iv_base64':iv_base64,
'key_base64':key_base64 //key_base64 will be encrypted with RSA
},
success: function(data){
alert(data);
},
error: function(){
alert('Index-Error');
}
});
// PHP
// I can get the jsonString but I can't get the single message like 'message', 'messageA' or 'messageB'
...
//Decryption in PHP
public function jsMessage($data_base64, $iv_base64, $key_base64){
$data_enc = base64_decode($data_base64); // data_base64 from JS
$iv = base64_decode($iv_base64); // iv_base64 from JS
$key = base64_decode($key_base64); // key_base64 from JS
$plaintext = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $data_enc, MCRYPT_MODE_CBC, $iv ), "\t\0 " );
return $plaintext;
}
$json_string = aes_decrypt($_POST['data_base64'], $_POST['iv_base64'], $_POST['key_base64']);
// json_decode returns NULL but WHY?
$array=json_decode($json_string);
$message=$array->message
$messageA=$array->messageA
$messageB=$array->messageB
**Edit 1**
The error message I get is:
**"Control character error, possibly incorrectly encoded"**
but the Json which I get in php after the decryption is valid:
{"message":"blablabalbalbalaballab","messageA":"blablabalbalbalaballab" ,"messageB":"blablabalbalbalaballab"}为了确保我已经一次又一次地测试了json,here
**编辑2**

我不能把它贴上这些标志,这就是为什么我拍了一张照片。
发布于 2015-09-17 18:46:57
the user notes on mcrypt_decrypt()有答案
似乎mcrypt_decrypt使用空值('\0')填充返回字符串,以填充到n*块大小
$json = rtrim($json, "\0");发布于 2015-04-11 08:17:52
看起来您正在对加密的json字符串进行base64编码。然而,在尝试解密之前,您并没有在您的PHP示例中对其进行base64解码。
另外,如果您的解密函数是mcrypt_decrypt,那么您传递的参数是错误的,它需要是mcrypt_decrypt($cipher,$key,$data,$mode,$iv)。
编辑:更多信息
看起来你正在对你在ajax调用中传递的其他值进行base64编码,但是在你的例子中不要在php端解码它们,你也需要这样做。
发布于 2015-04-12 22:29:16
说明
场景:在JS中,我使用cryptojs加密jsonString。在PHP中,我用"mcrypt_decrypt“来解密它。
但是我在解密后在php中得到的JsonString最后有一些有趣的字符。
只有当我复制var_dump()的输出并将其粘贴到集成开发环境中(即notepad++、eclipse等)时,我才能看到这些字符。
解决方案
我只需将最后一个花括号后面的12个不可见字符子串,然后它就行了,。我希望它能帮助一些人。
json_decode(substr( $json, 0, strlen( $jsonString)-12));
编辑
最好使用这个:
$strPad = ord($json[strlen($json)-1]);
$n_data = substr($json, 0, -$strPad);
$row=json_decode($n_data );大于
json_decode(substr( $json, 0, strlen( $jsonString)-12));所以你不需要像我一样计算你要删除的点数。
https://stackoverflow.com/questions/29572158
复制相似问题