How to store raw binary data hashes in MySQL?

I want to store hashed passwords in MySQL, I use PHP:

<?php
    $salt = '!£$%^&*()#';
    $username = 'abc';
    $password = '123';
    $hash = hash('sha1', $username . $salt . $password, true);
?>

The true parameter in hash () returns the value as raw binary data. But I do not understand what this means. How to store it correctly in MySQL?

+3
source share
4 answers

I have found a solution.

Regular (hexadecimal) hashes sha1 () are always CHAR (40). When you return the hash as raw binary data in php, it returns the string as CHAR (20), saving 50% of the database space, but representing the same value. This is due to the fact that 2 characters of the hex can be compressed into 1 character, thus halving the space needed.

, CHAR (20) * _bin.

+4

hash() , -:

  • . -, , sha1.
  • , .

. , . , , -.

+3

MySQL, BINARY(16), 16 , VARBINARY(32), 32 BLOB , (, BLOB 64K, LONGBLOB 4G).

+1

"" , AFAIK, addslashes().

:.

$hash = hash('sha1', $username . $salt . $password, true);
$query_safe_hash = addslashes($hash);
$query_safe_username = addslashes($username);
$query = "INSERT INTO DBTable(username, password) VALUES ('$query_safe_username', '$query_safe_hash')";
mysql_query($query) or die("Failed to store credentials!");

: , , . -

$salt = generate_random_salt();
$query_safe_hash = addslashes($salt) . addslashes(hash('sha1', $salt . $username . $password, true);

Then, in order to verify the user credentials, you retrieve the stored hash, delete slashes and remove the known salt length from the beginning of the stored hash and use the same salt to generate a hash of the provided credentials, and then compare. This helps to strengthen your hash algorithm against various cryptanalytic attacks (in particular, differential cryptanalysis).

-1
source

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


All Articles