Am I using CRYPT_BLOWFISH in PHP correctly?

I am going to use this for a user password system, but first I want to make sure that I am doing it correctly. Here is my test code:

  function generateBlowfishSalt () {
     $ chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./';
     $ numChars = strlen ($ chars);
     $ salt = '';

     for ($ i = 0; $ i <22; ++ $ i) {
         $ salt. = $ chars [mt_rand (0, $ numChars - 1)];
     }

     return $ salt;
 }

 $ password = 'foo';
 $ salt = generateBlowfishSalt ();
 $ hash1 = crypt ($ password, '$ 2a $ 12 $'. $ salt);
 $ hash2 = crypt ($ password, $ hash1);
 $ compare = ($ hash1 == $ hash2);

 printf ('password:% s </br>', $ password);
 printf ('salt:% s </br>', $ salt);
 printf ('hash1:% s </br>', $ hash1);
 printf ('hash2:% s </br>', $ hash2);
 printf ('compare:'. $ compare); 

Here is an example output:

  password: foo
 salt: MYVJ32OqLcMGBar3pUa.0S
 hash1: $ 2a $ 12 $ MYVJ32OqLcMGBar3pUa.0OTRwv6UX0bcxnSmheKOcqjvqvCrM / p2q
 hash2: $ 2a $ 12 $ MYVJ32OqLcMGBar3pUa.0OTRwv6UX0bcxnSmheKOcqjvqvCrM / p2q
 compare: 1 

My main questions are:

  • Am I correctly generating 22 character salt? Some implementations I've seen use base64_encode() to generate salt. Is there any need to do this?

  • Is it correct to store the integer value of $hash1 in the database and not to store a separate salt value, since $hash1 will have a salt in it and that is all I need to check the password?

  • On the PHP crypt() document page, the CRYPT_BLOWFISH example has the final $ argument salt (this this: '$2a$07$usesomesillystringforsalt$' ). But in all the examples I've seen, nobody uses the final $ . It's not obligatory?

thanks

+4
source share
1 answer

You make salt right. It just has to be random. There are many different methods for randomly generating this. Some people use it in addition to dates, etc. In addition, longer salts are not very important, as they will be cut off in any case. It requires a certain length, at least in terms of crypt (). Therefore, if a little extra supplement makes you feel better, go for it.

Suppose you store salt in a database. At first it was difficult for me to understand this. The whole point of salt is only to take longer to rainbow pin passwords with a huge list of possible passwords. In addition, the fix also helps with two or more passwords that are the same, which should happen. If so, the hashes will still be different due to random salts.

As for crypt (), keep testing it until it looks and is the same length as the PHP-DOC for PHP, but yes, it looks right.

0
source

Source: https://habr.com/ru/post/1413362/


All Articles