How to use Bcrypt to hash in Go

Overview

Bcrypt is a package in Go that implements Provos and Mazières’s bcrypt adaptive hashing algorithm to calculate the hash.

Implementation

First, we have to install the package, like so:

$ go get golang.org/x/crypto/bcrypt

Example

package main
import (
"golang.org/x/crypto/bcrypt"
"fmt"
)
func main() {
pass := []byte("People talk things not reasonable but you need not worry")
// Hashing the password
hash, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
fmt.Println(string(hash))
}

Explanation

In the example above:

  1. In line 4, we import the bcrypt package for hashing.

  2. In line 5, we import the fmt package for printing.

  3. In line 9, we use byte() to convert what we want to hash to bytes since bcrypt only accepts data with type byte.

  4. In line 12, we initialize the hash and err variables.

  5. We then call the bcrypt the package, which we chain with GenerateFromPassword().

  6. We pass two parameter/arguments:

    i. The string to be hashed.

    ii. DefaultCost, which is 10.

  7. We then check for errors.

if err != nil {
        panic(err)
    }
  1. Finally, we print out the hash value.

Output

$2a$10$TC1Rg.Usl51amxo9anbqTukoD/VSEMD.kyM/gwfnHnz4/64fcejdi

Please execute the code sample. Your hash should look like the above.

Free Resources