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 streamingprf 18 19import ( 20 "errors" 21 "fmt" 22 "io" 23 24 "github.com/google/tink/go/core/primitiveset" 25 "github.com/google/tink/go/keyset" 26 tinkpb "github.com/google/tink/go/proto/tink_go_proto" 27) 28 29// New generates a new instance of the Streaming PRF primitive. 30func New(h *keyset.Handle) (StreamingPRF, error) { 31 if h == nil { 32 return nil, errors.New("keyset handle can't be nil") 33 } 34 ps, err := h.PrimitivesWithKeyManager(new(HKDFStreamingPRFKeyManager)) 35 if err != nil { 36 return nil, fmt.Errorf("streaming_prf_factory: cannot obtain primitive set: %v", err) 37 } 38 return newWrappedStreamingPRF(ps) 39} 40 41// wrappedStreamingPRF is a Streaming PRF implementation that uses the underlying primitive set for Streaming PRF. 42type wrappedStreamingPRF struct { 43 ps *primitiveset.PrimitiveSet 44} 45 46// Asserts that wrappedStreamingPRF implements the StreamingPRF interface. 47var _ StreamingPRF = (*wrappedStreamingPRF)(nil) 48 49func newWrappedStreamingPRF(ps *primitiveset.PrimitiveSet) (*wrappedStreamingPRF, error) { 50 if rawEntries, err := ps.RawEntries(); err != nil || len(rawEntries) != 1 { 51 return nil, errors.New("streaming_prf_factory: only accepts keysets with 1 RAW key") 52 } 53 // ps.Entries is a map of prefix type -> []*Entry. 54 if len(ps.Entries) != 1 { 55 return nil, errors.New("streaming_prf_factory: only accepts keys with prefix type RAW") 56 } 57 if _, ok := (ps.Primary.Primitive).(StreamingPRF); !ok { 58 return nil, errors.New("streaming_prf_factory: not a Streaming PRF primitive") 59 } 60 if ps.Primary.PrefixType != tinkpb.OutputPrefixType_RAW { 61 return nil, errors.New("streaming_prf_factory: primary key prefix type is not RAW") 62 } 63 if ps.Primary.Status != tinkpb.KeyStatusType_ENABLED { 64 return nil, errors.New("streaming_prf_factory: primary key is not ENABLED") 65 } 66 return &wrappedStreamingPRF{ps: ps}, nil 67} 68 69func (w *wrappedStreamingPRF) Compute(input []byte) (io.Reader, error) { 70 primary := w.ps.Primary 71 p, ok := (primary.Primitive).(StreamingPRF) 72 if !ok { 73 return nil, errors.New("streaming_prf_factory: not a Streaming PRF primitive") 74 } 75 return p.Compute(input) 76} 77