Home  >  Article  >  Backend Development  >  How to Achieve PHP\'s crypt() Function Equivalence for CRYPT_BLOWFISH in Go?

How to Achieve PHP\'s crypt() Function Equivalence for CRYPT_BLOWFISH in Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 15:38:29874browse

 How to Achieve PHP's crypt() Function Equivalence for CRYPT_BLOWFISH in Go?

PHP crypt() Function Equivalent in Go

Question:

How can a Go function be made to mimic the behavior of PHP's crypt() function for specific input strings, where PHP's crypt() with CRYPT_BLOWFISH evaluation results in true?

Attempts and Expected Result:

Attempts have been made to achieve this, but without success:

  • Attempt 1:
    Using the github.com/nyarla/go-crypt module, the result was false.
  • Attempt 2:
    Creating a custom crypt function using C interop also resulted in false.
  • Attempt 3:
    Another Go module was attempted but lacked support for CRYPT_BLOWFISH.

The desired outcome is for a Go crypt() function to correctly evaluate the strings "enter-new-password" and "$2a$09$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2" to true, like PHP's crypt().

Solution:

While an exact PHP crypt() equivalent in Go couldn't be found, an alternative solution was implemented:

<code class="go">import "golang.org/x/crypto/bcrypt"

check := bcrypt.CompareHashAndPassword([]byte("a$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2"), []byte("enter-new-password"))

if check == nil {
    fmt.Println("Passwords match")
} else {
    fmt.Println("Passwords don't match")
}</code>

This approach utilizes the golang.org/x/crypto/bcrypt module to compare the provided password with the stored hash value. The CompareHashAndPassword() function returns nil if the passwords match and an error otherwise.

Additional Notes:

It's important to note that PHP's crypt function offers multiple hashing algorithms, including sha256, sha512, and blowfish. In Go, different modules are often necessary to handle specific algorithms. In this case, the blowfish type hashing used in the PHP example is not natively supported by any of the Go modules attempted. Therefore, the bcrypt module was used instead.

The above is the detailed content of How to Achieve PHP\'s crypt() Function Equivalence for CRYPT_BLOWFISH in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn