CHAR vs VARCHAR for password security

2019-07-02 12:43发布

Are there any benefits of CHAR over VARCHAR for storing passwords?

I have hunted high and low but can't find anything on this.

I ask because I have been told to use CHAR for passwords and am intrigued as to why.

标签: sql char
2条回答
甜甜的少女心
2楼-- · 2019-07-02 13:16

Do your passwords have a max length constraint? If they do, you should have no need for varchar.

In any case, if you are storing passwords, you should be hashing them and storing the hash. Many hashing algorithms hash to a fixed size so I don't think char should be an issue here. Just allocate the appropriate amount of characters.

Whatever you do, make sure you hash them!

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-02 13:33

There is no difference in security. The difference is in the storage mechanism.

From the MySQL manual:

The following table illustrates the differences between CHAR and VARCHAR by showing the result of storing various string values into CHAR(4) and VARCHAR(4) columns (assuming that the column uses a single-byte character set such as latin1).

Value       CHAR(4) Storage Required    VARCHAR(4)  Storage Required
''          ''      4 bytes             ''          1 byte
'ab'        'ab '   4 bytes             'ab'        3 bytes
'abcd'      'abcd'  4 bytes             'abcd'      5 bytes
'abcdefgh'  'abcd'  4 bytes             'abcd'      5 bytes

So you can see that VARCHAR is beneficial if the length of the string that you are storing is variable. The reason why CHAR is often used for password fields is because the output of hashing algorithms is consistent regardless of the length of input. Since you are storing a hash of the user's password, and not the password itself, the field length will be consistent.

leeor is correct in advising you to hash passwords. PHP The Right Way is a good resource for best practices in that regard.

查看更多
登录 后发表回答