go - 2 minutes read

GoLang Password Hashing

Security is like the bouncer at the club of your application – super important. And where do you stash those passwords? Even more vital. Pro tip: Don't leave them lying around in plain text like a sticky note on your monitor. That's a one-way ticket to hacker-ville. We're always told to 'use a different password for every website,' but come on, who actually does that? We all know 'Password123' is getting way more use than it should!

Luckily for us, Go comes to the rescue with a shiny package called Bcrypt. It's like a superhero for your passwords, based on Provos and Mazières’s bcrypt adaptive hashing algorithm – which sounds super fancy, but really just means it’s here to save your passwords from evil hackers. So go ahead, let Bcrypt do the heavy lifting while you take the credit!

 

package main

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

func main() {
	hash := Hash("mypassword")
	log.Println(hash)
	
	match := Check("mypassword", hash)
	log.Println(strconv.FormatBool(match))
}

// Hash generates a hash for the given password or an error
func Hash(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    return string(bytes), err
}

// Check confirms if the given password matches the stored hash.
func Check(password string, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

 

The code above is just a simple example to get you started. Thankfully, I've bundled everything into a handy service that you can download for free. Enjoy! https://github.com/mtdevs28080617/go-bcrypt

Spread the word!

© Copyright 2025. All rights reserved, MTDevs.