Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

php - How to generate a good salt - Is my function secure enough?

Here's the function I'm using to generate random salts:

function generateRandomString($nbLetters){
    $randString="";
    $charUniverse="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for($i=0; $i<$nbLetters; $i++){
       $randInt=rand(0,61);
        $randChar=$charUniverse[$randInt];
        $randString=$randomString.$randChar;
    }
    return $randomString;
}

This is for a non commercial website. It's only used to generate the salt (to be stored in the db and used along with the user submitted pw for hashing).

Is this appropriate? Should I use a larger subset of characters, and if so is there an easy way to do that in PHP?

question from:https://stackoverflow.com/questions/4099333/how-to-generate-a-good-salt-is-my-function-secure-enough

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are hashing passwords, you should use a modern hashing algorithm that does not require you to generate your own salt. Using weak hashing algorithms presents a danger to both you and your users. My original answer was written eight years ago. Times have changed, and password hashing is a lot easier now.

You should always use built in functions to hash/check passwords. Using your own algorithms at any point introduces a huge amount of unnecessary risk.

For PHP, consider using password_hash(), with the PASSWORD_BCRYPT algorithm. There is no need to provide your own salt.

Below is my original answer, for posterity:


Warning: The following implementation does not produce an unpredictable salt, as per the documentation for uniqid.

From the php sha1 page:

$salt = uniqid(mt_rand(), true);

This looks simpler, and more effective (since each is unique) than what you have proposed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...