cast.mx raw

   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 ed25519
   6  
   7  import (
   8  	"bytes"
   9  	"crypto/internal/fips140"
  10  	_ "crypto/internal/fips140/check"
  11  	"errors"
  12  	"sync"
  13  )
  14  
  15  func fipsPCT(k *PrivateKey) {
  16  	fips140.PCT("Ed25519 sign and verify PCT", func() error {
  17  		return pairwiseTest(k)
  18  	})
  19  }
  20  
  21  // pairwiseTest needs to be a top-level function declaration to let the calls
  22  // inline and their allocations not escape.
  23  func pairwiseTest(k *PrivateKey) error {
  24  	msg := []byte("PCT")
  25  	sig := Sign(k, msg)
  26  	// Note that this runs pub.a.SetBytes. If we wanted to make key generation
  27  	// in FIPS mode faster, we could reuse A from GenerateKey. But another thing
  28  	// that could make it faster is just _not doing a useless self-test_.
  29  	pub, err := NewPublicKey(k.PublicKey())
  30  	if err != nil {
  31  		return err
  32  	}
  33  	return Verify(pub, msg, sig)
  34  }
  35  
  36  func signWithoutSelfTest(priv *PrivateKey, message []byte) []byte {
  37  	signature := []byte{:signatureSize}
  38  	return signWithDom(signature, priv, message, domPrefixPure, "")
  39  }
  40  
  41  func verifyWithoutSelfTest(pub *PublicKey, message, sig []byte) error {
  42  	return verifyWithDom(pub, message, sig, domPrefixPure, "")
  43  }
  44  
  45  var fipsSelfTest = sync.OnceFunc(func() {
  46  	fips140.CAST("Ed25519 sign and verify", func() error {
  47  		seed := [32]byte{
  48  			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
  49  			0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
  50  			0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
  51  			0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
  52  		}
  53  		msg := []byte("CAST")
  54  		want := []byte{
  55  			0xbd, 0xe7, 0xa5, 0xf3, 0x40, 0x73, 0xb9, 0x5a,
  56  			0x2e, 0x6d, 0x63, 0x20, 0x0a, 0xd5, 0x92, 0x9b,
  57  			0xa2, 0x3d, 0x00, 0x44, 0xb4, 0xc5, 0xfd, 0x62,
  58  			0x1d, 0x5e, 0x33, 0x2f, 0xe4, 0x61, 0x42, 0x31,
  59  			0x5b, 0x10, 0x53, 0x13, 0x4d, 0xcb, 0xd1, 0x1b,
  60  			0x2a, 0xf6, 0xcd, 0x0e, 0xdb, 0x9a, 0xd3, 0x1e,
  61  			0x35, 0xdb, 0x0b, 0xcf, 0x58, 0x90, 0x4f, 0xd7,
  62  			0x69, 0x38, 0xed, 0x30, 0x51, 0x0f, 0xaa, 0x03,
  63  		}
  64  		k := &PrivateKey{seed: seed}
  65  		precomputePrivateKey(k)
  66  		pub, err := NewPublicKey(k.PublicKey())
  67  		if err != nil {
  68  			return err
  69  		}
  70  		sig := signWithoutSelfTest(k, msg)
  71  		if !bytes.Equal(sig, want) {
  72  			return errors.New("unexpected result")
  73  		}
  74  		return verifyWithoutSelfTest(pub, msg, sig)
  75  	})
  76  })
  77