Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to encrypt/decrypt a json string

Tags:

json

php

mysql

I have a webserver running mysql and php which sends data to a json string.

I have a second webserver which reads the data and then displays it.

Everything works fine at the moment.

I need to add some sensitive data into the string, so I was wondering what is the best way to encrypt/decrypt the json using php?

Can someone help!?

like image 867
Steve Avatar asked Feb 20 '12 17:02

Steve


3 Answers

I always liked MCRYPT

//Key
$key = 'SuperSecretKey';

//To Encrypt:
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, 'I want to encrypt this', MCRYPT_MODE_ECB);

//To Decrypt:
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB);

If that's something you're looking for. It'll treat the JSON as a string and then after you decrypt it you'll have to do your json_decode() or whatever it is you're doing.

like image 174
romo Avatar answered Nov 15 '22 15:11

romo


I bet the best way is use SSL (HTTPS) and I recommend you to read the OWASP Guide and especially the How-To section.

like image 37
alexsuslin Avatar answered Nov 15 '22 16:11

alexsuslin


It really depending on how sensitive the data are. However from my experience a simple php encryption usually do the trick. I would usually encrypt the sensitive fields in the json data fields before encoding it to a json string.

Here's the code for the encryption part.

$key = 'password to (en/de)crypt'; $string = ' string to be encrypted '; // note the spaces

To Encrypt:

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

To Decrypt:

$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

However, you should always hash (MD5, SHA1) passwords, preferably with some salt.

like image 26
iewnait Avatar answered Nov 15 '22 16:11

iewnait