Created
January 13, 2014 02:33
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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