Source file src/crypto/mldsa/example_test.go

     1  // Copyright 2026 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  //go:build !fips140v1.0
     6  
     7  package mldsa_test
     8  
     9  import (
    10  	"crypto/mldsa"
    11  	"fmt"
    12  	"log"
    13  )
    14  
    15  func Example() {
    16  	// The signer generates a new ML-DSA-44 key pair.
    17  	sk, err := mldsa.GenerateKey(mldsa.MLDSA44())
    18  	if err != nil {
    19  		log.Fatal(err)
    20  	}
    21  
    22  	// The signer publishes the public key encoding.
    23  	publicKey := sk.PublicKey().Bytes()
    24  	fmt.Printf("public key: %d bytes\n", len(publicKey))
    25  
    26  	// The signer signs a message and publishes the signature.
    27  	msg := []byte("hello, world")
    28  	sig, err := sk.Sign(nil, msg, &mldsa.Options{Context: "example"})
    29  	if err != nil {
    30  		log.Fatal(err)
    31  	}
    32  	fmt.Printf("signature: %d bytes\n", len(sig))
    33  
    34  	// The verifier reconstructs the public key and checks the signature.
    35  	// The context string must match the one used by the signer.
    36  	pk, err := mldsa.NewPublicKey(mldsa.MLDSA44(), publicKey)
    37  	if err != nil {
    38  		log.Fatal(err)
    39  	}
    40  	if err := mldsa.Verify(pk, msg, sig, &mldsa.Options{Context: "example"}); err != nil {
    41  		log.Fatal("invalid signature: ", err)
    42  	}
    43  
    44  	// Output:
    45  	// public key: 1312 bytes
    46  	// signature: 2420 bytes
    47  }
    48  

View as plain text