lenslocked/cmd/bcrypt/bcrypt.go
2024-08-06 12:35:27 -04:00

42 lines
845 B
Go

package main
import (
"fmt"
"os"
"golang.org/x/crypto/bcrypt"
)
func main() {
switch os.Args[1] {
case "hash":
hash(os.Args[2])
case "compare":
compare(os.Args[2], os.Args[3])
default:
fmt.Printf("Invalid command: %v\n", os.Args[1])
}
}
func hash(password string) {
fmt.Printf("Hash the password %q\n", password)
hashedBytes, err := bcrypt.GenerateFromPassword(
[]byte(password), bcrypt.DefaultCost)
if err != nil {
fmt.Printf("error hashing: %v\n", err)
return
}
hash := string(hashedBytes)
fmt.Println(hash)
}
func compare(password, hash string) {
fmt.Printf("Compare the password %q with the hash %q\n", password, hash)
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err != nil {
fmt.Printf("Password is invalid: %v\n", password)
return
}
fmt.Println("Password is correct!")
}