-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
aead.go
70 lines (56 loc) · 1.5 KB
/
aead.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
package jwk
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"github.com/pkg/errors"
)
type AEAD struct {
Key []byte
}
func (c *AEAD) Encrypt(plaintext []byte) (string, error) {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
if len(c.Key) < 32 {
return "", errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
}
block, err := aes.NewCipher(c.Key[:32])
if err != nil {
return "", errors.WithStack(err)
}
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", errors.WithStack(err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", errors.WithStack(err)
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
return base64.URLEncoding.EncodeToString(append(ciphertext, nonce...)), nil
}
func (c *AEAD) Decrypt(ciphertext string) ([]byte, error) {
if len(c.Key) < 32 {
return []byte{}, errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
}
raw, err := base64.URLEncoding.DecodeString(ciphertext)
if err != nil {
return []byte{}, errors.WithStack(err)
}
n := len(raw)
block, err := aes.NewCipher(c.Key)
if err != nil {
return []byte{}, errors.WithStack(err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return []byte{}, errors.WithStack(err)
}
plaintext, err := aesgcm.Open(nil, raw[n-12:n], raw[:n-12], nil)
if err != nil {
return []byte{}, errors.WithStack(err)
}
return plaintext, nil
}