xref: /aosp_15_r20/external/tink/go/mac/hmac_key_manager.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
18
19import (
20	"errors"
21	"fmt"
22	"io"
23
24	"google.golang.org/protobuf/proto"
25	"github.com/google/tink/go/keyset"
26	"github.com/google/tink/go/mac/subtle"
27	"github.com/google/tink/go/subtle/random"
28	commonpb "github.com/google/tink/go/proto/common_go_proto"
29	hmacpb "github.com/google/tink/go/proto/hmac_go_proto"
30	tinkpb "github.com/google/tink/go/proto/tink_go_proto"
31)
32
33const (
34	hmacKeyVersion = 0
35	hmacTypeURL    = "type.googleapis.com/google.crypto.tink.HmacKey"
36)
37
38var errInvalidHMACKey = errors.New("hmac_key_manager: invalid key")
39var errInvalidHMACKeyFormat = errors.New("hmac_key_manager: invalid key format")
40
41// hmacKeyManager generates new HMAC keys and produces new instances of HMAC.
42type hmacKeyManager struct{}
43
44// Primitive constructs a HMAC instance for the given serialized HMACKey.
45func (km *hmacKeyManager) Primitive(serializedKey []byte) (interface{}, error) {
46	if len(serializedKey) == 0 {
47		return nil, errInvalidHMACKey
48	}
49	key := new(hmacpb.HmacKey)
50	if err := proto.Unmarshal(serializedKey, key); err != nil {
51		return nil, errInvalidHMACKey
52	}
53	if err := km.validateKey(key); err != nil {
54		return nil, err
55	}
56	hash := commonpb.HashType_name[int32(key.Params.Hash)]
57	hmac, err := subtle.NewHMAC(hash, key.KeyValue, key.Params.TagSize)
58	if err != nil {
59		return nil, err
60	}
61	return hmac, nil
62}
63
64// NewKey generates a new HMACKey according to specification in the given HMACKeyFormat.
65func (km *hmacKeyManager) NewKey(serializedKeyFormat []byte) (proto.Message, error) {
66	if len(serializedKeyFormat) == 0 {
67		return nil, errInvalidHMACKeyFormat
68	}
69	keyFormat := new(hmacpb.HmacKeyFormat)
70	if err := proto.Unmarshal(serializedKeyFormat, keyFormat); err != nil {
71		return nil, errInvalidHMACKeyFormat
72	}
73	if err := km.validateKeyFormat(keyFormat); err != nil {
74		return nil, fmt.Errorf("hmac_key_manager: invalid key format: %s", err)
75	}
76	keyValue := random.GetRandomBytes(keyFormat.KeySize)
77	return &hmacpb.HmacKey{
78		Version:  hmacKeyVersion,
79		Params:   keyFormat.Params,
80		KeyValue: keyValue,
81	}, nil
82}
83
84// NewKeyData generates a new KeyData according to specification in the given
85// serialized HMACKeyFormat. This should be used solely by the key management API.
86func (km *hmacKeyManager) NewKeyData(serializedKeyFormat []byte) (*tinkpb.KeyData, error) {
87	key, err := km.NewKey(serializedKeyFormat)
88	if err != nil {
89		return nil, err
90	}
91	serializedKey, err := proto.Marshal(key)
92	if err != nil {
93		return nil, errInvalidHMACKeyFormat
94	}
95
96	return &tinkpb.KeyData{
97		TypeUrl:         hmacTypeURL,
98		Value:           serializedKey,
99		KeyMaterialType: km.KeyMaterialType(),
100	}, nil
101}
102
103// DoesSupport checks whether this KeyManager supports the given key type.
104func (km *hmacKeyManager) DoesSupport(typeURL string) bool {
105	return typeURL == hmacTypeURL
106}
107
108// TypeURL returns the type URL of keys managed by this KeyManager.
109func (km *hmacKeyManager) TypeURL() string {
110	return hmacTypeURL
111}
112
113// KeyMaterialType returns the key material type of this key manager.
114func (km *hmacKeyManager) KeyMaterialType() tinkpb.KeyData_KeyMaterialType {
115	return tinkpb.KeyData_SYMMETRIC
116}
117
118// DeriveKey derives a new key from serializedKeyFormat and pseudorandomness.
119func (km *hmacKeyManager) DeriveKey(serializedKeyFormat []byte, pseudorandomness io.Reader) (proto.Message, error) {
120	if len(serializedKeyFormat) == 0 {
121		return nil, errInvalidHMACKeyFormat
122	}
123	keyFormat := new(hmacpb.HmacKeyFormat)
124	if err := proto.Unmarshal(serializedKeyFormat, keyFormat); err != nil {
125		return nil, errInvalidHMACKeyFormat
126	}
127	if err := km.validateKeyFormat(keyFormat); err != nil {
128		return nil, fmt.Errorf("hmac_key_manager: invalid key format: %v", err)
129	}
130	if err := keyset.ValidateKeyVersion(keyFormat.GetVersion(), hmacKeyVersion); err != nil {
131		return nil, fmt.Errorf("hmac_key_manager: invalid key version: %s", err)
132	}
133
134	keyValue := make([]byte, keyFormat.GetKeySize())
135	if _, err := io.ReadFull(pseudorandomness, keyValue); err != nil {
136		return nil, fmt.Errorf("hmac_key_manager: not enough pseudorandomness given")
137	}
138	return &hmacpb.HmacKey{
139		Version:  hmacKeyVersion,
140		Params:   keyFormat.Params,
141		KeyValue: keyValue,
142	}, nil
143}
144
145// validateKey validates the given HMACKey. It only validates the version of the
146// key because other parameters will be validated in primitive construction.
147func (km *hmacKeyManager) validateKey(key *hmacpb.HmacKey) error {
148	err := keyset.ValidateKeyVersion(key.Version, hmacKeyVersion)
149	if err != nil {
150		return fmt.Errorf("hmac_key_manager: invalid version: %s", err)
151	}
152	keySize := uint32(len(key.KeyValue))
153	hash := commonpb.HashType_name[int32(key.Params.Hash)]
154	return subtle.ValidateHMACParams(hash, keySize, key.Params.TagSize)
155}
156
157// validateKeyFormat validates the given HMACKeyFormat
158func (km *hmacKeyManager) validateKeyFormat(format *hmacpb.HmacKeyFormat) error {
159	if format.Params == nil {
160		return fmt.Errorf("null HMAC params")
161	}
162	hash := commonpb.HashType_name[int32(format.Params.Hash)]
163	return subtle.ValidateHMACParams(hash, format.KeySize, format.Params.TagSize)
164}
165