forked from dongri/secgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (67 loc) · 1.36 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
package main
import (
"fmt"
"math/big"
"os"
"strconv"
"crypto/rand"
)
const (
DefaultLength = 10
DefaultQty = 1
UsageMessage string = "usage: secgen <n: length> [option] <n: quantity>"
)
func main() {
var length int
var qty int
var err error
if len(os.Args) < 2 {
fmt.Println("Please set length (and quantity if you want)")
fmt.Println(UsageMessage)
return
} else {
length, err = strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err.Error())
fmt.Println(UsageMessage)
return
}
qty = DefaultQty
if len(os.Args) > 2 {
qty, err = strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println(err.Error())
fmt.Println(UsageMessage)
return
}
}
}
for i := 0; i < qty; i++ {
secret, err := generateRandomString(length)
if err != nil {
fmt.Print(err.Error())
return
}
fmt.Println(secret)
}
}
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
func generateRandomString(n int) (string, error) {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+|~-=[]{};:"
ret := make([]byte, n)
for i := 0; i < n; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
return "", err
}
ret[i] = letters[num.Int64()]
}
return string(ret), nil
}