File: key_manager_test.go

package info (click to toggle)
golang-github-tink-crypto-tink-go 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,952 kB
  • sloc: sh: 864; makefile: 6
file content (331 lines) | stat: -rw-r--r-- 10,291 bytes parent folder | download
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package aescmac_test

import (
	"encoding/hex"
	"fmt"
	"testing"

	"google.golang.org/protobuf/proto"
	"github.com/tink-crypto/tink-go/v2/core/registry"
	subtleMac "github.com/tink-crypto/tink-go/v2/mac/subtle"
	"github.com/tink-crypto/tink-go/v2/subtle/random"
	"github.com/tink-crypto/tink-go/v2/testutil"
	cmacpb "github.com/tink-crypto/tink-go/v2/proto/aes_cmac_go_proto"
	tinkpb "github.com/tink-crypto/tink-go/v2/proto/tink_go_proto"
)

func TestKeyManagerPrimitiveBasic(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("AESCMAC key manager not found: %s", err)
	}
	testKeys := genValidCMACKeys()
	for i := 0; i < len(testKeys); i++ {
		serializedKey, err := proto.Marshal(testKeys[i])
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		p, err := km.Primitive(serializedKey)
		if err != nil {
			t.Errorf("unexpected error in test case %d: %s", i, err)
		}
		if err := validateCMACPrimitive(p, testKeys[i]); err != nil {
			t.Errorf("%s", err)
		}
	}
}

func TestKeyManagerPrimitiveWithInvalidInput(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("cannot obtain AESCMAC key manager: %s", err)
	}
	// invalid key
	testKeys := genInvalidCMACKeys()
	for i := 0; i < len(testKeys); i++ {
		serializedKey, err := proto.Marshal(testKeys[i])
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		if _, err := km.Primitive(serializedKey); err == nil {
			t.Errorf("expect an error in test case %d", i)
		}
	}
	if _, err := km.Primitive(nil); err == nil {
		t.Errorf("expect an error when input is nil")
	}
	// empty input
	if _, err := km.Primitive([]byte{}); err == nil {
		t.Errorf("expect an error when input is empty")
	}
}

func TestKeyManagerNewKeyMultipleTimes(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("cannot obtain AESCMAC key manager: %s", err)
	}
	serializedFormat, err := proto.Marshal(testutil.NewAESCMACKeyFormat(16))
	if err != nil {
		t.Fatalf("proto.Marshal() err = %q, want nil", err)
	}
	keys := make(map[string]bool)
	nTest := 26
	for i := 0; i < nTest; i++ {
		key, err := km.NewKey(serializedFormat)
		if err != nil {
			t.Fatalf("km.NewKey() err = %q, want nil", err)
		}
		serializedKey, err := proto.Marshal(key)
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		keys[string(serializedKey)] = true

		keyData, err := km.NewKeyData(serializedFormat)
		if err != nil {
			t.Fatalf("km.NewKeyData() err = %q, want nil", err)
		}
		serializedKey = keyData.Value
		keys[string(serializedKey)] = true
	}
	if len(keys) != nTest*2 {
		t.Errorf("key is repeated")
	}
}

func TestKeyManagerNewKeyBasic(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("cannot obtain AESCMAC key manager: %s", err)
	}
	testFormats := genValidCMACKeyFormats()
	for i := 0; i < len(testFormats); i++ {
		serializedFormat, err := proto.Marshal(testFormats[i])
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		key, err := km.NewKey(serializedFormat)
		if err != nil {
			t.Errorf("unexpected error in test case %d: %s", i, err)
		}
		if err := validateCMACKey(testFormats[i], key.(*cmacpb.AesCmacKey)); err != nil {
			t.Errorf("%s", err)
		}
	}
}

func TestKeyManagerNewKeyWithInvalidInput(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("cannot obtain AESCMAC key manager: %s", err)
	}
	// invalid key formats
	testFormats := genInvalidCMACKeyFormats()
	for i := 0; i < len(testFormats); i++ {
		serializedFormat, err := proto.Marshal(testFormats[i])
		if err != nil {
			fmt.Println("Error!")
		}
		if _, err := km.NewKey(serializedFormat); err == nil {
			t.Errorf("expect an error in test case %d: %s", i, err)
		}
	}
	if _, err := km.NewKey(nil); err == nil {
		t.Errorf("expect an error when input is nil")
	}
	// empty input
	if _, err := km.NewKey([]byte{}); err == nil {
		t.Errorf("expect an error when input is empty")
	}
}

func TestKeyManagerNewKeyDataBasic(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("cannot obtain AESCMAC key manager: %s", err)
	}
	testFormats := genValidCMACKeyFormats()
	for i := 0; i < len(testFormats); i++ {
		serializedFormat, err := proto.Marshal(testFormats[i])
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		keyData, err := km.NewKeyData(serializedFormat)
		if err != nil {
			t.Errorf("unexpected error in test case %d: %s", i, err)
		}
		if keyData.TypeUrl != testutil.AESCMACTypeURL {
			t.Errorf("incorrect type url in test case %d", i)
		}
		if keyData.KeyMaterialType != tinkpb.KeyData_SYMMETRIC {
			t.Errorf("incorrect key material type in test case %d", i)
		}
		key := new(cmacpb.AesCmacKey)
		if err := proto.Unmarshal(keyData.Value, key); err != nil {
			t.Errorf("invalid key value")
		}
		if err := validateCMACKey(testFormats[i], key); err != nil {
			t.Errorf("invalid key")
		}
	}
}

func TestKeyManagerNewKeyDataWithInvalidInput(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("AESCMAC key manager not found: %s", err)
	}
	// invalid key formats
	testFormats := genInvalidCMACKeyFormats()
	for i := 0; i < len(testFormats); i++ {
		serializedFormat, err := proto.Marshal(testFormats[i])
		if err != nil {
			t.Fatalf("proto.Marshal() err = %q, want nil", err)
		}
		if _, err := km.NewKeyData(serializedFormat); err == nil {
			t.Errorf("expect an error in test case %d", i)
		}
	}
	// nil input
	if _, err := km.NewKeyData(nil); err == nil {
		t.Errorf("expect an error when input is nil")
	}
}

func TestKeyManagerDoesSupport(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("AESCMAC key manager not found: %s", err)
	}
	if !km.DoesSupport(testutil.AESCMACTypeURL) {
		t.Errorf("AESCMACKeyManager must support %s", testutil.AESCMACTypeURL)
	}
	if km.DoesSupport("some bad type") {
		t.Errorf("AESCMACKeyManager must support only %s", testutil.AESCMACTypeURL)
	}
}

func TestKeyManagerTypeURL(t *testing.T) {
	km, err := registry.GetKeyManager(testutil.AESCMACTypeURL)
	if err != nil {
		t.Errorf("AESCMAC key manager not found: %s", err)
	}
	if km.TypeURL() != testutil.AESCMACTypeURL {
		t.Errorf("incorrect GetKeyType()")
	}
}

func genInvalidCMACKeys() []proto.Message {
	badVersionKey := testutil.NewAESCMACKey(16)
	badVersionKey.Version++
	shortKey := testutil.NewAESCMACKey(16)
	shortKey.KeyValue = []byte{1, 1}
	nilParams := testutil.NewAESCMACKey(16)
	nilParams.Params = nil
	return []proto.Message{
		// not a AESCMACKey
		testutil.NewAESCMACParams(16),
		// bad version
		badVersionKey,
		// tag size too big
		testutil.NewAESCMACKey(17),
		// tag size too small
		testutil.NewAESCMACKey(1),
		// key too short
		shortKey,
		// params field is unset
		nilParams,
	}
}

func genInvalidCMACKeyFormats() []proto.Message {
	shortKeyFormat := testutil.NewAESCMACKeyFormat(16)
	shortKeyFormat.KeySize = 1
	nilParams := testutil.NewAESCMACKeyFormat(16)
	nilParams.Params = nil
	return []proto.Message{
		// not a AESCMACKeyFormat
		testutil.NewAESCMACParams(16),
		// tag size too big
		testutil.NewAESCMACKeyFormat(17),
		// tag size too small
		testutil.NewAESCMACKeyFormat(1),
		// key too short
		shortKeyFormat,
		// params field is unset
		nilParams,
	}
}

func genValidCMACKeyFormats() []*cmacpb.AesCmacKeyFormat {
	return []*cmacpb.AesCmacKeyFormat{
		testutil.NewAESCMACKeyFormat(10),
		testutil.NewAESCMACKeyFormat(16),
	}
}

func genValidCMACKeys() []*cmacpb.AesCmacKey {
	return []*cmacpb.AesCmacKey{
		testutil.NewAESCMACKey(10),
		testutil.NewAESCMACKey(16),
	}
}

// Checks whether the given AESCMACKey matches the given key AESCMACKeyFormat
func validateCMACKey(format *cmacpb.AesCmacKeyFormat, key *cmacpb.AesCmacKey) error {
	if format.KeySize != uint32(len(key.KeyValue)) ||
		key.Params.TagSize != format.Params.TagSize {
		return fmt.Errorf("key format and generated key do not match")
	}
	p, err := subtleMac.NewAESCMAC(key.KeyValue, key.Params.TagSize)
	if err != nil {
		return fmt.Errorf("cannot create primitive from key: %s", err)
	}
	return validateCMACPrimitive(p, key)
}

// validateCMACPrimitive checks whether the given primitive matches the given AESCMACKey
func validateCMACPrimitive(p any, key *cmacpb.AesCmacKey) error {
	cmacPrimitive := p.(*subtleMac.AESCMAC)
	keyPrimitive, err := subtleMac.NewAESCMAC(key.KeyValue, key.Params.TagSize)
	if err != nil {
		return fmt.Errorf("Could not create AES CMAC with key material %q and tag size %d: %s", hex.EncodeToString(key.KeyValue), key.Params.TagSize, err)
	}
	data := random.GetRandomBytes(20)
	mac, err := cmacPrimitive.ComputeMAC(data)
	if err != nil {
		return fmt.Errorf("mac computation failed: %s", err)
	}
	keyMac, err := keyPrimitive.ComputeMAC(data)
	if err != nil {
		return fmt.Errorf("mac computation with provided key failed: %s", err)
	}
	if err = cmacPrimitive.VerifyMAC(mac, data); err != nil {
		return fmt.Errorf("mac self verification failed: %s", err)
	}
	if err = cmacPrimitive.VerifyMAC(keyMac, data); err != nil {
		return fmt.Errorf("mac computed with the provided key could not be verified: %s", err)
	}
	if err = keyPrimitive.VerifyMAC(mac, data); err != nil {
		return fmt.Errorf("mac could not be verified by primitive using the provided key: %s", err)
	}
	if err = keyPrimitive.VerifyMAC(keyMac, data); err != nil {
		return fmt.Errorf("mac self verification of mac created with the provided key failed: %s", err)
	}
	return nil
}