Skip to content

Instantly share code, notes, and snippets.

@donvito
Created October 6, 2018 15:45
Show Gist options
  • Save donvito/9c30ac809822dd4eed03c4abc578bd18 to your computer and use it in GitHub Desktop.
Save donvito/9c30ac809822dd4eed03c4abc578bd18 to your computer and use it in GitHub Desktop.
Hash passwords using bcrypt library #golang
package main
import (
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
)
func main() {
pw := "mypassword"
isPasswordValid := checkPassword(hashPassword("mypassword"), pw)
fmt.Println("Is password valid?", isPasswordValid)
}
func hashPassword(password string) (hashedPassword string) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
log.Fatal(err)
}
fmt.Println("Hashed password", string(hash))
return string(hash)
}
func checkPassword(hashedPassword string, password string) (isPasswordValid bool) {
if err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)); err != nil {
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment