bcrypt
This commit is contained in:
41
cmd/bcrypt/bcrypt.go
Normal file
41
cmd/bcrypt/bcrypt.go
Normal file
@@ -0,0 +1,41 @@
|
||||
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!")
|
||||
}
|
||||
Reference in New Issue
Block a user