Home >Backend Development >Golang >Is There a True Go Equivalent to PHP\'s crypt() Function?

Is There a True Go Equivalent to PHP\'s crypt() Function?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 05:10:31349browse

Is There a True Go Equivalent to PHP's crypt() Function?

Finding a Go Equivalent for PHP's crypt() Function

Crypt function in PHP and Golang

Problem Introduction

The PHP crypt() function generates a hashed value of a given string using a specified algorithm. A recent question arose seeking a Golang equivalent of this function that would produce identical results for specific input and hash values.

Unsuccessful Attempts

Several attempts were made to implement the Go equivalent of PHP's crypt() function:

  • Attempt 1: The go-crypt module did not produce the same result.
  • Attempt 2: Defining a custom crypt function using C interoperability also failed.
  • Attempt 3: The bcrypt package did not support the CRYPT_BLOWFISH algorithm used by PHP5.3 and earlier.

Solution

Despite not finding an exact "Go crypt function" equivalent, an alternative was discovered:

  • Using the golang.org/x/crypto/bcrypt package, the bcrypt.CompareHashAndPassword() function can be used to compare a plain text password with a hashed value.

Example

The following Go code can be used:

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

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

This code will return nil if the bcrypt version of "enter-new-password" is the same as the provided hash value; otherwise, it will return an error.

Additional Notes

  • PHP's crypt() function supports various hashing algorithms, including sha256, sha512, blowfish, etc.
  • In Go, it is necessary to explicitly specify the hash type and cost when using the bcrypt package.
  • For the specific scenario in the question, the existence of $2a$ as a prefix in the hash value suggested the use of a Blowfish-type hash.

The above is the detailed content of Is There a True Go Equivalent to PHP\'s crypt() Function?. 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