Skip to content

Instantly share code, notes, and snippets.

@appleboy
Created October 30, 2017 06:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appleboy/f8637f26874a3b27765aff4ece3fd55f to your computer and use it in GitHub Desktop.
Save appleboy/f8637f26874a3b27765aff4ece3fd55f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
)
func main() {
userPassword1 := "some user-provided password"
// Generate "hash" to store from user password
hash, err := bcrypt.GenerateFromPassword([]byte(userPassword1), bcrypt.DefaultCost)
if err != nil {
// TODO: Properly handle error
log.Fatal(err)
}
fmt.Println("Hash to store:", string(hash))
// Store this "hash" somewhere, e.g. in your database
// After a while, the user wants to log in and you need to check the password he entered
userPassword2 := "some user-provided password"
hashFromDatabase := hash
// Comparing the password with the hash
if err := bcrypt.CompareHashAndPassword(hashFromDatabase, []byte(userPassword2)); err != nil {
// TODO: Properly handle error
log.Fatal(err)
}
fmt.Println("Password was correct!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment