Home > Backend Development > Golang > How to Achieve the Functionality of PHP\'s crypt() with Blowfish in Golang?

How to Achieve the Functionality of PHP\'s crypt() with Blowfish in Golang?

Susan Sarandon
Release: 2024-10-28 06:32:02
Original
491 people have browsed it

How to Achieve the Functionality of PHP's crypt() with Blowfish in Golang?

Golang Equivalent of PHP's crypt() Function with Support for Blowfish

PHP's crypt() function offers a range of hashing methods, including blowfish. Attempting to replicate its behavior in Golang has proven challenging due to the absence of a direct equivalent.

Alternative Solution

Despite the lack of an exact Golang crypt() equivalent, an effective alternative is available using the golang.org/x/crypto/bcrypt package. The following code snippet provides an example:

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

// Check whether the bcrypt version of "enter-new-password" matches "a$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2".
check := bcrypt.CompareHashAndPassword([]byte("a$f5561d2634fb28a969f2dO8QeQ70f4bjCnF/.GvPpjj.8jgmtzZP2"), []byte("enter-new-password"))
log.Println(check)</code>
Copy after login

If the bcrypt hash of "enter-new-password" matches the provided hash, check will be nil. Otherwise, check will be set to an error object.

Considerations

PHP's crypt() function supports various hashing algorithms, such as sha256, sha512, and blowfish. In Golang, it's necessary to explicitly specify the hash type, cost, and other parameters.

The $2a$ prefix in the provided hash suggests the use of a blowfish-based algorithm. Some earlier attempts at a solution did not account for this, leading to incorrect results.

The golang.org/x/crypto/bcrypt/bcrypt_test.go file offers additional examples on how to leverage this package effectively.

The above is the detailed content of How to Achieve the Functionality of PHP\'s crypt() with Blowfish in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template