-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
87 lines (69 loc) · 2.08 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package goth
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
)
// GenerateKey Generates an encryption key
func GenerateKey() string {
const keyLen = 32
ret := make([]byte, keyLen)
if _, err := rand.Read(ret); err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(ret)
}
// EncryptCookie Encrypts a cookie value with specific encryption key
func EncryptCookie(value, key string) (string, error) {
keyDecoded, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return "", fmt.Errorf("failed to base64-decode key: %w", err)
}
block, err := aes.NewCipher(keyDecoded)
if err != nil {
return "", fmt.Errorf("failed to create AES cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM mode: %w", err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("failed to read: %w", err)
}
ciphertext := gcm.Seal(nonce, nonce, []byte(value), nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// DecryptCookie Decrypts a cookie value with specific encryption key
func DecryptCookie(value, key string) (string, error) {
keyDecoded, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return "", fmt.Errorf("failed to base64-decode key: %w", err)
}
enc, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return "", fmt.Errorf("failed to base64-decode value: %w", err)
}
block, err := aes.NewCipher(keyDecoded)
if err != nil {
return "", fmt.Errorf("failed to create AES cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM mode: %w", err)
}
nonceSize := gcm.NonceSize()
if len(enc) < nonceSize {
return "", errors.New("encrypted value is not valid")
}
nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", fmt.Errorf("failed to decrypt ciphertext: %w", err)
}
return string(plaintext), nil
}