-
Notifications
You must be signed in to change notification settings - Fork 3
/
ecies.go
345 lines (280 loc) · 8.25 KB
/
ecies.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package rome
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/asn1"
"errors"
"hash"
"golang.org/x/crypto/chacha20"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/salsa20"
)
// Cipher specifies what cipher to use in encryption
type Cipher uint8
const (
// CipherAES_GCM is a AHEAD cipher and is recommended for most use cases
CipherAES_GCM = iota + 1
// CipherChacha20 is a UNAUTHENTICATED cipher and is only provided with the expectation
// you will handle the data integrity by using a MAC. Or instead please use one of the
// provided authenticated ChaCha ciphers below.
CipherChacha20
// CipherChacha20_SHA256 is a authenticated Encrypt-then-MAC (EtM) cipher using ChaCha20
// the MAC is a SHA256 hmac with the secret being the encryption key
CipherChacha20_SHA256
// CipherChacha20_SHA512 is a authenticated Encrypt-then-MAC (EtM) cipher using ChaCha20
// the MAC is a SHA512 hmac with the secret being the encryption key
CipherChacha20_SHA512
// CipherChaCha20Poly1305 is a authenticated cipher which takes a 256bit key
CipherChaCha20Poly1305
// CipherSalsa20 is a UNAUTHENTICATED cipher and is only provided with the expectation
// you will handle the data integrity by using a MAC. Or instead please use one of the
// provided authenticated ChaCha ciphers below.
CipherSalsa20
)
var (
// ErrUnknownCipher is returned if the cipher provided is unsupported
ErrUnknownCipher = errors.New("unknown cipher suite")
// ErrCipherTxtSmall is returned if the data is so small it must be invalid
ErrCipherTxtSmall = errors.New("cipher text is too small")
// ErrAuthFail is returned when the ciphertext mac fails
ErrAuthFail = errors.New("message authentication failed")
// ErrKeySize is returned if the key is not supported in the encryption algorithm
ErrKeySize = errors.New("key size not supported")
)
// Encrypt uses ECIES hybrid encryption. Cipher is used to specify the encryption
// algorithm and hash is used to derive the key via the ECDH
func (k *ECPublicKey) Encrypt(m []byte, c Cipher, hash hash.Hash, options ...Option) ([]byte, error) {
// generate ephemeral key to perform ECDH
// it is important this key is never used again
k2, err := k.generateEphemeralKey()
if err != nil {
return nil, err
}
// perform ECDH with provided hash function and the new ephemeral key
secret, err := k.DH(hash, k2, options...)
if err != nil {
return nil, err
}
// format public key in ASN.1 DER bytes
public, err := k2.Public().KeyASN1()
if err != nil {
return nil, err
}
// create new output buffer and write the ephemeral public key
output := bytes.NewBuffer(public)
nonceLen := 12
if c == CipherSalsa20 {
nonceLen = 8
}
// generate a nonce for added security
nonce := make([]byte, nonceLen)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
switch c {
case CipherAES_GCM:
b, err := aes.NewCipher(secret)
if err != nil {
return nil, err
}
cipher, err := cipher.NewGCMWithNonceSize(b, len(nonce))
if err != nil {
return nil, err
}
// prepend the nonce with the cipher text to the end
// the nonce is a fixed length so we should be able to decode
// it on the other end
ciphertext := cipher.Seal(nil, nonce, m, nil)
output.Write(append(nonce, ciphertext...))
return output.Bytes(), nil
case CipherChacha20:
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
dst := make([]byte, len(m))
b.XORKeyStream(dst, m)
output.Write(append(nonce, dst...))
return output.Bytes(), nil
case CipherChacha20_SHA256:
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
dst := make([]byte, len(m))
b.XORKeyStream(dst, m)
// calculate SHA256 HMAC to authenticate the cipher
h := hmac.New(sha256.New, secret)
h.Write(dst)
output.Write(nonce)
output.Write(h.Sum(nil))
output.Write(dst)
return output.Bytes(), nil
case CipherChacha20_SHA512:
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
dst := make([]byte, len(m))
b.XORKeyStream(dst, m)
// calculate SHA512 HMAC to authenticate the cipher
h := hmac.New(sha512.New, secret)
h.Write(dst)
output.Write(nonce)
output.Write(h.Sum(nil))
output.Write(dst)
return output.Bytes(), nil
case CipherChaCha20Poly1305:
b, err := chacha20poly1305.New(secret)
if err != nil {
return nil, err
}
ciphertext := b.Seal(nil, nonce, m, nil)
output.Write(nonce)
output.Write(ciphertext)
return output.Bytes(), nil
case CipherSalsa20:
dst := make([]byte, len(m))
key := [32]byte{}
if len(secret) != 32 {
return nil, ErrKeySize
}
copy(key[:], secret)
salsa20.XORKeyStream(dst, m, nonce, &key)
output.Write(nonce)
output.Write(dst)
return output.Bytes(), nil
default:
return nil, ErrUnknownCipher
}
}
// Decrypt uses ECIES hybrid encryption. Cipher is used to specify the encryption
// algorithm and hash is used to derive the key via the ECDH
func (k *ECKey) Decrypt(ciphertext []byte, c Cipher, hash hash.Hash, options ...Option) ([]byte, error) {
// unmarshal ASN.1 der bytes to get length
var pub pkixPublicKey
rest, err := asn1.Unmarshal(ciphertext, &pub)
if err != nil {
return nil, err
}
// calculate and trim public key ASN.1 bytes
public := ciphertext[:len(ciphertext)-len(rest)]
// parse public key
key, err := ParseECPublicASN1(public)
if err != nil {
return nil, err
}
// trim public key prefix
ciphertext = ciphertext[len(public):]
secret, err := key.DH(hash, k, options...)
if err != nil {
return nil, err
}
nonceLen := 12
if c == CipherSalsa20 {
nonceLen = 8
}
// range check length
if len(ciphertext) < nonceLen {
return nil, ErrCipherTxtSmall
}
nonce := ciphertext[:nonceLen]
ciphertext = ciphertext[nonceLen:]
switch c {
case CipherAES_GCM:
b, err := aes.NewCipher(secret)
if err != nil {
return nil, err
}
cipher, err := cipher.NewGCMWithNonceSize(b, len(nonce))
if err != nil {
return nil, err
}
return cipher.Open(nil, nonce, ciphertext, nil)
case CipherChacha20:
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
// decrypt by xoring the ciphertext back
plaintext := make([]byte, len(ciphertext))
b.XORKeyStream(plaintext, ciphertext)
return plaintext, nil
case CipherChacha20_SHA256:
if len(ciphertext) < 32 {
return nil, ErrCipherTxtSmall
}
mac := ciphertext[:32]
ciphertext = ciphertext[32:]
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
// decrypt by xoring the ciphertext back
plaintext := make([]byte, len(ciphertext))
b.XORKeyStream(plaintext, ciphertext)
// calculate SHA256 HMAC to authenticate the cipher
h := hmac.New(sha256.New, secret)
h.Write(ciphertext)
if !bytes.Equal(h.Sum(nil), mac) {
return nil, ErrAuthFail
}
return plaintext, nil
case CipherChacha20_SHA512:
if len(ciphertext) < 64 {
return nil, ErrCipherTxtSmall
}
mac := ciphertext[:64]
ciphertext = ciphertext[64:]
b, err := chacha20.NewUnauthenticatedCipher(secret, nonce)
if err != nil {
return nil, err
}
// decrypt by xoring the ciphertext back
plaintext := make([]byte, len(ciphertext))
b.XORKeyStream(plaintext, ciphertext)
// calculate SHA512 HMAC to authenticate the cipher
h := hmac.New(sha512.New, secret)
h.Write(ciphertext)
if !bytes.Equal(h.Sum(nil), mac) {
return nil, ErrAuthFail
}
return plaintext, nil
case CipherChaCha20Poly1305:
b, err := chacha20poly1305.New(secret)
if err != nil {
return nil, err
}
return b.Open(nil, nonce, ciphertext, nil)
case CipherSalsa20:
dst := make([]byte, len(ciphertext))
key := [32]byte{}
if len(secret) != 32 {
return nil, ErrKeySize
}
copy(key[:], secret)
salsa20.XORKeyStream(dst, ciphertext, nonce, &key)
return dst, nil
}
return nil, ErrUnknownCipher
}
// generateEphemeralKey will generate a temporary key on the same curve
func (k *ECPublicKey) generateEphemeralKey() (*ECKey, error) {
k2, err := ecdsa.GenerateKey(k.ecdsa.Curve, rand.Reader)
if err != nil {
return nil, err
}
return &ECKey{
priv: k2.D.Bytes(),
ecdsa: k2,
pub: &ECPublicKey{
ecdsa: &k2.PublicKey,
},
}, nil
}