golang equivalent of PHP crypt()

后端 未结 1 1460
孤街浪徒
孤街浪徒 2021-01-02 17:53

This line of code in PHP evaluates to true

echo \'$2a$09$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2\' == crypt(\"enter-new-password\",\'$2a$09$f55         


        
相关标签:
1条回答
  • 2021-01-02 18:04

    Although I haven't found an exact "Go crypt function" equivalent of PHP's crypt function, I found an alternative.

    The following solved my problem

    import "golang.org/x/crypto/bcrypt"
    // check will be nil if the bcrypt version of "enter-new-password" is the same as the "$2a$09$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2" .  Otherwise check will be an error object
    check := bcrypt.CompareHashAndPassword([]byte("$2a$09$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2"),[]byte("enter-new-password"))
    log.Println(check)
    

    The golang.org/x/crypto/bcrypt/bcrypt_test.go has some useful examples of how to use this module.


    Apparently PHP's crypt function has many different ways of hashing a value, like sha256, sha512, blowfish etc... It seems there are many go lang modules out there, but you have to explicitly state the hash type, the cost, etc... In my question, the existence of $2a$ as a prefix to the hash value suggested the use of some blowfish type hash. Some of my earlier attempts didn't consider this. In fact, the module in attempt 3 does not have support for blowfish.

    0 讨论(0)
提交回复
热议问题