Create a gist now

Instantly share code, notes, and snippets.

This is the example I built while learning how to properly protect password before they are stored in the database. While hashing passwords is safer, some passwords are used for "3rd party tools" and therefore can't be hashed because they need to be "unencrypted" and sent to the 3rd party service. In my case, we were building an connector betwee…
<?php
//This example encrypts and decrypts a password
//it is a good use case for a "php class file" because the __FILE__ is constant for the key
//*additional security can be added by storing or defining a unique key per website
//using __FILE__ exmaple for class files
$pass = 'samplepassword123!';
echo 'Password: '.$pass.'<br />';
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, sha1(basename(__FILE__), TRUE), $pass, MCRYPT_MODE_ECB);
echo 'Encrypted Pass: '.$encrypted.'<br />';
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, sha1(basename(__FILE__), TRUE), $encrypted, MCRYPT_MODE_ECB);
echo 'Decrypted Pass: '.$decrypted.'<br />';
//increase security with a custom hash key per websites/application
//limit your key to 24 characters
define('MYSECRETKEY', '123456789012345678901234')
$pass = 'samplepassword123!';
echo 'Password: '.$pass.'<br />';
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, MYSECRETKEY, $pass, MCRYPT_MODE_ECB);
echo 'Encrypted Pass: '.$encrypted.'<br />';
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, MYSECRETKEY, $encrypted, MCRYPT_MODE_ECB);
echo 'Decrypted Pass: '.$decrypted.'<br />';
?>
@scarstens
Owner

I had a dumb moment there... FILE is the complete path and moving the file between servers will break the password field (to fix simply set a new password) assuming that your storing the encrypted password in a DB or XML file.

@scarstens
Owner

think that basename(FILE) would do the trick for a good class based constant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment