-3

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;
?>
timss
  • 9,982
  • 4
  • 34
  • 56
hadi
  • 21
  • 5

2 Answers2

1
$salt = substr( mcrypt_create_iv(16, MCRYPT_DEV_URANDOM), mt_rand( 0, 22 ) );

you have some syntax errors

Danijel
  • 12,408
  • 5
  • 38
  • 54
  • not working in getting this error Fatal error: Call to undefined function mcrypt_create_iv() in /root/phptest/blowfish.php on line 4 – hadi May 16 '13 at 22:25
  • sorry not working ether getting this error Fatal error: Call to undefined function mcrypt_create_iv() in /root/phptest/blowfish.php on line 4 – hadi May 16 '13 at 22:28
1

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);
martinstoeckli
  • 23,430
  • 6
  • 56
  • 87