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 hpke 18 19import ( 20 "errors" 21 "fmt" 22 23 "github.com/google/tink/go/tink" 24 pb "github.com/google/tink/go/proto/hpke_go_proto" 25) 26 27// Encrypt for HPKE implements interface HybridEncrypt. 28type Encrypt struct { 29 recipientPubKey *pb.HpkePublicKey 30 kem kem 31 kdf kdf 32 aead aead 33} 34 35var _ tink.HybridEncrypt = (*Encrypt)(nil) 36 37// NewEncrypt constructs an Encrypt using HpkePublicKey. 38func NewEncrypt(recipientPubKey *pb.HpkePublicKey) (*Encrypt, error) { 39 if recipientPubKey.GetPublicKey() == nil || len(recipientPubKey.GetPublicKey()) == 0 { 40 return nil, errors.New("HpkePublicKey.PublicKey bytes are missing") 41 } 42 kem, kdf, aead, err := newPrimitivesFromProto(recipientPubKey.GetParams()) 43 if err != nil { 44 return nil, err 45 } 46 return &Encrypt{recipientPubKey, kem, kdf, aead}, nil 47} 48 49// Encrypt encrypts plaintext, binding contextInfo to the resulting ciphertext. 50func (e *Encrypt) Encrypt(plaintext, contextInfo []byte) ([]byte, error) { 51 ctx, err := newSenderContext(e.recipientPubKey, e.kem, e.kdf, e.aead, contextInfo) 52 if err != nil { 53 return nil, fmt.Errorf("newSenderContext: %v", err) 54 } 55 56 ciphertext, err := ctx.seal(plaintext, emptyAssociatedData) 57 if err != nil { 58 return nil, fmt.Errorf("seal: %v", err) 59 } 60 61 return append(ctx.encapsulatedKey, ciphertext...), nil 62} 63