How to hash a password in Go

When you’re storing a password in a database the worst thing that you could do as a software developer is store that password in plain text. We have to store and treat sensitive data as what it is, sensitive!

Luckily, in Go we can do this really easily using the Bcrypt package. Once, we retrieved the package with go get we can use it straight away. Hashing a can be done with one function, yes I’ll repeat that, one function.

Let’s start by importing the package in the file we want to use it in:

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

Now we have our package we can hash our package using the GenerateFromPassword() function like so:

hashed, _ := bcrypt.GenerateFromPassword([]byte(u.Password), 8)

u.Password = string(hashed)

In our example we have a hypothetical user struct which has a plain text password assigned to the Password field, we was to use that to generate our password and then reassign our hashed password back to the struct field.

So we pass the password as a byte array to the GenerateFromPassword() function firstly and then pass the cost, which in this example we have set to an arbitrary value of 8. We get back the hashed password as a byte array and a possible error, which for the example we have ignored with the underscore. Finally, we convert the hashed password to a string and reassign it back to the password field on the user struct. Really simple, really nice, and a perfect solution for storing user passwords in a database.

Thank you for reading! I’ll be back with more Go tutorials in the future.


Source link