LonelyWebCrawler
LonelyWebCrawler

Reputation: 2906

Why does my PHP Blowfish encryption produce such weird results?

After hearing that MD5 isn't safe for password storage (MySQL), I decided to use PHP's crypt() with Blowfish (tell me if you know any better algorithms). So I randomly generate a 32-character salt and encrypt a given string. Here's the code:

//Some variables
$text = $_POST['text'];
$salt = "";
$length = 32;
$chars = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ123456789";
$numchars = strlen($chars);

//Random string generation
for ($i=0; $i <= $length; $i++)
{
    $index = mt_rand(0, $numchars-1);
    $salt .= $chars[$index];
}

//Encrypt $text using Blowfish
$encrypted = crypt($text, "$2a$12$" . $salt . "$");

The results I've been getting have been really weird... with some configurations much like this one the encrypted result contained multiple dollar sings $ in a row. With this code, $encrypted-- the result-- actually contains the salt it was given, and $encrypted is preceded by the Blowfish indicator $2a$.

My version of PHP supports Blowfish, by the way. Here's an example of a result:

Encrypted "hello"
$encrypted: "$2a$12$az1aszWXtzw9R7Y4Iv97KeUPwcPG9pgx/CAW42F/67X64l60lMvGa"
$salt:             "az1aszWXtzw9R7Y4Iv97KmM6miSXnecKB"

What am I doing wrong? Thanks for your help.

EDIT : Whoa, I just thought of something: Shouldn't I always use the same salt, or should I randomly generate one and store it with each user account in MySQL?

Upvotes: 2

Views: 2035

Answers (2)

neevan
neevan

Reputation: 31

You should use randomly generate one and store it with each user account in MySQL Because it is more safer than using the same salt.

Reason is that the salt which is used can be always the 22 characters and the remaining $2a$12$ totally first 28 char which specify by the salt and the rest will be an hash of your password.

Upvotes: 0

Mike Purcell
Mike Purcell

Reputation: 19979

Check out https://www.php.net/crypt, example #3 "Using crypt() with different hash types". In the example output it shows that the salt strings are also part of the encrypted value, so your issue with the salt being part of the encryption appears to be by design.

Upvotes: 2

Related Questions