forked from shoenig/bcrypt-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (91 loc) · 1.86 KB
/
main.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Command bcrypt-tool is command line tool for common bcrypt functions
// including the ability to generate hashes, determine if a password
// matches a hash, and compute cost from a hash.
package main
import (
"fmt"
"os"
"strconv"
"golang.org/x/crypto/bcrypt"
)
const (
helpText = `Usage: bcrypt-tool [action] argument ...
ACTIONS
hash [password] <cost> Generate hash given password and optional cost (4-31)
match [password] [hash] Print "yes" and return 0 if password is a match
for hash, or print "no" and return 1 otherwise
cost [hash] Print the cost of hash (4-31)`
)
func main() {
os.Args = os.Args[1:]
if len(os.Args) < 2 {
help()
}
switch os.Args[0] {
case "cost":
if len(os.Args) != 2 {
help()
}
c := cost(os.Args[1])
fmt.Println(fmt.Sprintf("%d", c))
case "match":
if len(os.Args) != 3 {
help()
}
ok := match(os.Args[1], os.Args[2])
if ok {
fmt.Println("yes")
} else {
fmt.Println("no")
os.Exit(1)
}
case "hash":
if len(os.Args) > 4 {
help()
}
passwd := os.Args[1]
cost := bcrypt.DefaultCost
if len(os.Args) == 3 {
c, e := strconv.Atoi(os.Args[2])
if e != nil {
help()
}
cost = c
}
hash := hash(passwd, cost)
fmt.Println(hash)
default:
help()
}
}
func help() {
_, _ = fmt.Fprintln(os.Stderr, helpText)
os.Exit(2)
}
func cost(hash string) int {
h := []byte(hash)
c, e := bcrypt.Cost(h)
if e != nil {
_, _ = fmt.Fprintln(os.Stderr, e)
os.Exit(2)
}
return c
}
func match(password, hash string) bool {
p := []byte(password)
h := []byte(hash)
e := bcrypt.CompareHashAndPassword(h, p)
if e != nil {
return false
}
return true
}
func hash(password string, cost int) string {
p := []byte(password)
h, e := bcrypt.GenerateFromPassword(p, cost)
if e != nil {
_, _ = fmt.Fprintln(os.Stderr, e)
os.Exit(2)
}
return string(h)
}