1
function password_encrypt($password) {
    $hash_format = "$2y$10$";   // Tells PHP to use Blowfish with a "cost" of 10
    $salt_length = 22;        // Blowfish salts should be 22-characters or more
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}

function generate_salt($length) {
    // Not 100% unique, not 100% random, but good enough for a salt
    // MD5 returns 32 characters
    $unique_random_string = md5(uniqid(mt_rand(), true));     
    // Valid characters for a salt are [a-zA-Z0-9./]
    $base64_string = base64_encode($unique_random_string);    
    // But not '+' which is valid in base64 encoding
    $modified_base64_string = str_replace('+', '.', $base64_string);      
    // Truncate string to the correct length
    $salt = substr($modified_base64_string, 0, $length);
    return $salt;
}    

Do you guys thnk this is secure? What could have been done differently? What's maybe easier to use to secure a password and hash it?

5
  • 2
    password_hash() and password_verify() does the trick and are easy to use and very secure, compared to what you just did. Commented Nov 29, 2016 at 9:06
  • @MasivuyeCokile Easy to use? Where would i have to put it in my code? or how would you write it? :/ Commented Nov 29, 2016 at 9:07
  • <?php $password = "YourStrongPassword"; $hash = password_hash($password,PASSWORD_DEFAULT); //hashing the password. $pass2 = $password; //this could be from a userinput // verifying the hash. if(password_verify($pass2,$hash)){ echo "passwords match"; }else{ echo "passwords does not match"; } ?> Commented Nov 29, 2016 at 9:32
  • 1
    You can check the manual for more about password_hash() and password_verify() Commented Nov 29, 2016 at 9:35
  • sha1 with a 10 characters salt is much enough .... Commented Nov 29, 2016 at 10:15

1 Answer 1

3

Blowfish itself is already really secure. One thing: don't do too much hashing etc. to generate a salt. Also, why not make it easier and use password_hash?

http://php.net/manual/en/function.password-hash.php

Example:

echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT)."\n";

And to check a password:

if (password_verify($password_nonhashed, $password_hashed)) {

You don't need to hash a salt too much with blowfish. Just use sha1 hash for a salt if you really don't want to use password_hash.

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt.