Salt Cryptography

Last three months ago, I made a single page web application to let users register their own team. As the password usually users fill in will make some inconvenience in our cyber ​​security competition, I took a service to send a email which including an automatic generation password. And what I do is adding salt in password to confirm the security.

So what's called salt?

In cryptography, a salt is random data that are used as an additional input to a one-way function that hashes a password or passphrase.

And a new salt is randomly generated for each password. In my apply page, the salt and the password are concatenated and processed with a cryptographic hash function, and the resulting output (but not the original password) is sent to users email while the salt and the original password is stored in a database.

Hashing allows for later authentication while defending against compromise of the plaintext password in the event that the database is somehow compromised. And in this way, the output password will be somehow entirely safe although the original password may be cracked.

All right, it is time to begin. In PHP, the code like this:

$length = 32;
$mode = 0;
switch ($mode) 
{
    case '1':
    $str = '1234567890';
    break;
    case '2':
    $str = 'abcdefghijklmnopqrstuvwxyz';
    break;
    case '3':
    $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    break;
    default:
    $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    break;
}
$pass = '';
$l = strlen($str) - 1;
$num = 0;
for($i = 0;$i < $length;$i++){
    $num = rand(0, $l);
    $a = $str[$num];
    $pass .= $a;
}

$saltLength = 6;
$salt = '';
for ($a = 0; $a < $saltLength; $a++) {
        $salt .= chr(mt_rand(97,122));    
}

echo 'Salt:' . $salt;
echo '<br>';
echo 'Original Password:' . $pass;  
echo '<br>';
// Simply add the salt to the end
echo 'Outping:' . md5(sha1($pass.$salt));

That's all. And next you can do what you want to do, maybe send the output password to users via email or some other things.

Remember that it is common for a web application to store in a database the hash value of a user's password. Without a salt, a successful SQL injection attack may yield easily crackable passwords. You can read more on wiki about the beneficial of the salt.

Have fun :D