I'm trying to generate salt using Mcrypt's mcrypt_create_iv()
, but it doesn't seems to work and I'm getting errors.
Here is my code:
<?php
$salt= substr(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM))(mt_rand()),0,22);
echo $salt;
?>
I'm trying to generate salt using Mcrypt's mcrypt_create_iv()
, but it doesn't seems to work and I'm getting errors.
Here is my code:
<?php
$salt= substr(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM))(mt_rand()),0,22);
echo $salt;
?>
$salt = substr( mcrypt_create_iv(16, MCRYPT_DEV_URANDOM), mt_rand( 0, 22 ) );
you have some syntax errors
This cannot work, you use mcrypt_create_iv()
to get random bytes, but those cannot be used for hashing with BCrypt. The problem is, that mcrypt_create_iv returns binary data, while BCrypt expects a salt with characters of a given alphabet. You would have to encode your salt to this alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
. The function mt_rand()
is of no use here.
PHP 5.5 will have it's own functions password_hash() and password_verify() ready, to simplify generating BCrypt password hashes. I strongly recommend to use this excellent api, or it's compatibility pack for earlier PHP versions. The usage is very straightforward:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);