PHP password_hash function salt length 21 or 22?

落花浮王杯 提交于 2019-12-05 17:55:13
ircmaxell

First, please don't provide your own salt. You're not going to do a better job generating it than the library does. And using static salts (like you did in the example) will compromise security. Just let it generate its own salt (incidentally, I believe letting a salt in is the biggest mistake I made in that API).

As far as 21 vs 22 characters, give this answer a read.

Basically, the salt is base64 encoded. This means that every 6 bits of the salt is encoded into 8 bits. So every byte of encoded salt is 6 bits.

21 characters is 126 bits. That means that only part of the 22nd character is used (the first 2 decoded bits). The reason you get the same hash with A and B, is that the leading 2 bits are the same for both characters.

In fact, there are only 4 unique hashes for the 22nd byte.

martinstoeckli

BCrypt expects a salt of a given alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. As you can see the '-' is not in it and that's why your salt is invalid. A valid salt you could see plaintext in the hash-value.

In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.

password_hash("stackoverflow", PASSWORD_DEFAULT);

Nevertheless you are right, when you say that BCrypt does not use the full 22 characters. It seems that BCrypt only uses 126 bits of the salt instead of the 128bits you get with 22 base64 encoded characters. For more information you can have a look at this discussion Why does crypt/blowfish generate the same hash....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!