1
2
3
4
5 package rsa
6
7 import (
8 "bufio"
9 "encoding/hex"
10 "fmt"
11 "os"
12 "strings"
13 "testing"
14 )
15
16 func TestMillerRabin(t *testing.T) {
17 f, err := os.Open("testdata/miller_rabin_tests.txt")
18 if err != nil {
19 t.Fatal(err)
20 }
21
22 var expected bool
23 var W, B string
24 var lineNum int
25 scanner := bufio.NewScanner(f)
26 for scanner.Scan() {
27 lineNum++
28 line := scanner.Text()
29 if len(line) == 0 || line[0] == '#' {
30 continue
31 }
32
33 k, v, _ := strings.Cut(line, " = ")
34 switch k {
35 case "Result":
36 switch v {
37 case "Composite":
38 expected = millerRabinCOMPOSITE
39 case "PossiblyPrime":
40 expected = millerRabinPOSSIBLYPRIME
41 default:
42 t.Fatalf("unknown result %q on line %d", v, lineNum)
43 }
44 case "W":
45 W = v
46 case "B":
47 B = v
48
49 t.Run(fmt.Sprintf("line %d", lineNum), func(t *testing.T) {
50 if len(W)%2 != 0 {
51 W = "0" + W
52 }
53 for len(B) < len(W) {
54 B = "0" + B
55 }
56
57 mr, err := millerRabinSetup(decodeHex(t, W))
58 if err != nil {
59 t.Logf("W = %s", W)
60 t.Logf("B = %s", B)
61 t.Fatalf("failed to set up Miller-Rabin test: %v", err)
62 }
63
64 result, err := millerRabinIteration(mr, decodeHex(t, B))
65 if err != nil {
66 t.Logf("W = %s", W)
67 t.Logf("B = %s", B)
68 t.Fatalf("failed to run Miller-Rabin test: %v", err)
69 }
70
71 if result != expected {
72 t.Logf("W = %s", W)
73 t.Logf("B = %s", B)
74 t.Fatalf("unexpected result: got %v, want %v", result, expected)
75 }
76 })
77 default:
78 t.Fatalf("unknown key %q on line %d", k, lineNum)
79 }
80 }
81 if err := scanner.Err(); err != nil {
82 t.Fatal(err)
83 }
84 }
85
86 func decodeHex(t *testing.T, s string) []byte {
87 t.Helper()
88 b, err := hex.DecodeString(s)
89 if err != nil {
90 t.Fatalf("failed to decode hex %q: %v", s, err)
91 }
92 return b
93 }
94
View as plain text