-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
195 lines (187 loc) · 5.56 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Grand generates cryptographically-secure random byte strings.
//
// Usage:
//
// grand [flags]
//
// The flags are:
//
// -e encoding
// output encoding; one of:
// "hex" - base16
// "b64s" - base64, standard alphabet
// "b64sr" - base64, standard alphabet, no padding
// "b64u" - base64, URL-safe alphabet
// "b64ur" - base64, URL-safe alphabet, no padding
// "b32s" - base32, standard alphabet
// "b32sr" - base32, standard alphabet, no padding
// "b32h" - base32, extended hex alphabet
// "b32hr" - base32, extended hex alphabet, no padding
// (default "hex")
// -n int
// number of random byte strings to generate (default 1)
// -s size
// size of random byte strings; an integer or an inclusive range,
// e.g. "16-32" (if a range is specified, the size of each byte
// string will be a cryptographically-secure random number in the
// range) (default "16")
package main
import (
"crypto/rand"
"encoding/base32"
"encoding/base64"
"encoding/hex"
"errors"
"flag"
"fmt"
"math/big"
"os"
"strconv"
"strings"
)
func main() {
// define and parse flags
var (
e string
s string
n int
)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Grand generates cryptographically-secure random byte strings.\nUsage:\n")
flag.PrintDefaults()
}
flag.StringVar(&e, "e", "hex", "output `encoding`;"+` one of:
"hex" - base16
"b64s" - base64, standard alphabet
"b64sr" - base64, standard alphabet, no padding
"b64u" - base64, URL-safe alphabet
"b64ur" - base64, URL-safe alphabet, no padding
"b32s" - base32, standard alphabet
"b32sr" - base32, standard alphabet, no padding
"b32h" - base32, extended hex alphabet
"b32hr" - base32, extended hex alphabet, no padding
`)
flag.StringVar(&s, "s", "16", "`size`"+` of random byte strings; an integer or an inclusive range,
e.g. "16-32" (if a range is specified, the size of each byte
string will be a cryptographically-secure random number in the
range)`)
flag.IntVar(&n, "n", 1, "number of random byte strings to generate")
flag.Parse()
// define encodings, validate -e flag value
encodings := map[string]encoding{
"hex": new(hexEncoding),
"b64s": base64.StdEncoding,
"b64sr": base64.RawStdEncoding,
"b64u": base64.URLEncoding,
"b64ur": base64.RawURLEncoding,
"b32s": base32.StdEncoding,
"b32sr": base32.StdEncoding.WithPadding(base32.NoPadding),
"b32h": base32.HexEncoding,
"b32hr": base32.HexEncoding.WithPadding(base32.NoPadding),
}
enc, ok := encodings[e]
if !ok {
fmt.Fprintf(os.Stderr, "invalid value %q for flag -e: encoding not found\n", e)
flag.Usage()
os.Exit(2)
}
// parse and validate -s flag value
sizeMin, sizeMax, err := parseValidateSize(s)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid value %q for flag -s: %v\n", s, err)
flag.Usage()
os.Exit(2)
}
// validate -n flag value
if n < 1 {
fmt.Fprintf(os.Stderr, "invalid value %v for flag -n: n must be greater than zero\n", n)
flag.Usage()
os.Exit(2)
}
// define buffers
// random bytes will be written to b
// encoded random bytes will be written to be
// hex produces the longest encodings with a length of n*2
b := make([]byte, sizeMax)
be := make([]byte, sizeMax*2)
// generate, encode, and print random byte strings
for range n {
l, err := size(sizeMin, sizeMax)
if err != nil {
fmt.Fprintf(os.Stderr, "error generating random size: %v", err)
os.Exit(1)
}
_, err = rand.Read(b[:l])
if err != nil {
fmt.Fprintf(os.Stderr, "error generating random byte string: %v", err)
os.Exit(1)
}
enc.Encode(be, b[:l])
le := enc.EncodedLen(l)
fmt.Println(string(be[:le]))
}
}
// size returns a cryptographically-secure random int between sizeMin and sizeMax, inclusive.
// It panics if sizeMin > sizeMax.
func size(sizeMin, sizeMax int) (int, error) {
if sizeMin == sizeMax {
return sizeMin, nil
}
rmax := big.NewInt(int64(sizeMax - sizeMin + 1))
r, err := rand.Int(rand.Reader, rmax)
if err != nil {
return 0, err
}
s := sizeMin + int(r.Int64())
return s, nil
}
// parseValidateSize parses s, which can be an integer or a range in the form of sizeMin-sizeMax, e.g. "1-2".
// It validates that 0 < sizeMin <= sizeMax.
// If s is an integer n, then sizeMin = sizeMax = n.
func parseValidateSize(s string) (sizeMin, sizeMax int, err error) {
// parse
sizeMinStr, sizeMaxStr, isRange := strings.Cut(s, "-")
if isRange {
sizeMin, err = strconv.Atoi(sizeMinStr)
if err != nil {
return 0, 0, errors.New("parse error")
}
sizeMax, err = strconv.Atoi(sizeMaxStr)
if err != nil {
return 0, 0, errors.New("parse error")
}
} else {
sizeMin, err = strconv.Atoi(s)
if err != nil {
return 0, 0, errors.New("parse error")
}
sizeMax = sizeMin
}
// validate
if sizeMin < 1 {
if isRange {
return 0, 0, errors.New("size_min must be greater than zero")
}
return 0, 0, errors.New("size must be greater than zero")
}
if sizeMax < sizeMin {
return 0, 0, errors.New("size_max must not be less than size_min")
}
return sizeMin, sizeMax, nil
}
// encoding has two methods required for encoding byte slices.
// It satisfies the standard library's base64 and base32 encodings.
type encoding interface {
Encode(dst []byte, src []byte)
EncodedLen(n int) int
}
// hexEncoding satisfies encoding with thin wrappers around the standard library's hex package functions.
type hexEncoding struct{}
// Encode wraps hex.Encode, ignoring its return value.
func (*hexEncoding) Encode(dst []byte, src []byte) {
hex.Encode(dst, src)
}
// EncodedLen wraps hex.EncodedLen.
func (*hexEncoding) EncodedLen(n int) int {
return hex.EncodedLen(n)
}