Created
October 6, 2018 15:45
-
-
Save donvito/9c30ac809822dd4eed03c4abc578bd18 to your computer and use it in GitHub Desktop.
Hash passwords using bcrypt library #golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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