-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathpkg.templ.go
496 lines (426 loc) · 11.3 KB
/
pkg.templ.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
// +build ignore
// The previous line (and this one up to the warning below) is removed by the
// template generator.
// Code generated from pkg.templ.go. DO NOT EDIT.
// Package {{.Pkg}} implements the IND-CCA2 secure key encapsulation mechanism
{{ if .NIST -}}
// {{.KemName}} as defined in FIPS203.
{{- else -}}
// {{.KemName}} as submitted to round 3 of the NIST PQC competition and
// described in
//
// https://pq-crystals.org/kyber/data/kyber-specification-round3.pdf
{{- end }}
package {{.Pkg}}
import (
"bytes"
"crypto/subtle"
"io"
"github.com/cloudflare/circl/internal/sha3"
"github.com/cloudflare/circl/kem"
cpapke "github.com/cloudflare/circl/pke/kyber/{{.PkePkg}}"
cryptoRand "crypto/rand"
)
const (
// Size of seed for NewKeyFromSeed
KeySeedSize = cpapke.KeySeedSize + 32
// Size of seed for EncapsulateTo.
EncapsulationSeedSize = 32
// Size of the established shared key.
SharedKeySize = 32
// Size of the encapsulated shared key.
CiphertextSize = cpapke.CiphertextSize
// Size of a packed public key.
PublicKeySize = cpapke.PublicKeySize
// Size of a packed private key.
PrivateKeySize = cpapke.PrivateKeySize + cpapke.PublicKeySize + 64
)
// Type of a {{.KemName}} public key
type PublicKey struct {
pk *cpapke.PublicKey
hpk [32]byte // H(pk)
}
// Type of a {{.KemName}} private key
type PrivateKey struct {
sk *cpapke.PrivateKey
pk *cpapke.PublicKey
hpk [32]byte // H(pk)
z [32]byte
}
// NewKeyFromSeed derives a public/private keypair deterministically
// from the given seed.
//
// Panics if seed is not of length KeySeedSize.
func NewKeyFromSeed(seed []byte) (*PublicKey, *PrivateKey) {
var sk PrivateKey
var pk PublicKey
if len(seed) != KeySeedSize {
panic("seed must be of length KeySeedSize")
}
{{ if .NIST -}}
pk.pk, sk.sk = cpapke.NewKeyFromSeedMLKEM(seed[:cpapke.KeySeedSize])
{{- else -}}
pk.pk, sk.sk = cpapke.NewKeyFromSeed(seed[:cpapke.KeySeedSize])
{{- end }}
sk.pk = pk.pk
copy(sk.z[:], seed[cpapke.KeySeedSize:])
// Compute H(pk)
var ppk [cpapke.PublicKeySize]byte
sk.pk.Pack(ppk[:])
h := sha3.New256()
h.Write(ppk[:])
h.Read(sk.hpk[:])
copy(pk.hpk[:], sk.hpk[:])
return &pk, &sk
}
// GenerateKeyPair generates public and private keys using entropy from rand.
// If rand is nil, crypto/rand.Reader will be used.
func GenerateKeyPair(rand io.Reader) (*PublicKey, *PrivateKey, error) {
var seed [KeySeedSize]byte
if rand == nil {
rand = cryptoRand.Reader
}
_, err := io.ReadFull(rand, seed[:])
if err != nil {
return nil, nil, err
}
pk, sk := NewKeyFromSeed(seed[:])
return pk, sk, nil
}
// EncapsulateTo generates a shared key and ciphertext that contains it
// for the public key using randomness from seed and writes the shared key
// to ss and ciphertext to ct.
//
// Panics if ss, ct or seed are not of length SharedKeySize, CiphertextSize
// and EncapsulationSeedSize respectively.
//
// seed may be nil, in which case crypto/rand.Reader is used to generate one.
func (pk *PublicKey) EncapsulateTo(ct, ss []byte, seed []byte) {
if seed == nil {
seed = make([]byte, EncapsulationSeedSize)
if _, err := cryptoRand.Read(seed[:]); err != nil {
panic(err)
}
} else {
if len(seed) != EncapsulationSeedSize {
panic("seed must be of length EncapsulationSeedSize")
}
}
if len(ct) != CiphertextSize {
panic("ct must be of length CiphertextSize")
}
if len(ss) != SharedKeySize {
panic("ss must be of length SharedKeySize")
}
var m [32]byte
{{ if .NIST -}}
copy(m[:], seed)
{{- else -}}
// m = H(seed), the hash of shame
h := sha3.New256()
h.Write(seed)
h.Read(m[:])
{{- end }}
// (K', r) = G(m ‖ H(pk))
var kr [64]byte
g := sha3.New512()
g.Write(m[:])
g.Write(pk.hpk[:])
g.Read(kr[:])
// c = Kyber.CPAPKE.Enc(pk, m, r)
pk.pk.EncryptTo(ct, m[:], kr[32:])
{{ if .NIST -}}
copy(ss, kr[:SharedKeySize])
{{- else -}}
// Compute H(c) and put in second slot of kr, which will be (K', H(c)).
h.Reset()
h.Write(ct[:CiphertextSize])
h.Read(kr[32:])
// K = KDF(K' ‖ H(c))
kdf := sha3.NewShake256()
kdf.Write(kr[:])
kdf.Read(ss[:SharedKeySize])
{{- end }}
}
// DecapsulateTo computes the shared key which is encapsulated in ct
// for the private key.
//
// Panics if ct or ss are not of length CiphertextSize and SharedKeySize
// respectively.
func (sk *PrivateKey) DecapsulateTo(ss, ct []byte) {
if len(ct) != CiphertextSize {
panic("ct must be of length CiphertextSize")
}
if len(ss) != SharedKeySize {
panic("ss must be of length SharedKeySize")
}
// m' = Kyber.CPAPKE.Dec(sk, ct)
var m2 [32]byte
sk.sk.DecryptTo(m2[:], ct)
// (K'', r') = G(m' ‖ H(pk))
var kr2 [64]byte
g := sha3.New512()
g.Write(m2[:])
g.Write(sk.hpk[:])
g.Read(kr2[:])
// c' = Kyber.CPAPKE.Enc(pk, m', r')
var ct2 [CiphertextSize]byte
sk.pk.EncryptTo(ct2[:], m2[:], kr2[32:])
{{ if .NIST -}}
var ss2 [SharedKeySize]byte
// Compute shared secret in case of rejection: ss₂ = PRF(z ‖ c)
prf := sha3.NewShake256()
prf.Write(sk.z[:])
prf.Write(ct[:CiphertextSize])
prf.Read(ss2[:])
// Set ss2 to the real shared secret if c = c'.
subtle.ConstantTimeCopy(
subtle.ConstantTimeCompare(ct, ct2[:]),
ss2[:],
kr2[:SharedKeySize],
)
copy(ss, ss2[:])
{{- else -}}
// Compute H(c) and put in second slot of kr2, which will be (K'', H(c)).
h := sha3.New256()
h.Write(ct[:CiphertextSize])
h.Read(kr2[32:])
// Replace K'' by z in the first slot of kr2 if c ≠ c'.
subtle.ConstantTimeCopy(
1-subtle.ConstantTimeCompare(ct, ct2[:]),
kr2[:32],
sk.z[:],
)
// K = KDF(K''/z, H(c))
kdf := sha3.NewShake256()
kdf.Write(kr2[:])
kdf.Read(ss)
{{- end }}
}
// Packs sk to buf.
//
// Panics if buf is not of size PrivateKeySize.
func (sk *PrivateKey) Pack(buf []byte) {
if len(buf) != PrivateKeySize {
panic("buf must be of length PrivateKeySize")
}
sk.sk.Pack(buf[:cpapke.PrivateKeySize])
buf = buf[cpapke.PrivateKeySize:]
sk.pk.Pack(buf[:cpapke.PublicKeySize])
buf = buf[cpapke.PublicKeySize:]
copy(buf, sk.hpk[:])
buf = buf[32:]
copy(buf, sk.z[:])
}
// Unpacks sk from buf.
//
// Panics if buf is not of size PrivateKeySize.
{{ if .NIST -}}
//
// Returns an error if buf is not of size PrivateKeySize, or private key
// doesn't pass the ML-KEM decapsulation key check.
func (sk *PrivateKey) Unpack(buf []byte) error {
if len(buf) != PrivateKeySize {
return kem.ErrPrivKeySize
}
{{- else -}}
func (sk *PrivateKey) Unpack(buf []byte) {
if len(buf) != PrivateKeySize {
panic("buf must be of length PrivateKeySize")
}
{{- end }}
sk.sk = new(cpapke.PrivateKey)
sk.sk.Unpack(buf[:cpapke.PrivateKeySize])
buf = buf[cpapke.PrivateKeySize:]
sk.pk = new(cpapke.PublicKey)
sk.pk.Unpack(buf[:cpapke.PublicKeySize])
{{ if .NIST -}}
var hpk [32]byte
h := sha3.New256()
h.Write(buf[:cpapke.PublicKeySize])
h.Read(hpk[:])
{{ end -}}
buf = buf[cpapke.PublicKeySize:]
copy(sk.hpk[:], buf[:32])
copy(sk.z[:], buf[32:])
{{ if .NIST -}}
if !bytes.Equal(hpk[:], sk.hpk[:]) {
return kem.ErrPrivKey
}
return nil
{{ end -}}
}
// Packs pk to buf.
//
// Panics if buf is not of size PublicKeySize.
func (pk *PublicKey) Pack(buf []byte) {
if len(buf) != PublicKeySize {
panic("buf must be of length PublicKeySize")
}
pk.pk.Pack(buf)
}
// Unpacks pk from buf.
//
{{ if .NIST -}}
// Returns an error if buf is not of size PublicKeySize, or the public key
// is not normalized.
func (pk *PublicKey) Unpack(buf []byte) error {
if len(buf) != PublicKeySize {
return kem.ErrPubKeySize
}
{{- else -}}
// Panics if buf is not of size PublicKeySize.
func (pk *PublicKey) Unpack(buf []byte) {
if len(buf) != PublicKeySize {
panic("buf must be of length PublicKeySize")
}
{{- end }}
pk.pk = new(cpapke.PublicKey)
{{ if .NIST -}}
if err := pk.pk.UnpackMLKEM(buf); err != nil {
return err
}
{{- else -}}
pk.pk.Unpack(buf)
{{- end }}
// Compute cached H(pk)
h := sha3.New256()
h.Write(buf)
h.Read(pk.hpk[:])
{{ if .NIST -}}
return nil
{{- end }}
}
// Boilerplate down below for the KEM scheme API.
type scheme struct{}
var sch kem.Scheme = &scheme{}
// Scheme returns a KEM interface.
func Scheme() kem.Scheme { return sch }
func (*scheme) Name() string { return "{{.Name}}" }
func (*scheme) PublicKeySize() int { return PublicKeySize }
func (*scheme) PrivateKeySize() int { return PrivateKeySize }
func (*scheme) SeedSize() int { return KeySeedSize }
func (*scheme) SharedKeySize() int { return SharedKeySize }
func (*scheme) CiphertextSize() int { return CiphertextSize }
func (*scheme) EncapsulationSeedSize() int { return EncapsulationSeedSize }
func (sk *PrivateKey) Scheme() kem.Scheme { return sch }
func (pk *PublicKey) Scheme() kem.Scheme { return sch }
func (sk *PrivateKey) MarshalBinary() ([]byte, error) {
var ret [PrivateKeySize]byte
sk.Pack(ret[:])
return ret[:], nil
}
func (sk *PrivateKey) Equal(other kem.PrivateKey) bool {
oth, ok := other.(*PrivateKey)
if !ok {
return false
}
if sk.pk == nil && oth.pk == nil {
return true
}
if sk.pk == nil || oth.pk == nil {
return false
}
if !bytes.Equal(sk.hpk[:], oth.hpk[:]) ||
subtle.ConstantTimeCompare(sk.z[:], oth.z[:]) != 1 {
return false
}
return sk.sk.Equal(oth.sk)
}
func (pk *PublicKey) Equal(other kem.PublicKey) bool {
oth, ok := other.(*PublicKey)
if !ok {
return false
}
if pk.pk == nil && oth.pk == nil {
return true
}
if pk.pk == nil || oth.pk == nil {
return false
}
return bytes.Equal(pk.hpk[:], oth.hpk[:])
}
func (sk *PrivateKey) Public() kem.PublicKey {
pk := new(PublicKey)
pk.pk = sk.pk
copy(pk.hpk[:], sk.hpk[:])
return pk
}
func (pk *PublicKey) MarshalBinary() ([]byte, error) {
var ret [PublicKeySize]byte
pk.Pack(ret[:])
return ret[:], nil
}
func (*scheme) GenerateKeyPair() (kem.PublicKey, kem.PrivateKey, error) {
return GenerateKeyPair(cryptoRand.Reader)
}
func (*scheme) DeriveKeyPair(seed []byte) (kem.PublicKey, kem.PrivateKey) {
if len(seed) != KeySeedSize {
panic(kem.ErrSeedSize)
}
return NewKeyFromSeed(seed[:])
}
func (*scheme) Encapsulate(pk kem.PublicKey) (ct, ss []byte, err error) {
ct = make([]byte, CiphertextSize)
ss = make([]byte, SharedKeySize)
pub, ok := pk.(*PublicKey)
if !ok {
return nil, nil, kem.ErrTypeMismatch
}
pub.EncapsulateTo(ct, ss, nil)
return
}
func (*scheme) EncapsulateDeterministically(pk kem.PublicKey, seed []byte) (
ct, ss []byte, err error) {
if len(seed) != EncapsulationSeedSize {
return nil, nil, kem.ErrSeedSize
}
ct = make([]byte, CiphertextSize)
ss = make([]byte, SharedKeySize)
pub, ok := pk.(*PublicKey)
if !ok {
return nil, nil, kem.ErrTypeMismatch
}
pub.EncapsulateTo(ct, ss, seed)
return
}
func (*scheme) Decapsulate(sk kem.PrivateKey, ct []byte) ([]byte, error) {
if len(ct) != CiphertextSize {
return nil, kem.ErrCiphertextSize
}
priv, ok := sk.(*PrivateKey)
if !ok {
return nil, kem.ErrTypeMismatch
}
ss := make([]byte, SharedKeySize)
priv.DecapsulateTo(ss, ct)
return ss, nil
}
func (*scheme) UnmarshalBinaryPublicKey(buf []byte) (kem.PublicKey, error) {
var ret PublicKey
{{ if .NIST -}}
if err := ret.Unpack(buf); err != nil {
return nil, err
}
{{- else -}}
if len(buf) != PublicKeySize {
return nil, kem.ErrPubKeySize
}
ret.Unpack(buf)
{{- end }}
return &ret, nil
}
func (*scheme) UnmarshalBinaryPrivateKey(buf []byte) (kem.PrivateKey, error) {
if len(buf) != PrivateKeySize {
return nil, kem.ErrPrivKeySize
}
var ret PrivateKey
{{ if .NIST -}}
if err := ret.Unpack(buf); err != nil {
return nil, err
}
{{- else -}}
ret.Unpack(buf)
{{- end }}
return &ret, nil
}