xref: /aosp_15_r20/external/tink/go/mac/mac_key_templates_test.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2018 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 mac_test
18
19import (
20	"testing"
21
22	"github.com/google/tink/go/keyset"
23	"github.com/google/tink/go/mac"
24	tinkpb "github.com/google/tink/go/proto/tink_go_proto"
25)
26
27func TestKeyTemplates(t *testing.T) {
28	var testCases = []struct {
29		name     string
30		template *tinkpb.KeyTemplate
31	}{
32		{name: "HMAC_SHA256_128BITTAG",
33			template: mac.HMACSHA256Tag128KeyTemplate()},
34		{name: "HMAC_SHA256_256BITTAG",
35			template: mac.HMACSHA256Tag256KeyTemplate()},
36		{name: "HMAC_SHA512_256BITTAG",
37			template: mac.HMACSHA512Tag256KeyTemplate()},
38		{name: "HMAC_SHA512_512BITTAG",
39			template: mac.HMACSHA512Tag512KeyTemplate()},
40		{name: "AES_CMAC",
41			template: mac.AESCMACTag128KeyTemplate()},
42	}
43	for _, tc := range testCases {
44		t.Run(tc.name, func(t *testing.T) {
45			handle, err := keyset.NewHandle(tc.template)
46			if err != nil {
47				t.Fatalf("keyset.NewHandle(tc.template) failed: %v", err)
48			}
49			primitive, err := mac.New(handle)
50			if err != nil {
51				t.Fatalf("mac.New(handle) failed: %v", err)
52			}
53
54			var testInputs = []struct {
55				message1 []byte
56				message2 []byte
57			}{
58				{
59					message1: []byte("this data needs to be authenticated"),
60					message2: []byte("this data needs to be authenticated"),
61				}, {
62					message1: []byte(""),
63					message2: []byte(""),
64				}, {
65					message1: []byte(""),
66					message2: nil,
67				}, {
68					message1: nil,
69					message2: []byte(""),
70				}, {
71					message1: nil,
72					message2: nil,
73				},
74			}
75			for _, ti := range testInputs {
76				tag, err := primitive.ComputeMAC(ti.message1)
77				if err != nil {
78					t.Fatalf("primitive.ComputeMAC(ti.message1) failed: %v", err)
79				}
80				if primitive.VerifyMAC(tag, ti.message2); err != nil {
81					t.Errorf("primitive.VerifyMAC(tag, ti.message2) failed: %v", err)
82				}
83			}
84		})
85	}
86}
87