...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package rfc6962
16
17 import (
18 "bytes"
19 "encoding/hex"
20 "testing"
21 )
22
23 func TestRFC6962Hasher(t *testing.T) {
24 hasher := DefaultHasher
25
26 leafHash := hasher.HashLeaf([]byte("L123456"))
27 emptyLeafHash := hasher.HashLeaf([]byte{})
28
29 for _, tc := range []struct {
30 desc string
31 got []byte
32 want string
33 }{
34
35 {
36 desc: "RFC6962 Empty",
37 want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
38 got: hasher.EmptyRoot(),
39 },
40
41
42 {
43 desc: "RFC6962 Empty Leaf",
44 want: "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
45 got: emptyLeafHash,
46 },
47
48 {
49 desc: "RFC6962 Leaf",
50 want: "395aa064aa4c29f7010acfe3f25db9485bbd4b91897b6ad7ad547639252b4d56",
51 got: leafHash,
52 },
53
54 {
55 desc: "RFC6962 Node",
56 want: "aa217fe888e47007fa15edab33c2b492a722cb106c64667fc2b044444de66bbb",
57 got: hasher.HashChildren([]byte("N123"), []byte("N456")),
58 },
59 } {
60 t.Run(tc.desc, func(t *testing.T) {
61 wantBytes, err := hex.DecodeString(tc.want)
62 if err != nil {
63 t.Fatalf("hex.DecodeString(%x): %v", tc.want, err)
64 }
65 if got, want := tc.got, wantBytes; !bytes.Equal(got, want) {
66 t.Errorf("got %x, want %x", got, want)
67 }
68 })
69 }
70 }
71
72
73 func TestRFC6962HasherCollisions(t *testing.T) {
74 hasher := DefaultHasher
75
76
77 leaf1, leaf2 := []byte("Hello"), []byte("World")
78 hash1 := hasher.HashLeaf(leaf1)
79 hash2 := hasher.HashLeaf(leaf2)
80 if bytes.Equal(hash1, hash2) {
81 t.Errorf("Leaf hashes should differ, but both are %x", hash1)
82 }
83
84
85 subHash1 := hasher.HashChildren(hash1, hash2)
86
87 preimage := append(hash1, hash2...)
88 forgedHash := hasher.HashLeaf(preimage)
89 if bytes.Equal(subHash1, forgedHash) {
90 t.Errorf("Hasher is not second-preimage resistant")
91 }
92
93
94 subHash2 := hasher.HashChildren(hash2, hash1)
95 if bytes.Equal(subHash1, subHash2) {
96 t.Errorf("Subtree hash does not depend on the order of leaves")
97 }
98 }
99
100 func BenchmarkHashChildren(b *testing.B) {
101 h := DefaultHasher
102 l := h.HashLeaf([]byte("one"))
103 r := h.HashLeaf([]byte("or other"))
104 for i := 0; i < b.N; i++ {
105 _ = h.HashChildren(l, r)
106 }
107 }
108
View as plain text