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 hybrid 18 19import ( 20 "errors" 21 22 "google.golang.org/protobuf/proto" 23 "github.com/google/tink/go/core/registry" 24 "github.com/google/tink/go/hybrid/internal/hpke" 25 "github.com/google/tink/go/keyset" 26 hpkepb "github.com/google/tink/go/proto/hpke_go_proto" 27 tinkpb "github.com/google/tink/go/proto/tink_go_proto" 28) 29 30const ( 31 // maxSupportedHPKEPublicKeyVersion is the max supported public key version. 32 // It must be incremented when support for new versions are implemented. 33 maxSupportedHPKEPublicKeyVersion = 0 34 hpkePublicKeyTypeURL = "type.googleapis.com/google.crypto.tink.HpkePublicKey" 35) 36 37var ( 38 errInvalidHPKEPublicKey = errors.New("invalid HPKE public key") 39 errNotSupportedOnHPKE = errors.New("not supported on HPKE public key manager") 40) 41 42// hpkePublicKeyManager implements the KeyManager interface for HybridEncrypt. 43type hpkePublicKeyManager struct{} 44 45var _ registry.KeyManager = (*hpkePublicKeyManager)(nil) 46 47func (p *hpkePublicKeyManager) Primitive(serializedKey []byte) (interface{}, error) { 48 if len(serializedKey) == 0 { 49 return nil, errInvalidHPKEPublicKey 50 } 51 key := new(hpkepb.HpkePublicKey) 52 if err := proto.Unmarshal(serializedKey, key); err != nil { 53 return nil, errInvalidHPKEPublicKey 54 } 55 if err := keyset.ValidateKeyVersion(key.GetVersion(), maxSupportedHPKEPublicKeyVersion); err != nil { 56 return nil, err 57 } 58 return hpke.NewEncrypt(key) 59} 60 61func (p *hpkePublicKeyManager) DoesSupport(typeURL string) bool { 62 return typeURL == hpkePublicKeyTypeURL 63} 64 65func (p *hpkePublicKeyManager) TypeURL() string { 66 return hpkePublicKeyTypeURL 67} 68 69func (p *hpkePublicKeyManager) NewKey(serializedKeyFormat []byte) (proto.Message, error) { 70 return nil, errNotSupportedOnHPKE 71} 72 73func (p *hpkePublicKeyManager) NewKeyData(serializedKeyFormat []byte) (*tinkpb.KeyData, error) { 74 return nil, errNotSupportedOnHPKE 75} 76