...
Source file
src/crypto/ed25519/ed25519vectors_test.go
1
2
3
4
5 package ed25519_test
6
7 import (
8 "crypto/ed25519"
9 "encoding/hex"
10 "encoding/json"
11 "internal/testenv"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "testing"
16 )
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 func TestEd25519Vectors(t *testing.T) {
33 jsonVectors := downloadEd25519Vectors(t)
34 var vectors []struct {
35 A, R, S, M string
36 Flags []string
37 }
38 if err := json.Unmarshal(jsonVectors, &vectors); err != nil {
39 t.Fatal(err)
40 }
41 for i, v := range vectors {
42 expectedToVerify := true
43 for _, f := range v.Flags {
44 switch f {
45
46
47
48
49
50 case "LowOrderResidue":
51 expectedToVerify = false
52
53
54
55 case "NonCanonicalR":
56 expectedToVerify = false
57 }
58 }
59
60 publicKey := decodeHex(t, v.A)
61 signature := append(decodeHex(t, v.R), decodeHex(t, v.S)...)
62 message := []byte(v.M)
63
64 didVerify := ed25519.Verify(publicKey, message, signature)
65 if didVerify && !expectedToVerify {
66 t.Errorf("#%d: vector with flags %s unexpectedly verified", i, v.Flags)
67 }
68 if !didVerify && expectedToVerify {
69 t.Errorf("#%d: vector with flags %s unexpectedly rejected", i, v.Flags)
70 }
71 }
72 }
73
74 func downloadEd25519Vectors(t *testing.T) []byte {
75 testenv.MustHaveExternalNetwork(t)
76
77
78
79 goTool := testenv.GoToolPath(t)
80 path := "filippo.io/mostly-harmless/[email protected]"
81 cmd := exec.Command(goTool, "mod", "download", "-json", path)
82
83 cmd.Env = append(os.Environ(), "GONOSUMDB=*")
84 output, err := cmd.Output()
85 if err != nil {
86 t.Fatalf("failed to run `go mod download -json %s`, output: %s", path, output)
87 }
88 var dm struct {
89 Dir string
90 }
91 if err := json.Unmarshal(output, &dm); err != nil {
92 t.Fatal(err)
93 }
94
95 jsonVectors, err := os.ReadFile(filepath.Join(dm.Dir, "ed25519vectors.json"))
96 if err != nil {
97 t.Fatalf("failed to read ed25519vectors.json: %v", err)
98 }
99 return jsonVectors
100 }
101
102 func decodeHex(t *testing.T, s string) []byte {
103 t.Helper()
104 b, err := hex.DecodeString(s)
105 if err != nil {
106 t.Errorf("invalid hex: %v", err)
107 }
108 return b
109 }
110
View as plain text