-
Notifications
You must be signed in to change notification settings - Fork 342
/
keys.go
68 lines (60 loc) · 1.34 KB
/
keys.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
package keys
import (
crand "crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
const AkiaAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" // Amazon AKIA alphabet is weird.
func KeyGenerator(length int) string {
var b strings.Builder
for {
bbuf := make([]byte, length) // one byte of randomness per character isn't really needed but it makes the implementation simpler
_, err := crand.Read(bbuf)
if err != nil {
continue // let's retry until we have enough entropy
}
for i := 0; i < length; i++ {
c := bbuf[i]
b.WriteByte(AkiaAlphabet[int(c)%len(AkiaAlphabet)])
}
break
}
return b.String()
}
func Base64StringGenerator(bytes int) string {
var ret string
bbuf := make([]byte, bytes)
for {
_, err := crand.Read(bbuf)
if err != nil {
continue
}
ret = base64.StdEncoding.EncodeToString(bbuf)
break
}
return ret
}
func HexStringGenerator(bytes int) string {
var ret string
buf := make([]byte, bytes)
for {
_, err := crand.Read(buf)
if err != nil {
continue
}
ret = strings.ToUpper(hex.EncodeToString(buf))
break
}
return ret
}
func GenAccessKeyID() string {
const accessKeyLength = 14
key := KeyGenerator(accessKeyLength)
return fmt.Sprintf("%s%s%s", "AKIAJ", key, "Q")
}
func GenSecretAccessKey() string {
const secretKeyLength = 30
return Base64StringGenerator(secretKeyLength)
}