How to create a secure password hash in Go?

To create a secure password hash in Go, you can use the bcrypt package. Bcrypt is a popular and widely used password hashing algorithm which includes a built-in salt and multiple iterations to make it resistant to brute-force attacks.

Here's an example of how to create a secure password hash using bcrypt in Go:

  1. First, install the bcrypt package by running the following command in your terminal:

    go get golang.org/x/crypto/bcrypt
  2. In your Go code, import the bcrypt package:

    import "golang.org/x/crypto/bcrypt"
  3. To create a password hash, you can use the bcrypt.GenerateFromPassword function. It takes the plaintext password as a byte array and the cost factor as an integer (higher values will increase the time taken to hash the password). Here's an example:

    password := "myPassword123" // Replace with your plaintext password cost := 14 // Adjust the cost factor as needed hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), cost) if err != nil { // Handle error }
  4. The hashedPassword variable will now contain the secure password hash. You can store this hash in a database or use it for authentication purposes.

It's important to note that bcrypt also includes a built-in salt, so you don't need to generate or store the salt separately. The salt is automatically included in the hashed password and can be used for verification during authentication.

To compare a plaintext password with a stored hash, you can use the bcrypt.CompareHashAndPassword function. Here's an example:

storedHash := // Retrieve the stored hash from your database // Compare the stored hash with the plaintext password err := bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password)) if err != nil { // Password does not match } // Password matches

By using bcrypt and the steps outlined above, you can create a secure password hash in Go that is resistant to brute-force attacks.