• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17package cryptofmt_test
18
19import (
20	"testing"
21
22	"github.com/google/tink/go/core/cryptofmt"
23	tinkpb "github.com/google/tink/go/proto/tink_go_proto"
24)
25
26var tests = []struct {
27	keyID  uint32
28	result string // expected prefix
29}{
30	{
31		keyID:  1000000,
32		result: string([]byte{0, 15, 66, 64}),
33	},
34	{
35		keyID:  4294967295,
36		result: string([]byte{255, 255, 255, 255}),
37	},
38	{
39		keyID:  0,
40		result: string([]byte{0, 0, 0, 0}),
41	},
42}
43
44func TestOutputPrefix(t *testing.T) {
45	key := new(tinkpb.Keyset_Key)
46	for i, test := range tests {
47		key.KeyId = test.keyID
48		// legacy type
49		key.OutputPrefixType = tinkpb.OutputPrefixType_LEGACY
50		prefix, err := cryptofmt.OutputPrefix(key)
51		if err != nil || !validatePrefix(prefix, cryptofmt.LegacyStartByte, test.result) {
52			t.Errorf("incorrect legacy prefix in test %d", i)
53		}
54		// crunchy type
55		key.OutputPrefixType = tinkpb.OutputPrefixType_CRUNCHY
56		prefix, err = cryptofmt.OutputPrefix(key)
57		if err != nil || !validatePrefix(prefix, cryptofmt.LegacyStartByte, test.result) {
58			t.Errorf("incorrect legacy prefix in test %d", i)
59		}
60		// tink type
61		key.OutputPrefixType = tinkpb.OutputPrefixType_TINK
62		prefix, err = cryptofmt.OutputPrefix(key)
63		if err != nil || !validatePrefix(prefix, cryptofmt.TinkStartByte, test.result) {
64			t.Errorf("incorrect tink prefix in test %d", i)
65		}
66		// raw type
67		key.OutputPrefixType = tinkpb.OutputPrefixType_RAW
68		prefix, err = cryptofmt.OutputPrefix(key)
69		if err != nil || prefix != cryptofmt.RawPrefix {
70			t.Errorf("incorrect raw prefix in test %d", i)
71		}
72	}
73	// unknown prefix type
74	key.OutputPrefixType = tinkpb.OutputPrefixType_UNKNOWN_PREFIX
75	if _, err := cryptofmt.OutputPrefix(key); err == nil {
76		t.Errorf("expect an error when prefix type is unknown")
77	}
78}
79
80func validatePrefix(prefix string, startByte byte, key string) bool {
81	if prefix[0] != startByte {
82		return false
83	}
84	return prefix[1:] == key
85}
86