Wednesday, March 19, 2014

One Way Encryption with Crypt Function and Salt

This tutorial shows how to hash passwords with random string as salt using Blowfish algo and PHP's function Crypt.
You should test this script at:
http://localhost/index.php?pass=secret&username=my_username.

<html>
 <head>
  <meta charset="utf-8">
 </head>
 <body>

<?php
function generateRandomString() {
 return substr(sha1(mt_rand()), 0, 22);
}

$password = $_REQUEST['pass'];
$username = $_REQUEST['username'];
$salt_1st_part = '$2a$05$';
$salt_2nd_part = generateRandomString();

if (CRYPT_BLOWFISH == 1) {
 $full = crypt($password, $salt_1st_part . $salt_2nd_part . '$');
 $databaseValue = substr($full, 7);

 $sql = "INSERT INTO `users` (`id` ,`username` ,`pass`) VALUES (NULL ,'$username','$databaseValue');";
 $query = mysql_query($sql);
 usleep(1000);
 $sql_select = "<p>run this query in phpMyAdmin to get user data <code>SELECT * FROM `users` WHERE 
   `username` = '$username' 
   AND 
   `pass` = '$databaseValue'</code></p>";
 echo $sql_select;
} else {
 die('Please upgrade PHP');
}
?>
 </body>
</html>

Don't alter green highlighted line unless you familiar with crypt() function and CRYPT_BLOWFISH constant.

Finally the MySQL table
CREATE TABLE IF NOT EXISTS `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(128) NOT NULL,
 `pass` varchar(128) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;
As you can see there is no salt column.

No comments:

Post a Comment