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 mainimport ("golang.org/x/crypto/bcrypt""fmt")func main() {pass := []byte("People talk things not reasonable but you need not worry")// Hashing the passwordhash, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)if err != nil {panic(err)}fmt.Println(string(hash))}
Explanation
In the example above:
-
In line 4, we import the
bcryptpackage for hashing. -
In line 5, we import the
fmtpackage for printing. -
In line 9, we use
byte()to convert what we want to hash to bytes sincebcryptonly accepts data with typebyte. -
In line 12, we initialize the
hashanderrvariables. -
We then call the
bcryptthe package, which we chain withGenerateFromPassword(). -
We pass two parameter/arguments:
i. The string to be hashed.
ii.
DefaultCost, which is 10. -
We then check for errors.
if err != nil {
panic(err)
}
- 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.