-
Notifications
You must be signed in to change notification settings - Fork 4
/
aesgcm.go
92 lines (73 loc) · 1.92 KB
/
aesgcm.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
package jwe
import (
"crypto/aes"
"crypto/cipher"
"errors"
"io"
)
var (
ErrInvalidKeySize = errors.New("invalid key size")
ErrInvalidTagSize = errors.New("invalid tag size")
ErrInvalidNonceSize = errors.New("invalid nonce size")
ErrUnsupportedEncryptionType = errors.New("unsupported encryption type")
)
const TagSizeAESGCM = 16
type EncryptionType string
var EncryptionTypeA256GCM = EncryptionType("A256GCM")
type cipherAESGCM struct {
keySize int
getAEAD func(key []byte) (cipher.AEAD, error)
}
func (ci cipherAESGCM) encrypt(key, aad, plaintext []byte) (iv []byte, ciphertext []byte, tag []byte, err error) {
if len(key) != ci.keySize {
return nil, nil, nil, ErrInvalidKeySize
}
aead, err := ci.getAEAD(key)
if err != nil {
return nil, nil, nil, err
}
iv = make([]byte, aead.NonceSize())
_, err = io.ReadFull(RandReader, iv)
if err != nil {
return nil, nil, nil, err
}
res := aead.Seal(nil, iv, plaintext, aad)
tagIndex := len(res) - TagSizeAESGCM
return iv, res[:tagIndex], res[tagIndex:], nil
}
func (ci cipherAESGCM) decrypt(key, aad, iv []byte, ciphertext []byte, tag []byte) ([]byte, error) {
if len(key) != ci.keySize {
return nil, ErrInvalidKeySize
}
if len(tag) != TagSizeAESGCM {
return nil, ErrInvalidTagSize
}
aead, err := ci.getAEAD(key)
if err != nil {
return nil, err
}
if len(iv) != aead.NonceSize() {
return nil, ErrInvalidNonceSize
}
return aead.Open(nil, iv, append(ciphertext, tag...), aad)
}
func newAESGCM(keySize int) *cipherAESGCM {
return &cipherAESGCM{
keySize: keySize,
getAEAD: func(key []byte) (cipher.AEAD, error) {
aesCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(aesCipher)
},
}
}
func getCipher(alg EncryptionType) (*cipherAESGCM, error) {
switch alg {
case EncryptionTypeA256GCM:
return newAESGCM(32), nil
default:
return nil, ErrUnsupportedEncryptionType
}
}