Why does PHP crypt() prepend the salt to the hash?

前端 未结 6 1224
终归单人心
终归单人心 2020-12-15 10:02

I am looking into building a login system and after reading the php manual when you pass a 2 digit salt to the crypt() function it returns a hash string, and th

6条回答
  •  盖世英雄少女心
    2020-12-15 10:44

    The crypt() function is obsolete. It was used to hash passwords for old-style Unix systems, before shadow password support came along. The salt was there to increase the complexity of brute forcing the password. However, since the salt was randomly generated by the password subsystem, it had to be stored in the clear so any future password actions would work. If the salt had been embedded into the password before crypting, there would be no practical way to verify a password - you'd have to try every single possible salt whenever a password check was done - highly impractical. So, the salt was prepended to the crypted password, so you could pull it out again for future use.

    crypted password: xxabcdefghijklmn
                      ^^- salt
                        ^^^^^^^^^^^^^^-- crypted pw
    
    if ('xx' + crypt('xx' + password) == 'crypted string') then
         password is ok
    endif
    

    These days, crypt() is the security equivalent of a cereal box decoder ring. There for historical purposes, and low-security "who cares if it's cracked into" storage. For any modern password usage, you'd be better off with more modern hashes, such as sha1/sha256/md5. And even md5 is considered broken these days, sha1 has cracks around the edges, and (last I checked) sha256 is still secure.

提交回复
热议问题