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 prf 18 19import ( 20 "fmt" 21 22 "github.com/google/tink/go/core/primitiveset" 23 "github.com/google/tink/go/internal/internalregistry" 24 "github.com/google/tink/go/internal/monitoringutil" 25 "github.com/google/tink/go/keyset" 26 "github.com/google/tink/go/monitoring" 27) 28 29// NewPRFSet creates a prf.Set primitive from the given keyset handle. 30func NewPRFSet(handle *keyset.Handle) (*Set, error) { 31 ps, err := handle.Primitives() 32 if err != nil { 33 return nil, fmt.Errorf("prf_set_factory: cannot obtain primitive set: %s", err) 34 } 35 return wrapPRFset(ps) 36} 37 38func wrapPRFset(ps *primitiveset.PrimitiveSet) (*Set, error) { 39 set := &Set{} 40 if _, ok := (ps.Primary.Primitive).(PRF); !ok { 41 return nil, fmt.Errorf("prf_set_factory: not a PRF primitive") 42 } 43 set.PrimaryID = ps.Primary.KeyID 44 set.PRFs = make(map[uint32]PRF) 45 logger, err := createLogger(ps) 46 if err != nil { 47 return nil, err 48 } 49 entries, err := ps.RawEntries() 50 if err != nil { 51 return nil, fmt.Errorf("Could not get raw entries: %v", err) 52 } 53 if len(entries) == 0 { 54 return nil, fmt.Errorf("Did not find any raw entries") 55 } 56 if len(ps.Entries) != 1 { 57 return nil, fmt.Errorf("Only raw entries allowed for prf.Set") 58 } 59 for _, entry := range entries { 60 prf, ok := (entry.Primitive).(PRF) 61 if !ok { 62 return nil, fmt.Errorf("prf_set_factory: not a PRF primitive") 63 } 64 set.PRFs[entry.KeyID] = &monitoredPRF{ 65 prf: prf, 66 keyID: entry.KeyID, 67 logger: logger, 68 } 69 } 70 return set, nil 71} 72 73func createLogger(ps *primitiveset.PrimitiveSet) (monitoring.Logger, error) { 74 if len(ps.Annotations) == 0 { 75 return &monitoringutil.DoNothingLogger{}, nil 76 } 77 keysetInfo, err := monitoringutil.KeysetInfoFromPrimitiveSet(ps) 78 if err != nil { 79 return nil, err 80 } 81 return internalregistry.GetMonitoringClient().NewLogger(&monitoring.Context{ 82 KeysetInfo: keysetInfo, 83 Primitive: "prf", 84 APIFunction: "compute", 85 }) 86} 87