-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
68 lines (54 loc) · 1.22 KB
/
utils.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 main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"hash"
"math/big"
)
var secretLength = map[Algorithm]int{
SHA1: 20,
SHA256: 32,
SHA512: 64,
}
func generateSecret(algorithm Algorithm) []byte {
length := secretLength[algorithm]
secret := make([]byte, length)
charRangeStart := 65
charRangeEnd := 122
charRange := int64((charRangeEnd - charRangeStart) + 1)
for i := range secret {
n, err := rand.Int(rand.Reader, big.NewInt(charRange))
if err != nil {
panic(err)
}
secret[i] = byte(n.Int64() + 65)
}
return secret
}
func dynamicTruncate(hmac []byte) []byte {
offset := hmac[len(hmac) - 1] & 0xf
dbc := hmac[offset:offset+4]
dbc[0] = dbc[0] & 0x7f
return dbc
}
func generateHMAC[V OTP](o V, counter []byte) []byte {
var mac hash.Hash
if o.Algorithm() == SHA1 {
mac = hmac.New(sha1.New, o.Secret())
} else if o.Algorithm() == SHA256 {
mac = hmac.New(sha256.New, o.Secret())
} else if o.Algorithm() == SHA512 {
mac = hmac.New(sha512.New, o.Secret())
}
mac.Write(counter)
return mac.Sum(nil)
}
func convertCounterToBytes(c uint64) []byte {
counter := make([]byte, 8)
binary.BigEndian.PutUint64(counter, c)
return counter
}