Encryption is easy. Don’t be lazy.

Encryption is easy. Don’t be lazy.

I was working on an internal app for our support staffs. It’s a web app that connects to iFormBuilder through the public API. To use it, one will have to get the API key, secret, etc., from the server.

It’s a very light-weight app so I didn’t want to setup another database. So I thought, yeah, it’s internal anyway, let’s just put the key, secret, and server id in cookies.

So I went about finishing the app with just that. 3 parameters saved in cookies.

All is good.

Except not. A voice came into my head as I walk down the hall.

“Sze, are you sure? Is this going to be that one other thing that you will regret later? Come on! Hold yourself to a higher standard!”

So I walked back to my desk, put headphone on. Shortly after, the following is in place:

$clientId = $_REQUEST['clientId']; $clientSecret = $_REQUEST['clientSecret']; 
$serverId = $_REQUEST['serverId'];$token = "$clientId::$clientSecret::$serverId"; 
$key = '...';
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $token, MCRYPT_MODE_CBC, md5(md5($key))));setcookie('apiToken',$encrypted);

And on the other side:

$key = '...';
$encryptedToken = $_COOKIE['apiToken'];
$decryptedToken = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encryptedToken), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
$tokens = explode('::',$decryptedToken);$global_clientKey = $tokens[0]; $global_clientSecret = $tokens[1]; $global_serverId = $tokens[2];

And that’s it.

This post is to remind myself that Encryption is easy. Don’t be lazy.