-
Notifications
You must be signed in to change notification settings - Fork 29
/
aes_gcm.go
98 lines (70 loc) · 2.24 KB
/
aes_gcm.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
package jose
import (
"fmt"
"errors"
"crypto/aes"
"crypto/cipher"
"github.com/dvsekhvalnov/jose2go/arrays"
)
// AES GCM authenticated encryption algorithm implementation
type AesGcm struct{
keySizeBits int
}
func init() {
RegisterJwe(&AesGcm{keySizeBits:128})
RegisterJwe(&AesGcm{keySizeBits:192})
RegisterJwe(&AesGcm{keySizeBits:256})
}
func (alg *AesGcm) Name() string {
switch alg.keySizeBits {
case 128: return A128GCM
case 192: return A192GCM
default: return A256GCM
}
}
func (alg *AesGcm) KeySizeBits() int {
return alg.keySizeBits
}
func (alg *AesGcm) Encrypt(aad, plainText, cek []byte) (iv, cipherText, authTag []byte, err error) {
cekSizeBits := len(cek)<<3
if cekSizeBits != alg.keySizeBits {
return nil,nil,nil, errors.New(fmt.Sprintf("AesGcm.Encrypt(): expected key of size %v bits, but was given %v bits.",alg.keySizeBits, cekSizeBits))
}
if iv,err = arrays.Random(12);err!=nil {
return nil,nil,nil,err
}
var block cipher.Block
if block, err = aes.NewCipher(cek);err!=nil {
return nil,nil,nil,err
}
var aesgcm cipher.AEAD
if aesgcm,err = cipher.NewGCM(block);err!=nil {
return nil,nil,nil,err
}
cipherWithTag := aesgcm.Seal(nil, iv, plainText, aad)
cipherText=cipherWithTag[:len(cipherWithTag)-aesgcm.Overhead()]
authTag=cipherWithTag[len(cipherWithTag)-aesgcm.Overhead():]
return iv, cipherText, authTag, nil
}
func (alg *AesGcm) Decrypt(aad, cek, iv, cipherText, authTag []byte) (plainText []byte, err error) {
cekSizeBits := len(cek)<<3
if cekSizeBits != alg.keySizeBits {
return nil, errors.New(fmt.Sprintf("AesGcm.Decrypt(): expected key of size %v bits, but was given %v bits.",alg.keySizeBits, cekSizeBits))
}
var block cipher.Block
if block, err = aes.NewCipher(cek);err!=nil {
return nil,err
}
var aesgcm cipher.AEAD
if aesgcm,err = cipher.NewGCM(block);err!=nil {
return nil,err
}
cipherWithTag:=append(cipherText,authTag...)
if nonceSize := len(iv); nonceSize != aesgcm.NonceSize() {
return nil, errors.New(fmt.Sprintf("AesGcm.Decrypt(): expected nonce of size %v bits, but was given %v bits.", aesgcm.NonceSize()<<3, nonceSize<<3))
}
if plainText,err = aesgcm.Open(nil, iv, cipherWithTag, aad);err!=nil {
return nil,err
}
return plainText,nil
}