Sling Academy
Home/Golang/Hashing Passwords Securely with `bcrypt` in Go

Hashing Passwords Securely with `bcrypt` in Go

Last updated: November 27, 2024

In today's digital age, ensuring the security of user passwords is of utmost importance. One popular and secure method for hashing passwords is using the bcrypt algorithm. In this guide, we'll explore how to implement bcrypt in a Go application.

What is bcrypt?

Bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher. The key benefit of bcrypt is that it is adaptive, which means you can increase the cost factor to make it harder to compute hashes as hardware improves.

Installing the bcrypt package

To use bcrypt in your project, you need to import the package. You can install it using the following command:

go get golang.org/x/crypto/bcrypt

Hashing Passwords

Once you've installed the package, you can hash a password using the following code snippet:


package main

import (
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func main() {
    // Original password
    password := "myS3cureP@ssword"

    // Generate hashed password
    hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Hashed Password: ", string(hashedPassword))
}

In this code:

  • We define a password to be hashed.
  • bcrypt.GenerateFromPassword generates a hashed password using a cost factor, where bcrypt.DefaultCost is usually a sensible default to use.
  • The hashed password is returned as a byte slice, so it's converted to a string for printing.

Validating a Password

To check if a given password matches the stored hashed password, use the following code snippet:


func checkPassword(hashedPassword, password string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
    return err == nil
}

func main() {
    storedPass := "$2a$10$K/EeBdWIEuiyIItrakv/IOyaDP75num1F/EEEFFDflaIH63UJoz1Ku" // Example hashed password
    password := "myS3cureP@ssword"

    if checkPassword(storedPass, password) {
        fmt.Println("The password is correct")
    } else {
        fmt.Println("The password is incorrect")
    }
}

In this code:

  • bcrypt.CompareHashAndPassword function checks whether the provided password matches the hashed password.
  • If they match, it returns nil; otherwise, it returns an error.

Adjusting the Complexity

The security of bcrypt can be adjusted by altering the cost parameter. The cost parameter allows you to make the hashing process more computationally intensive (and thus slower). For example:


hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 14) // Cost is set to 14 here

Keep in mind that a higher cost value means more computational resources and time are required to hash the password.

Conclusion

Using bcrypt in your Go applications is a simple and effective way to ensure that user passwords are stored securely. By following the steps above, you can safely hash and verify passwords. Remember to tune your cost factor as needed to keep up with advancements in computing power.

Next Article: Understanding Symmetric Encryption with AES in Go

Previous Article: Introduction to Cryptography in Go

Series: Cryptography and Security in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant