1// Copyright 2022 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 keyderivation 18 19import ( 20 "fmt" 21 22 "google.golang.org/protobuf/proto" 23 "github.com/google/tink/go/keyset" 24 prfderpb "github.com/google/tink/go/proto/prf_based_deriver_go_proto" 25 tinkpb "github.com/google/tink/go/proto/tink_go_proto" 26) 27 28// CreatePRFBasedKeyTemplate creates a PRF-Based Deriver key template with the 29// specified PRF and derived key templates. If either the PRF or derived key 30// templates are not supported by the registry, an error is returned. 31func CreatePRFBasedKeyTemplate(prfKeyTemplate, derivedKeyTemplate *tinkpb.KeyTemplate) (*tinkpb.KeyTemplate, error) { 32 keyFormat := &prfderpb.PrfBasedDeriverKeyFormat{ 33 PrfKeyTemplate: prfKeyTemplate, 34 Params: &prfderpb.PrfBasedDeriverParams{ 35 DerivedKeyTemplate: derivedKeyTemplate, 36 }, 37 } 38 serializedFormat, err := proto.Marshal(keyFormat) 39 if err != nil { 40 return nil, fmt.Errorf("failed to marshal key format: %s", err) 41 } 42 template := &tinkpb.KeyTemplate{ 43 TypeUrl: prfBasedDeriverTypeURL, 44 OutputPrefixType: derivedKeyTemplate.GetOutputPrefixType(), 45 Value: serializedFormat, 46 } 47 // Verify `template` is derivable. 48 if _, err := keyset.NewHandle(template); err != nil { 49 return nil, err 50 } 51 return template, nil 52} 53