簡體   English   中英

JSON在JavaScript中解密在PHP中加密

[英]JSON decrypt in JavaScript encrypt in PHP

我正在用PHP加密這樣的JSON文件:

0: {ID: 0, NAME: "London", REGION: "ENGLAND", …}
1: {ID: 1, NAME: "Rome", REGION: "ITALY", …}

在JS AES中的PHP解密中使用此庫加密

function cryptoJsAesEncrypt($passphrase, $value){
$salt = openssl_random_pseudo_bytes(8);
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
    $dx = md5($dx.$passphrase.$salt, true);
    $salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv  = substr($salted, 32,16);
$encrypted_data = openssl_encrypt(json_encode($value), 'aes-256-cbc', $key, true, $iv);
$data = array("ct" => base64_encode($encrypted_data), "iv" => bin2hex($iv), "s" => bin2hex($salt));
return json_encode($data);
}

我可以輕松地在PHP中加密並使用128位密鑰將數據寫入服務器(寫入JSON文件)

$key = "TjWnZq4t7w!z%C*F";
$ForecastArray_crypt= cryptoJsAesEncrypt($key, $ForecastArray);
file_put_contents('ukforecastlist_example_crypt.json', $ForecastArray_crypt);

問題是,當我嘗試使用調用在JavaScript中解密時

var ukforecastlist_decrypt = JSON.parse(CryptoJS.AES.decrypt(myjson.ct, "TjWnZq4t7w!z%C*F", {format: CryptoJSAesJson}).toString(CryptoJS.enc.Utf8));

控制台返回:

Uncaught SyntaxError: Unexpected token V in JSON at position 0
at JSON.parse (<anonymous>)
at Object.parse (core_uk.js:33)
at Object._parse (aes.js:30)
at Object.decrypt (aes.js:31)
at Object.decrypt (aes.js:25)
at <anonymous>:1:54

其中V確實是myjson.ct的首字母。

我究竟做錯了什么? 我確實使用jQuery獲得了JSON,並將其解析並存儲在myjson變量中。

解決了。 我現在正在使用這個簡單的PHP類:

https://github.com/henrya/projects/blob/master/JsEncode/jsencode.class.php

我可以使用以下方式在PHP中進行編碼:

$json_data = json_encode($myArray);

$d = new jsEncode();

$myArray_enc = $d->encodeString($json_data,$key);

並使用以下代碼在JS中解碼:

var myArray_decoded = JSON.parse(jsEncode.encode(myArray_enc,key));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM