我试图找出是否有一个javascript库,为php中的mcrypt_encrypt提供了功能。
我正在编写一个使用javascript访问我的api的函数。我总是加密和编码我的参数。这是我希望有一个js版本的方法。
public function sendRequest($request_params)
{
//encrypt the request parameters
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
//create the params array, which will
//be the POST parameters
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $this->_app_id;
//initialize and setup the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$result = curl_exec($ch);
//json_decode the result
$result = @json_decode($result);
//if everything went great, return the data
return $result;
}
这是我提出的上述请求的jquery版本,但它总是返回无效请求。意味着API无法解密请求
var queryAPI = function (request_object,callback)
{
var app_key = 'sdffkjhdsjfhsdjkfhsdkj';
var app_secret = 'hfszdhfkjzxjkcxzkjb';
var app_url = 'http://www.veepiz.com/api/jsonp.php';
var enc_request = $.toJSON(request_object);
var ciphertext =encode64(Crypto.AES.encrypt(enc_request, app_secret, { mode: new Crypto.mode.ECB }));
$.post(app_url,{'app_id':app_key,'enc_request':ciphertext},
function (data)
{
console.log(data);
},'jsonp');
}
这是我如何运行上述功能
var request={'controller':'user','action':'login','emailaddress':email,'password':pass};
queryAPI(request,function (d){console.log(d);});
在服务器端api,这是php如何解密请求
$params = json_decode(trim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256, $app_secret, base64_decode( urldecode( $enc_request )), MCRYPT_MODE_ECB )));
//check if the request is valid by checking if it's an array and looking for the controller and action
if( $params == false || isset($params->controller) == false || isset($params->action) == false ) {
$result['success'] = 0;
$result['errormsg'] = "Request is not valid! ";
//echo the result of the API call
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/javascript');
$result=json_encode($result);
# JSON if no callback
if( ! isset($_GET['callback']))
exit( $result );
# JSONP if valid callback
if(is_valid_callback($_GET['callback']))
exit( "{$_GET['callback']}($result)" );
# Otherwise, bad request
header('Status: 400 Bad Request', true, 400);
}
答案 0 :(得分:1)
答案 1 :(得分:0)
好吧我用AES解决了这个问题,我发现总是(serverside)urldecode($ enc_request),因为base64'='会在发布到url时发生变化。我使用的教程是JavaScript and PHP Encryption – The Secret Handshake
显然我的问题是由一个有问题的encode64()javascript函数引起的,该函数返回了无效的base64字符串