How to create two way encode/decode methods using use-specific key - PHP?

Jason Silberman picture Jason Silberman · Apr 8, 2013 · Viewed 31.2k times · Source

I need two functions/methods, one to encode, one to decode. This is not for storing passwords. Each user will have a specific key/salt to encode the data.

This is how I would like it to work:

function encode($str, $key) {
    // something fancy
}

function decode($str, $key) {
    // something fancy
}

$key = $logged_in_user->get_key();
$plain = 'abc abc 123 123';
$encoded_data = encode($plain, $key);
// some_fancy_encrypted_data_that_is_really_cooooool
$decoded_data = decode($encoded_data, $key);
// abc abc 123 123

Another thing is that every time I use this function it needs to return the same thing every time I use the encode function with the same user key.

How would I do this??

Answer

rinchik picture rinchik · Apr 8, 2013
$myVarIWantToEncodeAndDecode

Define key (salt, broth etc..): $key = "#&$sdfdfs789fs7d";

To encode:

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $myVarIWantToEncodeAndDecode, MCRYPT_MODE_CBC, md5(md5($key))));

To decode:

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

Note: mcrypt_decrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.