Source file src/crypto/mlkem/mlkemtest/mlkemtest.go

     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/mlkem"
    11  	"errors"
    12  )
    13  
    14  // Encapsulate768 implements derandomized ML-KEM-768 encapsulation
    15  // (ML-KEM.Encaps_internal from FIPS 203) using the provided encapsulation key
    16  // ek and 32 bytes of randomness.
    17  //
    18  // It must only be used for known-answer tests.
    19  func Encapsulate768(ek *mlkem.EncapsulationKey768, random []byte) (sharedKey, ciphertext []byte, err error) {
    20  	if len(random) != 32 {
    21  		return nil, nil, errors.New("mlkemtest: Encapsulate768: random must be 32 bytes")
    22  	}
    23  	k, err := fips140mlkem.NewEncapsulationKey768(ek.Bytes())
    24  	if err != nil {
    25  		return nil, nil, errors.New("mlkemtest: Encapsulate768: failed to reconstruct key: " + err.Error())
    26  	}
    27  	sharedKey, ciphertext = k.EncapsulateInternal((*[32]byte)(random))
    28  	return sharedKey, ciphertext, nil
    29  }
    30  
    31  // Encapsulate1024 implements derandomized ML-KEM-1024 encapsulation
    32  // (ML-KEM.Encaps_internal from FIPS 203) using the provided encapsulation key
    33  // ek and 32 bytes of randomness.
    34  //
    35  // It must only be used for known-answer tests.
    36  func Encapsulate1024(ek *mlkem.EncapsulationKey1024, random []byte) (sharedKey, ciphertext []byte, err error) {
    37  	if len(random) != 32 {
    38  		return nil, nil, errors.New("mlkemtest: Encapsulate1024: random must be 32 bytes")
    39  	}
    40  	k, err := fips140mlkem.NewEncapsulationKey1024(ek.Bytes())
    41  	if err != nil {
    42  		return nil, nil, errors.New("mlkemtest: Encapsulate1024: failed to reconstruct key: " + err.Error())
    43  	}
    44  	sharedKey, ciphertext = k.EncapsulateInternal((*[32]byte)(random))
    45  	return sharedKey, ciphertext, nil
    46  }
    47  

View as plain text