github.com/cloudflare/circl@v1.5.0/ecc/fourq/curve_test.go (about)

     1  package fourq
     2  
     3  import (
     4  	"crypto/rand"
     5  	"testing"
     6  
     7  	"github.com/cloudflare/circl/internal/conv"
     8  	"github.com/cloudflare/circl/internal/test"
     9  )
    10  
    11  func (P *Point) random() {
    12  	var _P pointR1
    13  	_P.random()
    14  	P.fromR1(&_P)
    15  }
    16  
    17  func TestMarshal(t *testing.T) {
    18  	testTimes := 1 << 10
    19  	var buf, k [Size]byte
    20  	var P, Q, R Point
    21  	t.Run("k*um(P)=kP", func(t *testing.T) {
    22  		for i := 0; i < testTimes; i++ {
    23  			P.random()
    24  			_, _ = rand.Read(k[:])
    25  
    26  			P.Marshal(&buf)
    27  			if ok := Q.Unmarshal(&buf); !ok {
    28  				test.ReportError(t, ok, true)
    29  			}
    30  			Q.ScalarMult(&k, &Q)
    31  			R.ScalarMult(&k, &P)
    32  
    33  			got := Q.X
    34  			want := R.X
    35  			if got != want {
    36  				test.ReportError(t, got, want, P, k)
    37  			}
    38  			got = Q.Y
    39  			want = R.Y
    40  			if got != want {
    41  				test.ReportError(t, got, want, P, k)
    42  			}
    43  		}
    44  	})
    45  	t.Run("m(kP)~=m(-kP)", func(t *testing.T) {
    46  		c := Params()
    47  		var minusK, encQ, encR [Size]byte
    48  		for i := 0; i < testTimes; i++ {
    49  			P.random()
    50  			bigK, _ := rand.Int(rand.Reader, c.N)
    51  			conv.BigInt2BytesLe(k[:], bigK)
    52  			bigK.Neg(bigK).Mod(bigK, c.N)
    53  			conv.BigInt2BytesLe(minusK[:], bigK)
    54  			Q.ScalarMult(&k, &P)
    55  			R.ScalarMult(&minusK, &P)
    56  			Q.Marshal(&encQ)
    57  			R.Marshal(&encR)
    58  
    59  			got := encQ[31] >> 7
    60  			want := 1 - (encR[31] >> 7)
    61  			encQ[31] &= 0x7F
    62  			encR[31] &= 0x7F
    63  
    64  			if encQ != encR {
    65  				test.ReportError(t, encQ, encR, P, k)
    66  			}
    67  			if got != want {
    68  				test.ReportError(t, got, want, P, k)
    69  			}
    70  		}
    71  	})
    72  }
    73  
    74  func BenchmarkCurve(b *testing.B) {
    75  	var P, Q, R Point
    76  	var k [32]byte
    77  
    78  	_, _ = rand.Read(k[:])
    79  	P.ScalarBaseMult(&k)
    80  	_, _ = rand.Read(k[:])
    81  	Q.ScalarBaseMult(&k)
    82  	_, _ = rand.Read(k[:])
    83  	R.ScalarBaseMult(&k)
    84  
    85  	b.Run("Add", func(b *testing.B) {
    86  		for i := 0; i < b.N; i++ {
    87  			P.Add(&Q, &R)
    88  		}
    89  	})
    90  
    91  	b.Run("Double", func(b *testing.B) {
    92  		for i := 0; i < b.N; i++ {
    93  			P.Add(&Q, &Q)
    94  		}
    95  	})
    96  
    97  	b.Run("ScalarBaseMult", func(b *testing.B) {
    98  		for i := 0; i < b.N; i++ {
    99  			P.ScalarBaseMult(&k)
   100  		}
   101  	})
   102  
   103  	b.Run("ScalarMult", func(b *testing.B) {
   104  		for i := 0; i < b.N; i++ {
   105  			P.ScalarMult(&k, &Q)
   106  		}
   107  	})
   108  }