-
Notifications
You must be signed in to change notification settings - Fork 0
/
AES.go
289 lines (207 loc) · 5.4 KB
/
AES.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package hippo
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
)
// AESMode captures the operational mode of the cipher.
type AESMode int
var modelabels = []string{
"cbc",
"gcm",
}
const (
CBC AESMode = iota // Cipher block chaining mode.
GCM // Galois/counter mode.
)
// ErrUnsupportedMode is returned if a key is given that indicates a
// mode with no registered implementation.
var ErrUnsupportedMode = fmt.Errorf("Unknown mode")
// AlgorithmAES_256_CBC is a constant string identifying the AES
// algorithm with 256 bit key and cipher block chaining mode.
const AlgorithmAES_256_CBC = "aes-256-cbc"
// AlgorithmAES_256_CBC is a constant string identifying the AES
// algorithm with 256 bit key and Galois/counter mode.
const AlgorithmAES_256_GCM = "aes-256-gcm"
func init() {
modes := []aes_t{
aes_t{bits: 256, mode: CBC},
aes_t{bits: 256, mode: GCM},
}
for i := range modes {
err := RegisterSKCipherer(&modes[i])
if err != nil {
panic(err)
}
}
}
type aes_t struct {
bits int
mode AESMode
}
// Algorithm returns the label identifying the algorithm and
// parameterization of this cipherer.
func (x *aes_t) Algorithm() string {
return fmt.Sprintf("aes-%v-%v", x.bits, modelabels[x.mode])
}
// Generate creates a new SKCipher.
func (x *aes_t) Generate() (SKCipher, error) {
var cipher AESCipher
cipher.Algorithm = x.Algorithm()
cipher.Bits = x.bits
cipher.Mode = x.mode
cipher.Key = make([]byte, x.bits/8)
_, err := rand.Read(cipher.Key)
if err != nil {
return nil, err
}
return &cipher, nil
}
// New wraps the given secret key in an SKCipher.
func (x *aes_t) New(key PrivateKey) (SKCipher, error) {
var cipher AESCipher
var err error
cipher.Algorithm = x.Algorithm()
cipher.Bits = x.bits
cipher.Mode = x.mode
err = cipher.SetKey(key)
if err != nil {
return nil, err
}
return &cipher, nil
}
// An AESCipher is an actionable secret key.
type AESCipher struct {
Algorithm string
Bits int
Mode AESMode
Key []byte
}
// SecretKey returns a JSON Base64-URL encoded marshaling of the
// cipher's secret key.
func (x *AESCipher) SecretKey() PrivateKey {
key := PrivateKey{
Algorithm: x.Algorithm,
Private: base64.RawURLEncoding.EncodeToString(x.Key),
}
return key
}
// SetKey sets the cipher's secret key from the given PrivateKey
// containing JSON Base64-URL encoded data.
func (x *AESCipher) SetKey(key PrivateKey) error {
if key.Algorithm != x.Algorithm {
return fmt.Errorf("Algorithm mismatch %v vs %v", key.Algorithm, x.Algorithm)
}
keydata, ok := key.Private.(string)
if !ok {
return fmt.Errorf("Data is not a string")
}
var err error
x.Key, err = base64.RawURLEncoding.DecodeString(keydata)
if err != nil {
return err
}
if len(x.Key) != x.Bits/8 {
return fmt.Errorf("Incorrect key bits")
}
return nil
}
// Encrypt produces cipherdata for the given plaindata.
func (x *AESCipher) Encrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(x.Key)
if err != nil {
return nil, err
}
switch x.Mode {
case CBC:
return encrypt_cbc(block, data)
case GCM:
return encrypt_gcm(block, data)
}
return nil, ErrUnsupportedMode
}
func encrypt_cbc(block cipher.Block, data []byte) ([]byte, error) {
msg := pad(data)
ciphertext := make([]byte, aes.BlockSize+len(msg))
iv := ciphertext[:aes.BlockSize]
_, err := rand.Read(iv)
if err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], msg)
return ciphertext, nil
}
func encrypt_gcm(block cipher.Block, data []byte) ([]byte, error) {
mode, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, mode.NonceSize(), mode.NonceSize()+len(data))
_, err = rand.Read(nonce)
if err != nil {
return nil, err
}
ciphertext := mode.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
// Decrypt takes cipherdata and produces plaindata. N.B. that
// depending on the mode an invalid key or data may or may not
// generate an error.
func (x *AESCipher) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(x.Key)
if err != nil {
return nil, err
}
switch x.Mode {
case CBC:
return decrypt_cbc(block, data)
case GCM:
return decrypt_gcm(block, data)
}
return nil, ErrUnsupportedMode
}
func decrypt_cbc(block cipher.Block, data []byte) ([]byte, error) {
if (len(data) % aes.BlockSize) != 0 {
return nil, fmt.Errorf("Data must be multiple of blocksize")
}
iv := data[:aes.BlockSize]
msg := data[aes.BlockSize:]
dst := make([]byte, len(msg))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(dst, msg)
plaintext, err := unpad(dst)
if err != nil {
return nil, err
}
return plaintext, nil
}
func decrypt_gcm(block cipher.Block, data []byte) ([]byte, error) {
mode, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := data[:mode.NonceSize()]
msg := data[mode.NonceSize():]
plaintext, err := mode.Open(nil, nonce, msg, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func pad(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func unpad(src []byte) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding > length {
return nil, fmt.Errorf("Invalid padding")
}
return src[:(length - unpadding)], nil
}