hash a password in go

To hash a password in Go, you can use the bcrypt package which provides a bcrypt hashing algorithm implementation.

Here is an example code that hashes a password:

main.go
import "golang.org/x/crypto/bcrypt"

func hashPassword(password string) (string, error) {
    // Hashing the password with the default cost of 10
    hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    if err != nil {
        return "", err
    }
    return string(hashedPassword), nil
}
329 chars
11 lines

In the above code, we first import the bcrypt package. The GenerateFromPassword function accepts two arguments, the first one being the password as []byte, and the second one for the cost of the algorithm. The higher the cost, the longer it takes to hash the password. bcrypt.DefaultCost is used as default and is currently set to 14.

The function returns the hashed password as a string.

Keep in mind that when storing a hashed password, you should always store the output as []byte and not as a plain text string. When checking if a password matches a stored hash, you can use the CompareHashAndPassword function from the bcrypt package.

gistlibby LogSnag