0

I am testing to hash using sha1 and i have inserted a row :

insert into tbl_user (username, password, email) values ('maysam', sha1('21lf892'), 'gerdakan.sa@gmail.com');

and when i want to select a row like using :

select * from tbl_user where password = sha1('21lf892');

and result is :

 Empty set (0.00 sec)

but if i try to select using like username :

select * from tbl_user where username  = 'maysam';

+----+----------+--------------------------------+-----------------------+
| id | username | password                       | email                 |
+----+----------+--------------------------------+-----------------------+
|  2 | maysam   | dd989b1d1d67c6e706852024ccb6a1 | gerdakan.sa@gmail.com |
+----+----------+--------------------------------+-----------------------+

what is the problem? why it can't select ?( i have tested hashing and selecting using md5 and sha2....

senaps
  • 1,374
  • 1
  • 14
  • 25

1 Answers1

2

A sha1 hash is 160bits, i.e. 40 characters when formatted in this way.

Your table appears to have the length of the password column set to something smaller than this, so the data is truncated on insert and is no longer equal to sha1('21f892').

As an aside, unsalted SHA1 hashes is a very weak way to store passwords. Prefer something like bcrypt or scrypt.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • my password field is a varchar (50).... what's the best filed type for a password? this is test, i would hash sha1 for beter security... – senaps Feb 05 '16 at 16:39
  • @senaps: If you are storing SHA1 hashes, use `char(40)`. – gen_Eric Feb 05 '16 at 16:40
  • @senaps: If you're using PHP, have a look at [`password_hash()`](http://php.net/password_hash). It uses bcrypt to hash the passwords and is much safer than SHA1. For this, you'll want `varchar(255)` for `PASSWORD_DEFAULT` (or `char(60)` for `PASSWORD_BCRYPT`). – gen_Eric Feb 05 '16 at 16:41