github.com/cloudflare/circl@v1.5.0/dh/curve4q/curve4Q_test.go (about)

     1  package curve4q
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"fmt"
     7  	"io"
     8  	"testing"
     9  
    10  	"github.com/cloudflare/circl/internal/test"
    11  )
    12  
    13  func TestDH(t *testing.T) {
    14  	var secretAlice, publicAlice, sharedAlice Key
    15  	var secretBob, publicBob, sharedBob Key
    16  	testTimes := 1 << 10
    17  
    18  	for i := 0; i < testTimes; i++ {
    19  		_, _ = rand.Read(secretAlice[:])
    20  		_, _ = rand.Read(secretBob[:])
    21  
    22  		KeyGen(&publicAlice, &secretAlice)
    23  		KeyGen(&publicBob, &secretBob)
    24  
    25  		if ok := Shared(&sharedAlice, &secretAlice, &publicBob); !ok {
    26  			test.ReportError(t, ok, true, secretAlice, publicBob)
    27  		}
    28  		if ok := Shared(&sharedBob, &secretBob, &publicAlice); !ok {
    29  			test.ReportError(t, ok, true, secretBob, publicAlice)
    30  		}
    31  
    32  		got := sharedAlice
    33  		want := sharedBob
    34  		if !bytes.Equal(got[:], want[:]) {
    35  			test.ReportError(t, got, want, secretAlice, secretBob)
    36  		}
    37  	}
    38  }
    39  
    40  func BenchmarkDH(b *testing.B) {
    41  	var secret, public, shared Key
    42  	_, _ = rand.Read(secret[:])
    43  	_, _ = rand.Read(public[:])
    44  
    45  	b.Run("keygen", func(b *testing.B) {
    46  		for i := 0; i < b.N; i++ {
    47  			KeyGen(&public, &secret)
    48  		}
    49  	})
    50  	b.Run("shared", func(b *testing.B) {
    51  		for i := 0; i < b.N; i++ {
    52  			Shared(&shared, &secret, &public)
    53  		}
    54  	})
    55  }
    56  
    57  func ExampleKey() {
    58  	var AliceSecret, BobSecret,
    59  		AlicePublic, BobPublic,
    60  		AliceShared, BobShared Key
    61  
    62  	// Generating Alice's secret and public keys
    63  	_, _ = io.ReadFull(rand.Reader, AliceSecret[:])
    64  	KeyGen(&AlicePublic, &AliceSecret)
    65  
    66  	// Generating Bob's secret and public keys
    67  	_, _ = io.ReadFull(rand.Reader, BobSecret[:])
    68  	KeyGen(&BobPublic, &BobSecret)
    69  
    70  	// Deriving Alice's shared key
    71  	Shared(&AliceShared, &AliceSecret, &BobPublic)
    72  
    73  	// Deriving Bob's shared key
    74  	Shared(&BobShared, &BobSecret, &AlicePublic)
    75  
    76  	fmt.Println(AliceShared == BobShared)
    77  	// Output: true
    78  }