forked from aws/aws-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes_gcm.go
105 lines (91 loc) · 2.06 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
98
99
100
101
102
103
104
105
package s3crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"io"
"io/ioutil"
)
// AESGCM Symmetric encryption algorithm. Since Golang designed this
// with only TLS in mind. We have to load it all into memory meaning
// this isn't streamed.
type aesGCM struct {
aead cipher.AEAD
nonce []byte
}
// newAESGCM creates a new AES GCM cipher. Expects keys to be of
// the correct size.
//
// Example:
//
// cd := &s3crypto.CipherData{
// Key: key,
// "IV": iv,
// }
// cipher, err := s3crypto.newAESGCM(cd)
func newAESGCM(cd CipherData) (Cipher, error) {
block, err := aes.NewCipher(cd.Key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &aesGCM{aesgcm, cd.IV}, nil
}
// Encrypt will encrypt the data using AES GCM
// Tag will be included as the last 16 bytes of the slice
func (c *aesGCM) Encrypt(src io.Reader) io.Reader {
reader := &gcmEncryptReader{
encrypter: c.aead,
nonce: c.nonce,
src: src,
}
return reader
}
type gcmEncryptReader struct {
encrypter cipher.AEAD
nonce []byte
src io.Reader
buf *bytes.Buffer
}
func (reader *gcmEncryptReader) Read(data []byte) (int, error) {
if reader.buf == nil {
b, err := ioutil.ReadAll(reader.src)
if err != nil {
return len(b), err
}
b = reader.encrypter.Seal(b[:0], reader.nonce, b, nil)
reader.buf = bytes.NewBuffer(b)
}
return reader.buf.Read(data)
}
// Decrypt will decrypt the data using AES GCM
func (c *aesGCM) Decrypt(src io.Reader) io.Reader {
return &gcmDecryptReader{
decrypter: c.aead,
nonce: c.nonce,
src: src,
}
}
type gcmDecryptReader struct {
decrypter cipher.AEAD
nonce []byte
src io.Reader
buf *bytes.Buffer
}
func (reader *gcmDecryptReader) Read(data []byte) (int, error) {
if reader.buf == nil {
b, err := ioutil.ReadAll(reader.src)
if err != nil {
return len(b), err
}
b, err = reader.decrypter.Open(b[:0], reader.nonce, b, nil)
if err != nil {
return len(b), err
}
reader.buf = bytes.NewBuffer(b)
}
return reader.buf.Read(data)
}