i am trying to find out is there a javascript library out there that gives functionality for mcrypt_encrypt in php.
I am writing a function to access my api using javascript. i always encrypt and encode my parameters. This is the method i would like to have a js version of.
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;
}
This is the jquery version of the above request ive come up with but it always returns an invalid request. meaning the API fails to decrypt the request
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');
}
here is how i run the above function
var request={'controller':'user','action':'login','emailaddress':email,'password':pass};
queryAPI(request,function (d){console.log(d);});
on the server side api, here is how php decrypts the request
$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);
}