-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryptsymmetric.go
106 lines (84 loc) · 2.09 KB
/
encryptsymmetric.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
package gocrypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"fmt"
"io"
)
type symmetricDriver struct {
key SimpleKey
signer HashingAlgo
}
func (driver symmetricDriver) Sign(data []byte) ([]byte, error) {
constructor := HashingInstance(driver.signer)
if constructor == nil {
return nil, fmt.Errorf("invalid hash algo passed to driver")
}
hasher := hmac.New(constructor, driver.key)
_, err := hasher.Write(data)
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
func (driver symmetricDriver) ValidateSignature(data []byte, signature []byte) (bool, error) {
constructor := HashingInstance(driver.signer)
if constructor == nil {
return false, fmt.Errorf("invalid hash algo passed to driver")
}
hasher := hmac.New(constructor, driver.key)
_, err := hasher.Write(data)
if err != nil {
return false, err
}
return hmac.Equal(signature, hasher.Sum(nil)), nil
}
func (driver symmetricDriver) Encrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(driver.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, data, nil), nil
}
func (driver symmetricDriver) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(driver.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]
result, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return result, nil
}
func (driver symmetricDriver) EncryptBase64(data []byte) (string, error) {
raw, err := driver.Encrypt(data)
if err != nil {
return "", err
}
encoded, err := base64Encode(raw)
return string(encoded), nil
}
func (driver symmetricDriver) DecryptBase64(encrypted string) ([]byte, error) {
raw, err := base64Decode([]byte(encrypted))
if err != nil {
return nil, err
}
return driver.Decrypt(raw)
}