/
crypto.go
109 lines (89 loc) · 2.65 KB
/
crypto.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
package kms
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"errors"
mathrand "math/rand"
"golang.org/x/crypto/pbkdf2"
)
// AesGCMEncrypt Encrypt data using AES with the GCM cipher mode (Gives Confidentiality and Authenticity)
func AesGCMEncrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
}
// AesGCMDecrypt Decrypt data using AES with the GCM cipher mode (Gives Confidentiality and Authenticity)
func AesGCMDecrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("Data to decrypt is too small")
}
plaintext, err := gcm.Open(nil, ciphertext[:nonceSize], ciphertext[nonceSize:], nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
// GetHmac256 will generate a HMAC hash encoded to base64
func GetHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// DeriveKey will generate a AES key from a passphrase
func DeriveAESKey(passphrase string, salt []byte) []byte {
// Create key
return pbkdf2.Key([]byte(passphrase), salt, 4096, 32, sha1.New)
}
// Get a random number
func GetRandomInt(min, max int) int {
// Generate a Crypto random seed from the OS
// We should not use the time as the seed as this will lead to predicatable PINs
var n int64
binary.Read(rand.Reader, binary.LittleEndian, &n)
mathrand.Seed(n)
// Now get a number from the range desired
return mathrand.Intn(max-min) + min
}
// Generate a Random secret encoded as a b32 string
// If the length is <= 0, a default length of 10 bytes will
// be used, which will generate a secret of length 16.
func RandomSecret(length int) string {
if length <= 0 {
length = 10
}
// Get a random based on a random int. Based off OS not based on Time.
rnd := mathrand.New(mathrand.NewSource(int64(GetRandomInt(100000, 999999))))
secret := make([]byte, length)
for i, _ := range secret {
secret[i] = byte(rnd.Int31() % 256)
}
return base32.StdEncoding.EncodeToString(secret)
}