DEV Community

Sam Newby
Sam Newby

Posted on

8 1

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"
)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay