/
crypto.go
569 lines (481 loc) · 12.9 KB
/
crypto.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package mls
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/asn1"
"fmt"
"hash"
"math/big"
"github.com/cisco/go-hpke"
"github.com/cisco/go-tls-syntax"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/ed25519"
)
type CipherSuite uint16
const (
X25519_AES128GCM_SHA256_Ed25519 CipherSuite = 0x0001
P256_AES128GCM_SHA256_P256 CipherSuite = 0x0002
X25519_CHACHA20POLY1305_SHA256_Ed25519 CipherSuite = 0x0003
X448_AES256GCM_SHA512_Ed448 CipherSuite = 0x0004 // UNSUPPORTED
P521_AES256GCM_SHA512_P521 CipherSuite = 0x0005
X448_CHACHA20POLY1305_SHA512_Ed448 CipherSuite = 0x0006 // UNSUPPORTED
)
func (cs CipherSuite) supported() bool {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519,
P256_AES128GCM_SHA256_P256,
P521_AES256GCM_SHA512_P521,
X25519_CHACHA20POLY1305_SHA256_Ed25519:
return true
}
return false
}
func (cs CipherSuite) String() string {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519:
return "X25519_AES128GCM_SHA256_Ed25519"
case P256_AES128GCM_SHA256_P256:
return "P256_AES128GCM_SHA256_P256"
case X25519_CHACHA20POLY1305_SHA256_Ed25519:
return "X25519_CHACHA20POLY1305_SHA256_Ed25519"
case X448_AES256GCM_SHA512_Ed448:
return "X448_AES256GCM_SHA512_Ed448"
case P521_AES256GCM_SHA512_P521:
return "P521_AES256GCM_SHA512_P521"
case X448_CHACHA20POLY1305_SHA512_Ed448:
return "X448_CHACHA20POLY1305_SHA512_Ed448"
}
return "UnknownCipherSuite"
}
type cipherConstants struct {
KeySize int
NonceSize int
SecretSize int
HPKEKEM hpke.KEMID
HPKEKDF hpke.KDFID
HPKEAEAD hpke.AEADID
}
func (cs CipherSuite) Constants() cipherConstants {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519:
return cipherConstants{
KeySize: 16,
NonceSize: 12,
SecretSize: 32,
HPKEKEM: hpke.DHKEM_X25519,
HPKEKDF: hpke.KDF_HKDF_SHA256,
HPKEAEAD: hpke.AEAD_AESGCM128,
}
case P256_AES128GCM_SHA256_P256:
return cipherConstants{
KeySize: 16,
NonceSize: 12,
SecretSize: 32,
HPKEKEM: hpke.DHKEM_P256,
HPKEKDF: hpke.KDF_HKDF_SHA256,
HPKEAEAD: hpke.AEAD_AESGCM128,
}
case X25519_CHACHA20POLY1305_SHA256_Ed25519:
return cipherConstants{
KeySize: 32,
NonceSize: 12,
SecretSize: 32,
HPKEKEM: hpke.DHKEM_X25519,
HPKEKDF: hpke.KDF_HKDF_SHA256,
HPKEAEAD: hpke.AEAD_CHACHA20POLY1305,
}
case P521_AES256GCM_SHA512_P521:
return cipherConstants{
KeySize: 32,
NonceSize: 12,
SecretSize: 64,
HPKEKEM: hpke.DHKEM_P521,
HPKEKDF: hpke.KDF_HKDF_SHA512,
HPKEAEAD: hpke.AEAD_AESGCM256,
}
}
panic("Unsupported ciphersuite")
}
func (cs CipherSuite) Scheme() SignatureScheme {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519:
return Ed25519
case P256_AES128GCM_SHA256_P256:
return ECDSA_SECP256R1_SHA256
case X25519_CHACHA20POLY1305_SHA256_Ed25519:
return Ed25519
case P521_AES256GCM_SHA512_P521:
return ECDSA_SECP521R1_SHA512
}
panic("Unsupported ciphersuite")
}
func (cs CipherSuite) zero() []byte {
return bytes.Repeat([]byte{0x00}, cs.newDigest().Size())
}
func (cs CipherSuite) newDigest() hash.Hash {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519, P256_AES128GCM_SHA256_P256,
X25519_CHACHA20POLY1305_SHA256_Ed25519:
return sha256.New()
case X448_AES256GCM_SHA512_Ed448, P521_AES256GCM_SHA512_P521:
return sha512.New()
}
panic("Unsupported ciphersuite")
}
func (cs CipherSuite) Digest(data []byte) []byte {
d := cs.newDigest()
d.Write(data)
return d.Sum(nil)
}
func (cs CipherSuite) NewHMAC(key []byte) hash.Hash {
return hmac.New(cs.newDigest, key)
}
func (cs CipherSuite) NewAEAD(key []byte) (cipher.AEAD, error) {
switch cs {
case X25519_AES128GCM_SHA256_Ed25519, P256_AES128GCM_SHA256_P256:
fallthrough
case X448_AES256GCM_SHA512_Ed448, P521_AES256GCM_SHA512_P521:
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(block)
case X25519_CHACHA20POLY1305_SHA256_Ed25519:
return chacha20poly1305.New(key)
}
panic("Unsupported ciphersuite")
}
func (cs CipherSuite) hkdfExtract(salt, ikm []byte) []byte {
mac := cs.NewHMAC(salt)
mac.Write(ikm)
return mac.Sum(nil)
}
func (cs CipherSuite) hkdfExpand(secret, info []byte, size int) []byte {
last := []byte{}
buf := []byte{}
counter := byte(1)
for len(buf) < size {
mac := cs.NewHMAC(secret)
mac.Write(last)
mac.Write(info)
mac.Write([]byte{counter})
last = mac.Sum(nil)
counter += 1
buf = append(buf, last...)
}
return buf[:size]
}
type hkdfLabel struct {
Length uint16
Label []byte `tls:"head=1"`
Context []byte `tls:"head=4"`
}
func (cs CipherSuite) hkdfExpandLabel(secret []byte, label string, context []byte, length int) []byte {
mlsLabel := []byte("mls10 " + label)
labelData, err := syntax.Marshal(hkdfLabel{uint16(length), mlsLabel, context})
if err != nil {
panic(fmt.Errorf("Error marshaling HKDF label: %v", err))
}
return cs.hkdfExpand(secret, labelData, length)
}
func (cs CipherSuite) deriveSecret(secret []byte, label string, context []byte) []byte {
contextHash := cs.Digest(context)
size := cs.Constants().SecretSize
return cs.hkdfExpandLabel(secret, label, contextHash, size)
}
type applicationContext struct {
Node NodeIndex
Generation uint32
}
func (cs CipherSuite) deriveAppSecret(secret []byte, label string, node NodeIndex, generation uint32, length int) []byte {
ctx, err := syntax.Marshal(applicationContext{node, generation})
if err != nil {
panic(fmt.Errorf("Error marshaling application context: %v", err))
}
return cs.hkdfExpandLabel(secret, label, ctx, length)
}
func (cs CipherSuite) hpke() HPKEInstance {
cc := cs.Constants()
suite, err := hpke.AssembleCipherSuite(cc.HPKEKEM, cc.HPKEKDF, cc.HPKEAEAD)
if err != nil {
panic("Unable to construct HPKE ciphersuite")
}
return HPKEInstance{cs, suite}
}
///
/// HPKE
///
type HPKEPrivateKey struct {
Data []byte `tls:"head=2"`
PublicKey HPKEPublicKey
}
type HPKEPublicKey struct {
Data []byte `tls:"head=2"`
}
func (k HPKEPublicKey) Equals(o HPKEPublicKey) bool {
return bytes.Equal(k.Data, o.Data)
}
type HPKECiphertext struct {
KEMOutput []byte `tls:"head=2"`
Ciphertext []byte `tls:"head=4"`
}
type HPKEInstance struct {
BaseSuite CipherSuite
Suite hpke.CipherSuite
}
func (h HPKEInstance) Generate() (HPKEPrivateKey, error) {
priv, pub, err := h.Suite.KEM.GenerateKeyPair(rand.Reader)
if err != nil {
return HPKEPrivateKey{}, err
}
key := HPKEPrivateKey{
Data: h.Suite.KEM.MarshalPrivate(priv),
PublicKey: HPKEPublicKey{h.Suite.KEM.Marshal(pub)},
}
return key, nil
}
func (h HPKEInstance) Derive(seed []byte) (HPKEPrivateKey, error) {
keyPairSecretSize := 0
switch h.BaseSuite.Constants().HPKEKEM {
case hpke.DHKEM_X25519:
keyPairSecretSize = 32
case hpke.DHKEM_P256:
keyPairSecretSize = 32
case hpke.DHKEM_P521:
keyPairSecretSize = 66
case hpke.DHKEM_X448:
keyPairSecretSize = 56
}
cs := h.BaseSuite
keyPairSecret := cs.hkdfExpandLabel(seed, "key pair", []byte{}, keyPairSecretSize)
var priv hpke.KEMPrivateKey
var err error
switch h.BaseSuite.Constants().HPKEKEM {
case hpke.DHKEM_P256, hpke.DHKEM_P521, hpke.DHKEM_X25519:
priv, err = h.Suite.KEM.UnmarshalPrivate(keyPairSecret)
case hpke.DHKEM_X448:
priv, err = h.Suite.KEM.UnmarshalPrivate(keyPairSecret)
}
if err != nil {
return HPKEPrivateKey{}, err
}
pub := priv.PublicKey()
key := HPKEPrivateKey{
Data: h.Suite.KEM.MarshalPrivate(priv),
PublicKey: HPKEPublicKey{h.Suite.KEM.Marshal(pub)},
}
return key, nil
}
func (h HPKEInstance) Encrypt(pub HPKEPublicKey, aad, pt []byte) (HPKECiphertext, error) {
pkR, err := h.Suite.KEM.Unmarshal(pub.Data)
if err != nil {
return HPKECiphertext{}, err
}
enc, ctx, err := hpke.SetupBaseS(h.Suite, rand.Reader, pkR, nil)
if err != nil {
return HPKECiphertext{}, err
}
ct := ctx.Seal(aad, pt)
return HPKECiphertext{enc, ct}, nil
}
func (h HPKEInstance) Decrypt(priv HPKEPrivateKey, aad []byte, ct HPKECiphertext) ([]byte, error) {
skR, err := h.Suite.KEM.UnmarshalPrivate(priv.Data)
if err != nil {
return nil, err
}
ctx, err := hpke.SetupBaseR(h.Suite, skR, ct.KEMOutput, nil)
if err != nil {
return nil, err
}
return ctx.Open(aad, ct.Ciphertext)
}
///
/// Signing
///
type SignaturePrivateKey struct {
Data []byte `tls:"head=2"`
PublicKey SignaturePublicKey
}
type SignaturePublicKey struct {
Data []byte `tls:"head=2"`
}
func (pub SignaturePublicKey) Equals(other SignaturePublicKey) bool {
return bytes.Equal(pub.Data, other.Data)
}
type SignatureScheme uint16
const (
ECDSA_SECP256R1_SHA256 SignatureScheme = 0x0403
ECDSA_SECP521R1_SHA512 SignatureScheme = 0x0603
Ed25519 SignatureScheme = 0x0807
)
func (ss SignatureScheme) supported() bool {
switch ss {
case ECDSA_SECP256R1_SHA256, ECDSA_SECP521R1_SHA512, Ed25519:
return true
}
return false
}
func (ss SignatureScheme) String() string {
switch ss {
case ECDSA_SECP256R1_SHA256:
return "ECDSA_SECP256R1_SHA256"
case ECDSA_SECP521R1_SHA512:
return "ECDSA_SECP521R1_SHA512"
case Ed25519:
return "Ed25519"
}
return "UnknownSignatureScheme"
}
func (ss SignatureScheme) Derive(preSeed []byte) (SignaturePrivateKey, error) {
switch ss {
case ECDSA_SECP256R1_SHA256:
h := sha256.New()
h.Write(preSeed)
priv := h.Sum(nil)
curve := elliptic.P256()
x, y := curve.Params().ScalarBaseMult(priv)
pub := elliptic.Marshal(curve, x, y)
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
case ECDSA_SECP521R1_SHA512:
h := sha512.New()
h.Write(preSeed)
priv := h.Sum(nil)
curve := elliptic.P521()
x, y := curve.Params().ScalarBaseMult(priv)
pub := elliptic.Marshal(curve, x, y)
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
case Ed25519:
h := sha256.New()
h.Write(preSeed)
seed := h.Sum(nil)
priv := ed25519.NewKeyFromSeed(seed)
pub := priv.Public().(ed25519.PublicKey)
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
}
panic("Unsupported algorithm")
}
func (ss SignatureScheme) Generate() (SignaturePrivateKey, error) {
switch ss {
case ECDSA_SECP256R1_SHA256:
curve := elliptic.P256()
priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
if err != nil {
return SignaturePrivateKey{}, err
}
pub := elliptic.Marshal(curve, x, y)
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
case ECDSA_SECP521R1_SHA512:
curve := elliptic.P521()
priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
if err != nil {
return SignaturePrivateKey{}, err
}
pub := elliptic.Marshal(curve, x, y)
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
case Ed25519:
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return SignaturePrivateKey{}, err
}
key := SignaturePrivateKey{
Data: priv,
PublicKey: SignaturePublicKey{pub},
}
return key, nil
}
panic("Unsupported algorithm")
}
type ecdsaSignature struct {
R, S *big.Int
}
func (ss SignatureScheme) Sign(priv *SignaturePrivateKey, message []byte) ([]byte, error) {
switch ss {
case ECDSA_SECP256R1_SHA256:
h := sha256.New()
h.Write(message)
digest := h.Sum(nil)
ecPriv := &ecdsa.PrivateKey{
D: big.NewInt(0).SetBytes(priv.Data),
PublicKey: ecdsa.PublicKey{
Curve: elliptic.P256(),
},
}
return ecPriv.Sign(rand.Reader, digest, nil)
case ECDSA_SECP521R1_SHA512:
h := sha512.New()
h.Write(message)
digest := h.Sum(nil)
ecPriv := &ecdsa.PrivateKey{
D: big.NewInt(0).SetBytes(priv.Data),
PublicKey: ecdsa.PublicKey{
Curve: elliptic.P521(),
},
}
return ecPriv.Sign(rand.Reader, digest, nil)
case Ed25519:
priv25519 := ed25519.PrivateKey(priv.Data)
return ed25519.Sign(priv25519, message), nil
}
panic("Unsupported algorithm")
}
func (ss SignatureScheme) Verify(pub *SignaturePublicKey, message, signature []byte) bool {
switch ss {
case ECDSA_SECP256R1_SHA256:
h := sha256.New()
h.Write(message)
digest := h.Sum(nil)
curve := elliptic.P256()
x, y := elliptic.Unmarshal(curve, pub.Data)
var sig ecdsaSignature
_, err := asn1.Unmarshal(signature, &sig)
if err != nil {
return false
}
ecPub := &ecdsa.PublicKey{Curve: curve, X: x, Y: y}
return ecdsa.Verify(ecPub, digest, sig.R, sig.S)
case ECDSA_SECP521R1_SHA512:
h := sha512.New()
h.Write(message)
digest := h.Sum(nil)
curve := elliptic.P521()
x, y := elliptic.Unmarshal(curve, pub.Data)
var sig ecdsaSignature
_, err := asn1.Unmarshal(signature, &sig)
if err != nil {
return false
}
ecPub := &ecdsa.PublicKey{Curve: curve, X: x, Y: y}
return ecdsa.Verify(ecPub, digest, sig.R, sig.S)
case Ed25519:
pub25519 := ed25519.PublicKey(pub.Data)
return ed25519.Verify(pub25519, message, signature)
}
panic("Unsupported algorithm")
}