xref: /aosp_15_r20/external/tink/go/hybrid/hybrid_encrypt_factory.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2019 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	"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	"github.com/google/tink/go/tink"
28)
29
30// NewHybridEncrypt returns an HybridEncrypt primitive from the given keyset handle.
31func NewHybridEncrypt(handle *keyset.Handle) (tink.HybridEncrypt, error) {
32	ps, err := handle.Primitives()
33	if err != nil {
34		return nil, fmt.Errorf("hybrid_factory: cannot obtain primitive set: %s", err)
35	}
36	return newEncryptPrimitiveSet(ps)
37}
38
39// encryptPrimitiveSet is an HybridEncrypt implementation that uses the underlying primitive set for encryption.
40type wrappedHybridEncrypt struct {
41	ps     *primitiveset.PrimitiveSet
42	logger monitoring.Logger
43}
44
45// compile time assertion that wrappedHybridEncrypt implements the HybridEncrypt interface.
46var _ tink.HybridEncrypt = (*wrappedHybridEncrypt)(nil)
47
48func newEncryptPrimitiveSet(ps *primitiveset.PrimitiveSet) (*wrappedHybridEncrypt, error) {
49	if err := isHybridEncrypt(ps.Primary.Primitive); err != nil {
50		return nil, err
51	}
52
53	for _, primitives := range ps.Entries {
54		for _, p := range primitives {
55			if err := isHybridEncrypt(p.Primitive); err != nil {
56				return nil, err
57			}
58		}
59	}
60	logger, err := createEncryptLogger(ps)
61	if err != nil {
62		return nil, err
63	}
64	return &wrappedHybridEncrypt{
65		ps:     ps,
66		logger: logger,
67	}, nil
68}
69
70func createEncryptLogger(ps *primitiveset.PrimitiveSet) (monitoring.Logger, error) {
71	if len(ps.Annotations) == 0 {
72		return &monitoringutil.DoNothingLogger{}, nil
73	}
74	keysetInfo, err := monitoringutil.KeysetInfoFromPrimitiveSet(ps)
75	if err != nil {
76		return nil, err
77	}
78	return internalregistry.GetMonitoringClient().NewLogger(&monitoring.Context{
79		KeysetInfo:  keysetInfo,
80		Primitive:   "hybrid_encrypt",
81		APIFunction: "encrypt",
82	})
83}
84
85// Encrypt encrypts the given plaintext binding contextInfo to the resulting ciphertext.
86// It returns the concatenation of the primary's identifier and the ciphertext.
87func (a *wrappedHybridEncrypt) Encrypt(plaintext, contextInfo []byte) ([]byte, error) {
88	primary := a.ps.Primary
89	p := primary.Primitive.(tink.HybridEncrypt) // verified in newEncryptPrimitiveSet
90
91	ct, err := p.Encrypt(plaintext, contextInfo)
92	if err != nil {
93		a.logger.LogFailure()
94		return nil, err
95	}
96	a.logger.Log(primary.KeyID, len(plaintext))
97	if len(primary.Prefix) == 0 {
98		return ct, nil
99	}
100	output := make([]byte, 0, len(primary.Prefix)+len(ct))
101	output = append(output, primary.Prefix...)
102	output = append(output, ct...)
103	return output, nil
104}
105
106// Asserts `p` implements tink.HybridEncrypt and not tink.AEAD. The latter check
107// is required as implementations of tink.AEAD also satisfy tink.HybridEncrypt.
108func isHybridEncrypt(p any) error {
109	if _, ok := p.(tink.AEAD); ok {
110		return fmt.Errorf("hybrid_factory: tink.AEAD is not tink.HybridEncrypt")
111	}
112	if _, ok := p.(tink.HybridEncrypt); !ok {
113		return fmt.Errorf("hybrid_factory: not tink.HybridEncrypt")
114	}
115	return nil
116}
117