1 package ed25519_test
2
3 import (
4 "bytes"
5 "encoding/hex"
6 "encoding/json"
7 "io"
8 "os"
9 "testing"
10
11 "github.com/cloudflare/circl/internal/test"
12 "github.com/cloudflare/circl/sign/ed25519"
13 )
14
15 type group struct {
16 Key struct {
17 Curve string `json:"curve"`
18 Size int `json:"keySize"`
19 Pk string `json:"pk"`
20 Sk string `json:"sk"`
21 Type string `json:"type"`
22 } `json:"key"`
23 Type string `json:"type"`
24 Tests []struct {
25 TcID int `json:"tcId"`
26 Comment string `json:"comment"`
27 Msg string `json:"msg"`
28 Sig string `json:"sig"`
29 Result string `json:"result"`
30 Flags []string `json:"flags"`
31 } `json:"tests"`
32 }
33
34 type Wycheproof struct {
35 Alg string `json:"algorithm"`
36 Version string `json:"generatorVersion"`
37 Num int `json:"numberOfTests"`
38 Groups []group `json:"testGroups"`
39 }
40
41 func (kat *Wycheproof) readFile(t *testing.T, fileName string) {
42 jsonFile, err := os.Open(fileName)
43 if err != nil {
44 t.Fatalf("File %v can not be opened. Error: %v", fileName, err)
45 }
46 defer jsonFile.Close()
47 input, err := io.ReadAll(jsonFile)
48 if err != nil {
49 t.Fatalf("File %v can not be read. Error: %v", fileName, err)
50 }
51
52 err = json.Unmarshal(input, &kat)
53 if err != nil {
54 t.Fatalf("File %v can not be loaded. Error: %v", fileName, err)
55 }
56 }
57
58 func (kat *Wycheproof) keyPair(t *testing.T) {
59 for i, g := range kat.Groups {
60 if g.Key.Curve != "edwards25519" {
61 t.Errorf("Curve not expected %v", g.Key.Curve)
62 }
63 private, _ := hex.DecodeString(g.Key.Sk)
64 public, _ := hex.DecodeString(g.Key.Pk)
65 keys := ed25519.NewKeyFromSeed(private)
66 got := keys.Public().(ed25519.PublicKey)
67 want := public
68
69 if !bytes.Equal(got, want) {
70 test.ReportError(t, got, want, i, g.Key.Sk)
71 }
72 }
73 }
74
75 func (kat *Wycheproof) verify(t *testing.T) {
76 for i, g := range kat.Groups {
77 for _, gT := range g.Tests {
78 isValid := gT.Result == "valid"
79 private, _ := hex.DecodeString(g.Key.Sk)
80 public, _ := hex.DecodeString(g.Key.Pk)
81 sig, _ := hex.DecodeString(gT.Sig)
82 msg, _ := hex.DecodeString(gT.Msg)
83
84 priv := ed25519.NewKeyFromSeed(private)
85 got := priv.Public().(ed25519.PublicKey)
86 want := public
87 if !bytes.Equal(got, want) {
88 test.ReportError(t, got, want, i, gT.TcID)
89 }
90 if isValid {
91 got := ed25519.Sign(priv, msg)
92 want := sig
93 if !bytes.Equal(got, want) {
94 test.ReportError(t, got, want, i, gT.TcID)
95 }
96 }
97 {
98 got := ed25519.Verify(priv.Public().(ed25519.PublicKey), msg, sig)
99 want := isValid
100 if got != want {
101 test.ReportError(t, got, want, i, gT.TcID)
102 }
103 }
104 }
105 }
106 }
107
108 func TestWycheproof(t *testing.T) {
109
110 var kat Wycheproof
111 kat.readFile(t, "testdata/wycheproof_Ed25519.json")
112 t.Run("EDDSAKeyPair", kat.keyPair)
113 t.Run("EDDSAVerify", kat.verify)
114 }
115
View as plain text