forked from vmware-archive/atc
/
encryption_key.go
54 lines (42 loc) · 982 Bytes
/
encryption_key.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
package db
import (
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"io"
)
type EncryptionKey struct {
aesgcm cipher.AEAD
}
func NewEncryptionKey(a cipher.AEAD) *EncryptionKey {
return &EncryptionKey{
aesgcm: a,
}
}
func (e EncryptionKey) Encrypt(plaintext []byte) (string, *string, error) {
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", nil, err
}
ciphertext := e.aesgcm.Seal(nil, nonce, plaintext, nil)
noncense := hex.EncodeToString(nonce)
return hex.EncodeToString(ciphertext), &noncense, nil
}
func (e EncryptionKey) Decrypt(text string, n *string) ([]byte, error) {
if n == nil {
return nil, ErrDataIsNotEncrypted
}
ciphertext, err := hex.DecodeString(text)
if err != nil {
return nil, err
}
nonce, err := hex.DecodeString(*n)
if err != nil {
return nil, err
}
plaintext, err := e.aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}