Encrypt json serialized response

Hello,

I am creating rest api with json response for which i am serializing the data and rendering it as json. But i want to encrypt the json data before i send the response. If i do it with json_encode and exit the script i can simply encrypt but how is it possible with serialize data.

I need your help.

Please let me know if i didn’t make it clear or need more info.

Many thanks

// Use your own key obviously
$key = 'lamekey';

// Use your own data obviously
$data = ['my secret data'];

// Encode the array into JSON
$json = json_encode($data);

// Encrypt the JSON data
$result = \Cake\Utility\Security::encrypt($json, $key);

// Continue with whatever you need to do

A question would be why you’re encrypting data that you’re sending. I can think of three possibilities:

  1. You want to send data securely to a browser. But the browser will also need the decryption key, which you’ll presumably need to send it over the same channel, so if anyone can intercept the data, they can get the key too, and you’re not really any further ahead. Just use HTTPS.
  2. You want to send some bit of data to the browser that it sends back to you later. Unless it’s authentication details to be used in JWT, probably easier and more secure to save it in the server-side session?
  3. You want to send data securely to some other server that’s consuming an API you’re providing. Again, just use HTTPS.

Thanks for your solution but i am not using json_encode($data) function instead i am using RequestHandler to renderAs json and passing the data to _serialize which converts to json. But through this framework i couldn’t find way to encrypt while converting to json.

the apis are consumed through front-end scripting but it may open way for phishing as the attacker can consume the api in other app without authorization. this is why want to encrypt, please let me know the alternative.
Thanks

@FinlayDaG33k’s example used json_encode, but it shows how to encrypt any piece of data. The fact that the example is JSON encoded data is immaterial to how to encrypt things.

Sounds like what you’re using this for is JWT authentication? That’s the one exception that I allowed in my list… :slight_smile:

1 Like

Just a little sidenote, this can also be done by using something like a DHKE (“Diffie-Hellmann Key Exhange”) buuuuut that’s a whole other topic :stuck_out_tongue: