【发布时间】:2015-04-10 23:25:05
【问题描述】:
我想将“消息”作为 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 **
我不能用这些标志发布它,这就是我拍照片的原因。
【问题讨论】:
-
如果不加密字符串,json_decode 是否有效?
-
不应该是
stringify是JSON.stringify? -
我希望这不是您的应用程序的真正设计方式。在与加密数据相同的 AJAX 请求中发送密钥是没有意义的。如果有人得到加密的消息,他们也会得到密钥,所以他们可以自己解密。
-
很明显你的解密码有问题。请edit您的问题添加一个可重现的问题示例。
-
@Barmar 密钥将使用 RSA 加密,JSON.stringify 不是问题。一切都适用于普通字符串。但我不想加密和解密每一个字符串,因为它花费了太多时间。
Artjom B. :我添加了解密方法。
感谢您的回答!