-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazyaesgcm.go
81 lines (64 loc) · 1.69 KB
/
lazyaesgcm.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
package lazyaesgcm
import (
"crypto/aes"
"crypto/cipher"
cryptorand "crypto/rand"
"encoding/hex"
"errors"
)
const (
nonceSize = 12
macSize = 16
)
type LazyAesGcm interface {
Encrypt(plaintext string, key []byte) (string, error)
Decrypt(ciphertext string, key []byte) (string, error)
}
type lazyAesGcm256 struct {
}
func (l *lazyAesGcm256) Encrypt(plaintext string, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// Select a random nonce, and leave capacity for the ciphertext.
nonce := make([]byte, nonceSize, nonceSize+len(plaintext)+macSize)
if _, err := cryptorand.Read(nonce); err != nil {
return "", err
}
aesGcm, err := cipher.NewGCMWithNonceSize(block, len(nonce))
if err != nil {
return "", err
}
// Encrypt the message and append the ciphertext to the nonce.
encrypted := aesGcm.Seal(nonce, nonce, []byte(plaintext), nil)
return hex.EncodeToString(encrypted), nil
}
func (l *lazyAesGcm256) Decrypt(ciphertext string, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(ciphertext) < nonceSize {
return "", errors.New("ciphertext too short")
}
encrypted, err := hex.DecodeString(ciphertext)
if err != nil {
return "", err
}
// Split nonce and ciphertext.
nonce, cipherBytes := encrypted[:nonceSize], encrypted[nonceSize:]
aesGcm, err := cipher.NewGCMWithNonceSize(block, len(nonce))
if err != nil {
return "", err
}
// Decrypt the message and check it wasn't tampered with.
plaintext, err := aesGcm.Open(nil, nonce, cipherBytes, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}
func New() LazyAesGcm {
return &lazyAesGcm256{}
}