Debian Codegraph @

src/crypto/internal/fips140/mlkem/mlkem768.go

raw
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package mlkem implements the quantum-resistant key encapsulation method
6 // ML-KEM (formerly known as Kyber), as specified in [NIST FIPS 203].
7 //
8 // [NIST FIPS 203]: https://doi.org/10.6028/NIST.FIPS.203
9 package mlkem
10
11 // This package targets security, correctness, simplicity, readability, and
12 // reviewability as its primary goals. All critical operations are performed in
13 // constant time.
14 //
15 // Variable and function names, as well as code layout, are selected to
16 // facilitate reviewing the implementation against the NIST FIPS 203 document.
17 //
18 // Reviewers unfamiliar with polynomials or linear algebra might find the
19 // background at https://words.filippo.io/kyber-math/ useful.
20 //
21 // This file implements the recommended parameter set ML-KEM-768. The ML-KEM-1024
22 // parameter set implementation is auto-generated from this file.
23 //
24 //go:generate go run generate1024.go -input mlkem768.go -output mlkem1024.go
25
26 import (
27 "bytes"
28 "crypto/internal/fips140"
29 "crypto/internal/fips140/drbg"
30 "crypto/internal/fips140/sha3"
31 "crypto/internal/fips140/subtle"
32 "errors"
33 )
34
35 const (
36 // ML-KEM global constants.
37 n = 256
38 q = 3329
39
40 // encodingSizeX is the byte size of a ringElement or nttElement encoded
41 // by ByteEncode_X (FIPS 203, Algorithm 5).
42 encodingSize12 = n * 12 / 8
43 encodingSize11 = n * 11 / 8
44 encodingSize10 = n * 10 / 8
45 encodingSize5 = n * 5 / 8
46 encodingSize4 = n * 4 / 8
47 encodingSize1 = n * 1 / 8
48
49 messageSize = encodingSize1
50
51 SharedKeySize = 32
52 SeedSize = 32 + 32
53 )
54
55 // ML-KEM-768 parameters.
56 const (
57 k = 3
58
59 CiphertextSize768 = k*encodingSize10 + encodingSize4
60 EncapsulationKeySize768 = k*encodingSize12 + 32
61 decapsulationKeySize768 = k*encodingSize12 + EncapsulationKeySize768 + 32 + 32
62 )
63
64 // ML-KEM-1024 parameters.
65 const (
66 k1024 = 4
67
68 CiphertextSize1024 = k1024*encodingSize11 + encodingSize5
69 EncapsulationKeySize1024 = k1024*encodingSize12 + 32
70 decapsulationKeySize1024 = k1024*encodingSize12 + EncapsulationKeySize1024 + 32 + 32
71 )
72
73 // A DecapsulationKey768 is the secret key used to decapsulate a shared key from a
74 // ciphertext. It includes various precomputed values.
75 type DecapsulationKey768 struct {
76 d [32]byte // decapsulation key seed
77 z [32]byte // implicit rejection sampling seed
78
79 ρ [32]byte // sampleNTT seed for A, stored for the encapsulation key
80 h [32]byte // H(ek), stored for ML-KEM.Decaps_internal
81
82 encryptionKey
83 decryptionKey
84 }
85
86 // Bytes returns the decapsulation key as a 64-byte seed in the "d || z" form.
87 //
88 // The decapsulation key must be kept secret.
89 func (dk *DecapsulationKey768) Bytes() []byte {
90 var b [SeedSize]byte
91 copy(b[:], dk.d[:])
92 copy(b[32:], dk.z[:])
93 return b[:]
94 }
95
96 // TestingOnlyExpandedBytes768 returns the decapsulation key as a byte slice
97 // using the full expanded NIST encoding.
98 //
99 // This should only be used for ACVP testing. For all other purposes prefer
100 // the Bytes method that returns the (much smaller) seed.
101 func TestingOnlyExpandedBytes768(dk *DecapsulationKey768) []byte {
102 b := make([]byte, 0, decapsulationKeySize768)
103
104 // ByteEncode₁₂(s)
105 for i := range dk.s {
106 b = polyByteEncode(b, dk.s[i])
107 }
108
109 // ByteEncode₁₂(t) || ρ
110 for i := range dk.t {
111 b = polyByteEncode(b, dk.t[i])
112 }
113 b = append(b, dk.ρ[:]...)
114
115 // H(ek) || z
116 b = append(b, dk.h[:]...)
117 b = append(b, dk.z[:]...)
118
119 return b
120 }
121
122 // EncapsulationKey returns the public encapsulation key necessary to produce
123 // ciphertexts.
124 func (dk *DecapsulationKey768) EncapsulationKey() *EncapsulationKey768 {
125 return &EncapsulationKey768{
126 ρ: dk.ρ,
127 h: dk.h,
128 encryptionKey: dk.encryptionKey,
129 }
130 }
131
132 // An EncapsulationKey768 is the public key used to produce ciphertexts to be
133 // decapsulated by the corresponding [DecapsulationKey768].
134 type EncapsulationKey768 struct {
135 ρ [32]byte // sampleNTT seed for A
136 h [32]byte // H(ek)
137 encryptionKey
138 }
139
140 // Bytes returns the encapsulation key as a byte slice.
141 func (ek *EncapsulationKey768) Bytes() []byte {
142 // The actual logic is in a separate function to outline this allocation.
143 b := make([]byte, 0, EncapsulationKeySize768)
144 return ek.bytes(b)
145 }
146
147 func (ek *EncapsulationKey768) bytes(b []byte) []byte {
148 for i := range ek.t {
149 b = polyByteEncode(b, ek.t[i])
150 }
151 b = append(b, ek.ρ[:]...)
152 return b
153 }
154
155 // encryptionKey is the parsed and expanded form of a PKE encryption key.
156 type encryptionKey struct {
157 t [k]nttElement // ByteDecode₁₂(ek[:384k])
158 a [k * k]nttElement // A[i*k+j] = sampleNTT(ρ, j, i)
159 }
160
161 // decryptionKey is the parsed and expanded form of a PKE decryption key.
162 type decryptionKey struct {
163 s [k]nttElement // ByteDecode₁₂(dk[:decryptionKeySize])
164 }
165
166 // GenerateKey768 generates a new decapsulation key, drawing random bytes from
167 // a DRBG. The decapsulation key must be kept secret.
168 func GenerateKey768() (*DecapsulationKey768, error) {
169 // The actual logic is in a separate function to outline this allocation.
170 dk := &DecapsulationKey768{}
171 return generateKey(dk)
172 }
173
174 func generateKey(dk *DecapsulationKey768) (*DecapsulationKey768, error) {
175 fipsSelfTest()
176 var d [32]byte
177 drbg.Read(d[:])
178 var z [32]byte
179 drbg.Read(z[:])
180 kemKeyGen(dk, &d, &z)
181 fips140.PCT("ML-KEM PCT", func() error { return kemPCT(dk) })
182 fips140.RecordApproved()
183 return dk, nil
184 }
185
186 // GenerateKeyInternal768 is a derandomized version of GenerateKey768,
187 // exclusively for use in tests.
188 func GenerateKeyInternal768(d, z *[32]byte) *DecapsulationKey768 {
189 fipsSelfTest()
190 dk := &DecapsulationKey768{}
191 kemKeyGen(dk, d, z)
192 return dk
193 }
194
195 // NewDecapsulationKey768 parses a decapsulation key from a 64-byte
196 // seed in the "d || z" form. The seed must be uniformly random.
197 func NewDecapsulationKey768(seed []byte) (*DecapsulationKey768, error) {
198 // The actual logic is in a separate function to outline this allocation.
199 dk := &DecapsulationKey768{}
200 return newKeyFromSeed(dk, seed)
201 }
202
203 func newKeyFromSeed(dk *DecapsulationKey768, seed []byte) (*DecapsulationKey768, error) {
204 if len(seed) != SeedSize {
205 return nil, errors.New("mlkem: invalid seed length")
206 }
207 d := (*[32]byte)(seed[:32])
208 z := (*[32]byte)(seed[32:])
209 kemKeyGen(dk, d, z)
210 fips140.RecordApproved()
211 return dk, nil
212 }
213
214 // TestingOnlyNewDecapsulationKey768 parses a decapsulation key from its expanded NIST format.
215 //
216 // Bytes() must not be called on the returned key, as it will not produce the
217 // original seed.
218 //
219 // This function should only be used for ACVP testing. Prefer NewDecapsulationKey768 for all
220 // other purposes.
221 func TestingOnlyNewDecapsulationKey768(b []byte) (*DecapsulationKey768, error) {
222 if len(b) != decapsulationKeySize768 {
223 return nil, errors.New("mlkem: invalid NIST decapsulation key length")
224 }
225
226 dk := &DecapsulationKey768{}
227 for i := range dk.s {
228 var err error
229 dk.s[i], err = polyByteDecode[nttElement](b[:encodingSize12])
230 if err != nil {
231 return nil, errors.New("mlkem: invalid secret key encoding")
232 }
233 b = b[encodingSize12:]
234 }
235
236 ek, err := NewEncapsulationKey768(b[:EncapsulationKeySize768])
237 if err != nil {
238 return nil, err
239 }
240 dk.ρ = ek.ρ
241 dk.h = ek.h
242 dk.encryptionKey = ek.encryptionKey
243 b = b[EncapsulationKeySize768:]
244
245 if !bytes.Equal(dk.h[:], b[:32]) {
246 return nil, errors.New("mlkem: inconsistent H(ek) in encoded bytes")
247 }
248 b = b[32:]
249
250 copy(dk.z[:], b)
251
252 // Generate a random d value for use in Bytes(). This is a safety mechanism
253 // that avoids returning a broken key vs a random key if this function is
254 // called in contravention of the TestingOnlyNewDecapsulationKey768 function
255 // comment advising against it.
256 drbg.Read(dk.d[:])
257
258 return dk, nil
259 }
260
261 // kemKeyGen generates a decapsulation key.
262 //
263 // It implements ML-KEM.KeyGen_internal according to FIPS 203, Algorithm 16, and
264 // K-PKE.KeyGen according to FIPS 203, Algorithm 13. The two are merged to save
265 // copies and allocations.
266 func kemKeyGen(dk *DecapsulationKey768, d, z *[32]byte) {
267 dk.d = *d
268 dk.z = *z
269
270 g := sha3.New512()
271 g.Write(d[:])
272 g.Write([]byte{k}) // Module dimension as a domain separator.
273 G := g.Sum(make([]byte, 0, 64))
274 ρ, σ := G[:32], G[32:]
275 dk.ρ = [32]byte(ρ)
276
277 A := &dk.a
278 for i := byte(0); i < k; i++ {
279 for j := byte(0); j < k; j++ {
280 A[i*k+j] = sampleNTT(ρ, j, i)
281 }
282 }
283
284 var N byte
285 s := &dk.s
286 for i := range s {
287 s[i] = ntt(samplePolyCBD(σ, N))
288 N++
289 }
290 e := make([]nttElement, k)
291 for i := range e {
292 e[i] = ntt(samplePolyCBD(σ, N))
293 N++
294 }
295
296 t := &dk.t
297 for i := range t { // t = A ◦ s + e
298 t[i] = e[i]
299 for j := range s {
300 t[i] = polyAdd(t[i], nttMul(A[i*k+j], s[j]))
301 }
302 }
303
304 H := sha3.New256()
305 ek := dk.EncapsulationKey().Bytes()
306 H.Write(ek)
307 H.Sum(dk.h[:0])
308 }
309
310 // kemPCT performs a Pairwise Consistency Test per FIPS 140-3 IG 10.3.A
311 // Additional Comment 1: "For key pairs generated for use with approved KEMs in
312 // FIPS 203, the PCT shall consist of applying the encapsulation key ek to
313 // encapsulate a shared secret K leading to ciphertext c, and then applying
314 // decapsulation key dk to retrieve the same shared secret K. The PCT passes if
315 // the two shared secret K values are equal. The PCT shall be performed either
316 // when keys are generated/imported, prior to the first exportation, or prior to
317 // the first operational use (if not exported before the first use)."
318 func kemPCT(dk *DecapsulationKey768) error {
319 ek := dk.EncapsulationKey()
320 K, c := ek.Encapsulate()
321 K1, err := dk.Decapsulate(c)
322 if err != nil {
323 return err
324 }
325 if subtle.ConstantTimeCompare(K, K1) != 1 {
326 return errors.New("mlkem: PCT failed")
327 }
328 return nil
329 }
330
331 // Encapsulate generates a shared key and an associated ciphertext from an
332 // encapsulation key, drawing random bytes from a DRBG.
333 //
334 // The shared key must be kept secret.
335 func (ek *EncapsulationKey768) Encapsulate() (sharedKey, ciphertext []byte) {
336 // The actual logic is in a separate function to outline this allocation.
337 var cc [CiphertextSize768]byte
338 return ek.encapsulate(&cc)
339 }
340
341 func (ek *EncapsulationKey768) encapsulate(cc *[CiphertextSize768]byte) (sharedKey, ciphertext []byte) {
342 fipsSelfTest()
343 var m [messageSize]byte
344 drbg.Read(m[:])
345 // Note that the modulus check (step 2 of the encapsulation key check from
346 // FIPS 203, Section 7.2) is performed by polyByteDecode in parseEK.
347 fips140.RecordApproved()
348 return kemEncaps(cc, ek, &m)
349 }
350
351 // EncapsulateInternal is a derandomized version of Encapsulate, exclusively for
352 // use in tests.
353 func (ek *EncapsulationKey768) EncapsulateInternal(m *[32]byte) (sharedKey, ciphertext []byte) {
354 fipsSelfTest()
355 cc := &[CiphertextSize768]byte{}
356 return kemEncaps(cc, ek, m)
357 }
358
359 // kemEncaps generates a shared key and an associated ciphertext.
360 //
361 // It implements ML-KEM.Encaps_internal according to FIPS 203, Algorithm 17.
362 func kemEncaps(cc *[CiphertextSize768]byte, ek *EncapsulationKey768, m *[messageSize]byte) (K, c []byte) {
363 g := sha3.New512()
364 g.Write(m[:])
365 g.Write(ek.h[:])
366 G := g.Sum(nil)
367 K, r := G[:SharedKeySize], G[SharedKeySize:]
368 c = pkeEncrypt(cc, &ek.encryptionKey, m, r)
369 return K, c
370 }
371
372 // NewEncapsulationKey768 parses an encapsulation key from its encoded form.
373 // If the encapsulation key is not valid, NewEncapsulationKey768 returns an error.
374 func NewEncapsulationKey768(encapsulationKey []byte) (*EncapsulationKey768, error) {
375 // The actual logic is in a separate function to outline this allocation.
376 ek := &EncapsulationKey768{}
377 return parseEK(ek, encapsulationKey)
378 }
379
380 // parseEK parses an encryption key from its encoded form.
381 //
382 // It implements the initial stages of K-PKE.Encrypt according to FIPS 203,
383 // Algorithm 14.
384 func parseEK(ek *EncapsulationKey768, ekPKE []byte) (*EncapsulationKey768, error) {
385 if len(ekPKE) != EncapsulationKeySize768 {
386 return nil, errors.New("mlkem: invalid encapsulation key length")
387 }
388
389 h := sha3.New256()
390 h.Write(ekPKE)
391 h.Sum(ek.h[:0])
392
393 for i := range ek.t {
394 var err error
395 ek.t[i], err = polyByteDecode[nttElement](ekPKE[:encodingSize12])
396 if err != nil {
397 return nil, err
398 }
399 ekPKE = ekPKE[encodingSize12:]
400 }
401 copy(ek.ρ[:], ekPKE)
402
403 for i := byte(0); i < k; i++ {
404 for j := byte(0); j < k; j++ {
405 ek.a[i*k+j] = sampleNTT(ek.ρ[:], j, i)
406 }
407 }
408
409 return ek, nil
410 }
411
412 // pkeEncrypt encrypt a plaintext message.
413 //
414 // It implements K-PKE.Encrypt according to FIPS 203, Algorithm 14, although the
415 // computation of t and AT is done in parseEK.
416 func pkeEncrypt(cc *[CiphertextSize768]byte, ex *encryptionKey, m *[messageSize]byte, rnd []byte) []byte {
417 var N byte
418 r, e1 := make([]nttElement, k), make([]ringElement, k)
419 for i := range r {
420 r[i] = ntt(samplePolyCBD(rnd, N))
421 N++
422 }
423 for i := range e1 {
424 e1[i] = samplePolyCBD(rnd, N)
425 N++
426 }
427 e2 := samplePolyCBD(rnd, N)
428
429 u := make([]ringElement, k) // NTT⁻¹(AT ◦ r) + e1
430 for i := range u {
431 var uHat nttElement
432 for j := range r {
433 // Note that i and j are inverted, as we need the transposed of A.
434 uHat = polyAdd(uHat, nttMul(ex.a[j*k+i], r[j]))
435 }
436 u[i] = polyAdd(e1[i], inverseNTT(uHat))
437 }
438
439 μ := ringDecodeAndDecompress1(m)
440
441 var vNTT nttElement // t⊺ ◦ r
442 for i := range ex.t {
443 vNTT = polyAdd(vNTT, nttMul(ex.t[i], r[i]))
444 }
445 v := polyAdd(polyAdd(inverseNTT(vNTT), e2), μ)
446
447 c := cc[:0]
448 for _, f := range u {
449 c = ringCompressAndEncode10(c, f)
450 }
451 c = ringCompressAndEncode4(c, v)
452
453 return c
454 }
455
456 // Decapsulate generates a shared key from a ciphertext and a decapsulation key.
457 // If the ciphertext is not valid, Decapsulate returns an error.
458 //
459 // The shared key must be kept secret.
460 func (dk *DecapsulationKey768) Decapsulate(ciphertext []byte) (sharedKey []byte, err error) {
461 fipsSelfTest()
462 if len(ciphertext) != CiphertextSize768 {
463 return nil, errors.New("mlkem: invalid ciphertext length")
464 }
465 c := (*[CiphertextSize768]byte)(ciphertext)
466 // Note that the hash check (step 3 of the decapsulation input check from
467 // FIPS 203, Section 7.3) is foregone as a DecapsulationKey is always
468 // validly generated by ML-KEM.KeyGen_internal.
469 return kemDecaps(dk, c), nil
470 }
471
472 // kemDecaps produces a shared key from a ciphertext.
473 //
474 // It implements ML-KEM.Decaps_internal according to FIPS 203, Algorithm 18.
475 func kemDecaps(dk *DecapsulationKey768, c *[CiphertextSize768]byte) (K []byte) {
476 fips140.RecordApproved()
477 m := pkeDecrypt(&dk.decryptionKey, c)
478 g := sha3.New512()
479 g.Write(m[:])
480 g.Write(dk.h[:])
481 G := g.Sum(make([]byte, 0, 64))
482 Kprime, r := G[:SharedKeySize], G[SharedKeySize:]
483 J := sha3.NewShake256()
484 J.Write(dk.z[:])
485 J.Write(c[:])
486 Kout := make([]byte, SharedKeySize)
487 J.Read(Kout)
488 var cc [CiphertextSize768]byte
489 c1 := pkeEncrypt(&cc, &dk.encryptionKey, (*[32]byte)(m), r)
490
491 subtle.ConstantTimeCopy(subtle.ConstantTimeCompare(c[:], c1), Kout, Kprime)
492 return Kout
493 }
494
495 // pkeDecrypt decrypts a ciphertext.
496 //
497 // It implements K-PKE.Decrypt according to FIPS 203, Algorithm 15,
498 // although s is retained from kemKeyGen.
499 func pkeDecrypt(dx *decryptionKey, c *[CiphertextSize768]byte) []byte {
500 u := make([]ringElement, k)
501 for i := range u {
502 b := (*[encodingSize10]byte)(c[encodingSize10*i : encodingSize10*(i+1)])
503 u[i] = ringDecodeAndDecompress10(b)
504 }
505
506 b := (*[encodingSize4]byte)(c[encodingSize10*k:])
507 v := ringDecodeAndDecompress4(b)
508
509 var mask nttElement // s⊺ ◦ NTT(u)
510 for i := range dx.s {
511 mask = polyAdd(mask, nttMul(dx.s[i], ntt(u[i])))
512 }
513 w := polySub(v, inverseNTT(mask))
514
515 return ringCompressAndEncode1(nil, w)
516 }