CodeIgniter and Hashing
Preamble
The concept of hashing in PHP is something that is ablaze across the internet. While these discussions typically include which algorithms to use and not to use. Some of them also include how-to's. In terms of CodeIgniter it does have a security helper. However, how this file achieves hashes is horrid, especially for new developers. It simply takes the input and runs it through PHP's hash() function. My helper file is designed to improve on the existing security helper.(All-be-it by-passing it).
File
The file name is hash_helper.php. This is to follow the naming conventions of CodeIgniter. The file in whole can be seen here.
First
The defining difference between my helper and the native security helper is the use of pseudo-random alphanumeric upper-lowercase salt creation.
if(!function_exists('generate_salt')){
function generate_salt($length = 10){
$source = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$i=0;
$salt = '';
while($i<$length){ $salt.=substr($source,rand(1,strlen($source)),1);
$i+=1;
}
return $salt;
}
}
As the GitHub link above explains, to change the length of a salt simply change the value of $length
. However, it is important that this parameter remains and is an integer. fortunately, this isn't the end of this file...
Second
Let's go ahead and create a keygen for this file, again this exists in the GitHub file. however, in the interest of saving space and simply having a naming convention that makes sense...
if(!function_exists('generate_key')){
function generate_key($length = 30){
return $this->generate_salt($length);
}
}
Expecting more? No need, this function merely exists so that the usage of generate_salt()
and generate_key()
are not confused.
Third and Final
As this tip says, it is about creating hashes:
if(!function_exists('generate_hash')){
function generate_hash($salt,$password,$algo = 'sha256'){
return hash($algo,$salt.$password);
}
}
So, for this file... the $salt
parameter is for the salt generated with generate_salt()
the $password
can be any string that needs to be hashed. The $algo
parameter needs to be a server supported algorithm.
and that is all. You have your salt, key, and hash to be stored in your user management. A follow-up tip will be made on how to use this file in a CodeIgniter, PDO, and MySQLi enviroment.
Again, to download this file visit the github link above.