-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_bcrycpt.go
49 lines (43 loc) · 1.06 KB
/
test_bcrycpt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
)
func main() {
for {
// 输入密码 获取 hash 值
pwd := getPwd()
hash := hashAndSalt(pwd)
// 再次输入密码验证
pwd2 := getPwd()
pwdMatch := comparePasswords(hash, pwd2)
fmt.Println("Passwords Match %v", pwdMatch)
}
}
func getPwd() []byte {
fmt.Println("Enter a password")
var pwd string
_, err := fmt.Scan(&pwd)
if err != nil {
log.Println(err)
}
return []byte(pwd)
}
func hashAndSalt(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
log.Println(err)
}
return string(hash)
}
func comparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
log.Println(hashedPwd, byteHash, plainPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
log.Println(err)
return false
}
return true
}