Skip to content

Instantly share code, notes, and snippets.

@newscloud
Created January 13, 2014 02:33
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 newscloud/8393857 to your computer and use it in GitHub Desktop.
Save newscloud/8393857 to your computer and use it in GitHub Desktop.
Code to encrypt and store salted usernames and passwords in PHP using MCrypt from http://jeffreifman.com/filtered-open-source-imap-mail-filtering-software-for-php/
public function createCredentials($username,$password) {
$salt = $this->random_string(4,4).'::'.$this->random_string(4,4);
$salts = explode('::',$salt);
$str = $salts[0].'::'.$username.'::'.$password.'::'.$salts[1];
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$account_salt = Yii::app()->params['account_salt']; // stored in your ini file somewhere on your server
mcrypt_generic_init($td, $account_salt, $iv);
$encrypted_data = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$result = array($salt,$encrypted_data);
return $result;
}
public function getCredentials($cred) {
$account_salt = Yii::app()->params['account_salt'];
$cred = base64_decode($cred);
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $account_salt, $iv);
$result = mdecrypt_generic($td,$cred);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$cred = explode('::',$result);
array_shift($cred);
array_pop($cred);
return $cred;
}
public function random_string($num_characters=5,$num_digits=3)
{
// via http://salman-w.blogspot.com/2009/06/generate-random-strings-using-php.html
$character_set_array = array();
$character_set_array[] = array('count' => $num_characters, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
$character_set_array[] = array('count' => $num_digits, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment