github.com/cloudflare/circl@v1.5.0/group/hash_test.go (about) 1 package group_test 2 3 import ( 4 "encoding/hex" 5 "encoding/json" 6 "fmt" 7 "os" 8 "path/filepath" 9 "testing" 10 11 "github.com/cloudflare/circl/group" 12 "github.com/cloudflare/circl/internal/test" 13 ) 14 15 func TestHashToElement(t *testing.T) { 16 fileNames, err := filepath.Glob("./testdata/P*.json") 17 if err != nil { 18 t.Fatal(err) 19 } 20 21 for _, fileName := range fileNames { 22 f, err := os.Open(fileName) 23 if err != nil { 24 t.Fatal(err) 25 } 26 dec := json.NewDecoder(f) 27 var v vectorSuite 28 err = dec.Decode(&v) 29 if err != nil { 30 t.Fatal(err) 31 } 32 f.Close() 33 34 t.Run(v.Ciphersuite, func(t *testing.T) { testHashing(t, &v) }) 35 } 36 } 37 38 func testHashing(t *testing.T, vs *vectorSuite) { 39 var G group.Group 40 switch vs.Ciphersuite[0:4] { 41 case "P256": 42 G = group.P256 43 case "P384": 44 G = group.P384 45 case "P521": 46 G = group.P521 47 default: 48 t.Fatal("non supported suite") 49 } 50 51 hashFunc := G.HashToElement 52 if !vs.RandomOracle { 53 hashFunc = G.HashToElementNonUniform 54 } 55 56 want := G.NewElement() 57 for i, v := range vs.Vectors { 58 got := hashFunc([]byte(v.Msg), []byte(vs.Dst)) 59 err := want.UnmarshalBinary(v.P.toBytes()) 60 if err != nil { 61 t.Fatal(err) 62 } 63 64 if !got.IsEqual(want) { 65 test.ReportError(t, got, want, i) 66 } 67 } 68 } 69 70 type vectorSuite struct { 71 L string `json:"L"` 72 Z string `json:"Z"` 73 Ciphersuite string `json:"ciphersuite"` 74 Curve string `json:"curve"` 75 Dst string `json:"dst"` 76 Expand string `json:"expand"` 77 Field struct { 78 M string `json:"m"` 79 P string `json:"p"` 80 } `json:"field"` 81 Hash string `json:"hash"` 82 K string `json:"k"` 83 Map struct { 84 Name string `json:"name"` 85 } `json:"map"` 86 RandomOracle bool `json:"randomOracle"` 87 Vectors []vector `json:"vectors"` 88 } 89 90 type point struct { 91 X string `json:"x"` 92 Y string `json:"y"` 93 } 94 95 func (p point) toBytes() []byte { 96 x, err := hex.DecodeString(p.X[2:]) 97 if err != nil { 98 panic(err) 99 } 100 y, err := hex.DecodeString(p.Y[2:]) 101 if err != nil { 102 panic(err) 103 } 104 return append(append([]byte{0x04}, x...), y...) 105 } 106 107 type vector struct { 108 P point `json:"P"` 109 Q0 point `json:"Q0,omitempty"` 110 Q1 point `json:"Q1,omitempty"` 111 Q point `json:"Q,omitempty"` 112 Msg string `json:"msg"` 113 U []string `json:"u"` 114 } 115 116 func BenchmarkHash(b *testing.B) { 117 for _, g := range allGroups { 118 name := g.(fmt.Stringer).String() 119 b.Run(name+"/HashToElement", func(b *testing.B) { 120 for i := 0; i < b.N; i++ { 121 g.HashToElement(nil, nil) 122 } 123 }) 124 b.Run(name+"/HashToElementNonUniform", func(b *testing.B) { 125 for i := 0; i < b.N; i++ { 126 g.HashToElementNonUniform(nil, nil) 127 } 128 }) 129 b.Run(name+"/HashToScalar", func(b *testing.B) { 130 for i := 0; i < b.N; i++ { 131 g.HashToScalar(nil, nil) 132 } 133 }) 134 } 135 }