Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scarstens/5470954 to your computer and use it in GitHub Desktop.
Save scarstens/5470954 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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