forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_test.go
123 lines (102 loc) · 2.61 KB
/
hash_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Copyright 2020 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package bundle
import (
"bytes"
"encoding/json"
"testing"
)
func TestHashFile(t *testing.T) {
mapInput := map[string]interface{}{
"key1": []interface{}{
"element1",
"element2",
},
"key2": map[string]interface{}{
"a": 0,
"b": 1,
"c": json.Number("123.45678911111111111111111111111111111111111111111111111"),
},
}
arrayInput := []interface{}{
[]string{"foo", "bar"},
mapInput,
`package example`,
[]string{"$", "α", "©", "™"},
}
tests := map[string]struct {
input interface{}
algorithm HashingAlgorithm
}{
"map": {mapInput, SHA256},
"array": {arrayInput, MD5},
"string": {"abc", SHA256},
"string_with_html_chars": {"<foo></foo>", SHA256},
"null": {`null`, SHA512},
"bool": {false, SHA256},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
h, _ := NewSignatureHasher(tc.algorithm)
// compute hash from the raw bytes
a := encodePrimitive(tc.input)
hash := h.(*hasher).h()
hash.Write(a)
d1 := hash.Sum(nil)
// compute hash on the input
d2, err := h.(*hasher).HashFile(tc.input)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if !bytes.Equal(d1, d2) {
t.Fatalf("Digests are not equal. Expected: %x but got: %x", d1, d2)
}
})
}
}
func TestHashFileBytes(t *testing.T) {
mapInput := map[string]interface{}{
"key1": []interface{}{
"element1",
"element2",
},
"key2": map[string]interface{}{
"a": 0,
"b": 1,
"c": json.Number("123.45678911111111111111111111111111111111111111111111111"),
},
}
arrayInput := []interface{}{
[]string{"foo", "bar"},
mapInput,
`package example`,
[]string{"$", "α", "©", "™"},
}
arrayBytes, _ := json.Marshal(arrayInput)
mapBytes, _ := json.Marshal(mapInput)
tests := map[string]struct {
input []byte
algorithm HashingAlgorithm
}{
"map_byte_array": {mapBytes, SHA256},
"array_byte_array": {arrayBytes, MD5},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
h, _ := NewSignatureHasher(tc.algorithm)
// compute hash from the raw bytes
hash := h.(*hasher).h()
hash.Write(tc.input)
d1 := hash.Sum(nil)
// compute hash on the input
d2, err := h.(*hasher).HashFile(tc.input)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if !bytes.Equal(d1, d2) {
t.Fatalf("Digests are not equal. Expected: %x but got: %x", d1, d2)
}
})
}
}