SoFunction
Updated on 2025-03-05

Golang uses bcrypt to implement password encryption and verification operation code

bcrypt can be used to save user passwords in the database, which is more secure and reliable than md5

document

//x/crypto/bcrypt

The standard document is given in the document. This library is the algorithm golang implementation described in the following file:

/legacy/event/usenix99/provos/

Install

go get -u /x/crypto/bcrypt

Encryption example

package main
import (
    "fmt"
    "/x/crypto/bcrypt"
)
func main() {
    password := "123456"
    hashedPassword, _ := ([]byte(password), )
    (string(hashedPassword))
    // $2a$10$EvdBpymvP7uDfI0TFRD6RO3YXLwQWUVYKMDqbWFloYCtyNXHCmbD2
    // $2a$10$6JDH6z7dJljoDo4VolpHbeIgzqHwhUvF1JRJ/h7Ibf/
}

You can see that after multiple runs, the generated results are different.

bcrypt cannot be decrypted, but it can be compared whether the encrypted data matches the encrypted data before encryption.

package main
import (
    "fmt"
    "/x/crypto/bcrypt"
)
func main() {
    password := "123456"
    hashedPassword := "$2a$10$EvdBpymvP7uDfI0TFRD6RO3YXLwQWUVYKMDqbWFloYCtyNXHCmbD2"
    err := ([]byte(hashedPassword), []byte(password))
    (err)
    // <nil>
}

Since the incoming and outgoing parameters of the algorithm are both byte-type data, for the sake of ease of use, the two methods can be simply encapsulated into a tool class, and the incoming and outgoing parameters are changed to data of string type

package utils
import (
    "/x/crypto/bcrypt"
)
func GenerateFromPassword(password string) (string, error) {
    hashedPassword, err := ([]byte(password), )
    if err != nil {
        return "", err
    }
    return string(hashedPassword), err
}
func CompareHashAndPassword(hashPassword string, password string) bool {
    err := ([]byte(hashPassword), []byte(password))
    return err == nil
}

This is the end of this article about Golang using bcrypt to implement password encryption and verification. For more related Golang password encryption and verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!