From ebb124e8120c01de9fc4b5b74b49507d7f1d035e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 29 Jan 2019 14:25:17 +0300 Subject: [PATCH] add random GF(2^127)-element generator --- gf127/gf127.go | 7 +++++++ gf127/gf127_test.go | 25 +++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/gf127/gf127.go b/gf127/gf127.go index 1dadb3b..f923cf9 100644 --- a/gf127/gf127.go +++ b/gf127/gf127.go @@ -12,6 +12,7 @@ import ( "encoding/hex" "errors" "math/bits" + "math/rand" ) // GF127 represents element of GF(2^127) @@ -36,6 +37,12 @@ func New(lo, hi uint64) *GF127 { return &GF127{lo, hi} } +// Random returns random element from GF(2^127). +// Is used mostly for testing. +func Random() *GF127 { + return &GF127{rand.Uint64(), rand.Uint64() >> 1} +} + // String returns hex-encoded representation, starting with MSB. func (c *GF127) String() string { return hex.EncodeToString(c.ByteArray()) diff --git a/gf127/gf127_test.go b/gf127/gf127_test.go index 6d0c7ae..eca46ad 100644 --- a/gf127/gf127_test.go +++ b/gf127/gf127_test.go @@ -1,17 +1,18 @@ package gf127 import ( - "math/rand" "testing" ) const maxUint64 = ^uint64(0) func TestAdd(t *testing.T) { - a := &GF127{rand.Uint64(), rand.Uint64() >> 1} - b := &GF127{rand.Uint64(), rand.Uint64() >> 1} - e := &GF127{a[0] ^ b[0], a[1] ^ b[1]} - c := &GF127{0, 0} + var ( + a = Random() + b = Random() + e = &GF127{a[0] ^ b[0], a[1] ^ b[1]} + c = new(GF127) + ) c.Add(a, b) if e[0] != c[0] || e[1] != c[1] { t.Errorf("expected (%s), got (%s)", e.String(), c.String()) @@ -74,10 +75,22 @@ var testCasesInv = [][2]*GF127{ } func TestInv(t *testing.T) { - c := new(GF127) + var a, b, c = new(GF127), new(GF127), new(GF127) for _, tc := range testCasesInv { if Inv(tc[0], c); !c.Equals(tc[1]) { t.Errorf("expected (%s), got (%s)", tc[1].String(), c.String()) } } + + for i := 0; i < 3; i++ { + // 0 has no inverse + if a = Random(); a.Equals(&GF127{0, 0}) { + continue + } + Inv(a, b) + Mul(a, b, c) + if !c.Equals(&GF127{1, 0}) { + t.Errorf("expected inverse of (%s), got (%s)", a.String(), b.String()) + } + } }