Debian Codegraph @

src/crypto/mlkem/mlkemtest/mlkemtest.go

raw
1 // Copyright 2025 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 mlkemtest provides testing functions for the ML-KEM algorithm.
6 package mlkemtest
7
8 import (
9 fips140mlkem "crypto/internal/fips140/mlkem"
10 "crypto/internal/fips140only"
11 "crypto/mlkem"
12 "errors"
13 )
14
15 // Encapsulate768 implements derandomized ML-KEM-768 encapsulation
16 // (ML-KEM.Encaps_internal from FIPS 203) using the provided encapsulation key
17 // ek and 32 bytes of randomness.
18 //
19 // It must only be used for known-answer tests.
20 func Encapsulate768(ek *mlkem.EncapsulationKey768, random []byte) (sharedKey, ciphertext []byte, err error) {
21 if len(random) != 32 {
22 return nil, nil, errors.New("mlkemtest: Encapsulate768: random must be 32 bytes")
23 }
24 if fips140only.Enforced() {
25 return nil, nil, errors.New("crypto/mlkem/mlkemtest: use of derandomized encapsulation is not allowed in FIPS 140-only mode")
26 }
27 k, err := fips140mlkem.NewEncapsulationKey768(ek.Bytes())
28 if err != nil {
29 return nil, nil, errors.New("mlkemtest: Encapsulate768: failed to reconstruct key: " + err.Error())
30 }
31 sharedKey, ciphertext = k.EncapsulateInternal((*[32]byte)(random))
32 return sharedKey, ciphertext, nil
33 }
34
35 // Encapsulate1024 implements derandomized ML-KEM-1024 encapsulation
36 // (ML-KEM.Encaps_internal from FIPS 203) using the provided encapsulation key
37 // ek and 32 bytes of randomness.
38 //
39 // It must only be used for known-answer tests.
40 func Encapsulate1024(ek *mlkem.EncapsulationKey1024, random []byte) (sharedKey, ciphertext []byte, err error) {
41 if len(random) != 32 {
42 return nil, nil, errors.New("mlkemtest: Encapsulate1024: random must be 32 bytes")
43 }
44 if fips140only.Enforced() {
45 return nil, nil, errors.New("crypto/mlkem/mlkemtest: use of derandomized encapsulation is not allowed in FIPS 140-only mode")
46 }
47 k, err := fips140mlkem.NewEncapsulationKey1024(ek.Bytes())
48 if err != nil {
49 return nil, nil, errors.New("mlkemtest: Encapsulate1024: failed to reconstruct key: " + err.Error())
50 }
51 sharedKey, ciphertext = k.EncapsulateInternal((*[32]byte)(random))
52 return sharedKey, ciphertext, nil
53 }