xref: /aosp_15_r20/external/tink/go/prf/subtle/hmac.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2020 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 subtle
18
19import (
20	"crypto/hmac"
21	"fmt"
22	"hash"
23
24	"github.com/google/tink/go/subtle"
25)
26
27const (
28	minHMACKeySizeInBytes = uint32(16)
29)
30
31// HMACPRF is a type that can be used to compute several HMACs with the same key material.
32type HMACPRF struct {
33	h   func() hash.Hash
34	key []byte
35}
36
37// NewHMACPRF creates a new HMACPRF object and initializes it with the correct key material.
38func NewHMACPRF(hashAlg string, key []byte) (*HMACPRF, error) {
39	h := &HMACPRF{}
40	hashFunc := subtle.GetHashFunc(hashAlg)
41	if hashFunc == nil {
42		return nil, fmt.Errorf("hmac: invalid hash algorithm")
43	}
44	h.h = hashFunc
45	h.key = key
46	return h, nil
47}
48
49// ValidateHMACPRFParams validates parameters of HMAC constructor.
50func ValidateHMACPRFParams(hash string, keySize uint32) error {
51	// validate key size
52	if keySize < minHMACKeySizeInBytes {
53		return fmt.Errorf("key too short")
54	}
55	if subtle.GetHashFunc(hash) == nil {
56		return fmt.Errorf("invalid hash function")
57	}
58	return nil
59}
60
61// ComputePRF computes the HMAC for the given key and data, returning outputLength bytes.
62func (h HMACPRF) ComputePRF(data []byte, outputLength uint32) ([]byte, error) {
63	mac := hmac.New(h.h, h.key)
64	if outputLength > uint32(mac.Size()) {
65		return nil, fmt.Errorf("outputLength must be between 0 and %d", mac.Size())
66	}
67	mac.Write(data)
68	return mac.Sum(nil)[:outputLength], nil
69}
70