-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.go
73 lines (58 loc) · 1.2 KB
/
crypt.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
package otp
import (
"crypto/rand"
"errors"
"fmt"
"io"
)
const (
Invalid Algorithm = iota
SHA1
SHA512
)
type Algorithm int
func NewAlgorithm(algorithm string) (Algorithm, error) {
switch algorithm {
case "SHA1":
return SHA1, nil
case "SHA512":
return SHA512, nil
default:
return Invalid, fmt.Errorf("invalid algorithm %q", algorithm)
}
}
func (a Algorithm) String() string {
switch a {
case SHA1:
return "SHA1"
case SHA512:
return "SHA512"
default:
return "invalid"
}
}
// NewKey will use the given reader to generate some random bytes to be used
// as the key in a one time password.
//
// Because of this it's important that the reader be set to nil in a production
// environment so that internally the function can use the most secure option
// which will be the standard library's crypto/rand reader.
func NewKey(r io.Reader, alg Algorithm) ([]byte, error) {
var n int
switch alg {
case SHA1:
n = 20
case SHA512:
n = 64
default:
return nil, errors.New("new key requires a valid algorithm")
}
if r == nil {
r = rand.Reader
}
b := make([]byte, n)
if _, err := io.ReadFull(r, b); err != nil {
return nil, fmt.Errorf("read random bytes: %w", err)
}
return b, nil
}