Source file src/crypto/mlkem/example_test.go

     1  // Copyright 2024 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_test
     6  
     7  import (
     8  	"crypto/mlkem"
     9  	"log"
    10  )
    11  
    12  func Example() {
    13  	// Alice generates a new key pair and sends the encapsulation key to Bob.
    14  	dk, err := mlkem.GenerateKey768()
    15  	if err != nil {
    16  		log.Fatal(err)
    17  	}
    18  	encapsulationKey := dk.EncapsulationKey().Bytes()
    19  
    20  	// Bob uses the encapsulation key to encapsulate a shared secret, and sends
    21  	// back the ciphertext to Alice.
    22  	ciphertext := Bob(encapsulationKey)
    23  
    24  	// Alice decapsulates the shared secret from the ciphertext.
    25  	sharedSecret, err := dk.Decapsulate(ciphertext)
    26  	if err != nil {
    27  		log.Fatal(err)
    28  	}
    29  
    30  	// Alice and Bob now share a secret.
    31  	_ = sharedSecret
    32  }
    33  
    34  func Bob(encapsulationKey []byte) (ciphertext []byte) {
    35  	// Bob encapsulates a shared secret using the encapsulation key.
    36  	ek, err := mlkem.NewEncapsulationKey768(encapsulationKey)
    37  	if err != nil {
    38  		log.Fatal(err)
    39  	}
    40  	sharedSecret, ciphertext := ek.Encapsulate()
    41  
    42  	// Alice and Bob now share a secret.
    43  	_ = sharedSecret
    44  
    45  	// Bob sends the ciphertext to Alice.
    46  	return ciphertext
    47  }
    48  

View as plain text