Hello Everyone! today i will show you how to hash passwords in PHP the right way. Passwords should be never stored in the database in raw form. It should be properly hashed. Hashing is the random process/function/ method to convert a piece of text into short fixed length which represents or identify the original text. It is an irreversible method that means the hash cannot be converted back to original text.
Securing your website from hackers is of utmost importance, but it is necessary to protect the important credentials of users in the website.
The MD5 algorithm is a widely used hash function producing a 128-bit hash value. It is widely used but it suffers from many vulnerabilities like hash collision, and quite weak. Many high end machines can brute-force these MD5 passwords in billion hashes per second. Weak passwords like password123/letmein/1234 can be easily cracked using rainbow tables/dictionary attacks ( where a user already hashes a wordlist of common passwords and searches through them ).
SHA256/512 are quite strong which generates an almost-unique, fixed size 256-bit (32-byte) hash. And with hash salts it would be the perfect thing to do.
Hash Salts are randomly generated strings that is used(mixed with the original text) in order to strengthen and unique hashes for the same text.
<?php $salt = uniqid(rand()); // generate random string $text = "hey this is text"; // text to be hashed $hash = crypt($text,'$5$rounds=5000$'.$salt.'$'); // crypt function, default rounds are 5000 and max , rounds=n determines how many times the hashing loop should be executed $verify = crypt($text,$hash); // in order to verify or match use the full hash echo $hash; echo " ".$verify; ?>
Well SHA-256 hash with a 16 character salt starting with $5$. If the salt string starts with “rounds=<N>$”, the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
you need to have the same salt that was used up in generating the hash. so in order to verify hash, we use the previously generated hash as salt.
If you want the function to generate the salt and hash, simply use.