-
Notifications
You must be signed in to change notification settings - Fork 0
/
key_encryptor.go
91 lines (72 loc) · 1.72 KB
/
key_encryptor.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
package goliauth
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"os"
)
// NewRandomKey will generate a 32 bytes random string
func NewRandomKey() []byte {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
// really, what are you gonna do if randomness failed?
panic(err)
}
return key
}
// Decrypt will return the original value of the encrypted string
func Decrypt(encryptedKey []byte) ([]byte, error) {
secretKey := getSecret()
block, err := aes.NewCipher(secretKey)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(encryptedKey) < aesgcm.NonceSize() {
// worth panicking when encrypted key is bad
panic("Malformed encrypted key")
}
return aesgcm.Open(
nil,
encryptedKey[:aesgcm.NonceSize()],
encryptedKey[aesgcm.NonceSize():],
nil,
)
}
// Encrypt will encrypt a raw string to
// an encrypted value
// an encrypted value has an IV (nonce) + actual encrypted value
// when we decrypt, we only decrypt the latter part
func Encrypt(key []byte) ([]byte, error) {
secretKey := getSecret()
block, err := aes.NewCipher(secretKey)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
iv := make([]byte, aesgcm.NonceSize())
if _, err := rand.Read(iv); err != nil {
return nil, err
}
ciphertext := aesgcm.Seal(iv, iv, key, nil)
return ciphertext, nil
}
func getSecret() []byte {
secret := os.Getenv("SECRET")
if secret == "" {
panic("Error: Must provide a secret key under env variable SECRET")
}
secretbite, err := hex.DecodeString(secret)
if err != nil {
// probably malform secret, panic out
panic(err)
}
return secretbite
}