File: aead_factory.go

package info (click to toggle)
golang-github-tink-crypto-tink-go 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,952 kB
  • sloc: sh: 864; makefile: 6
file content (205 lines) | stat: -rw-r--r-- 6,485 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package aead

import (
	"fmt"
	"slices"

	"github.com/tink-crypto/tink-go/v2/core/cryptofmt"
	"github.com/tink-crypto/tink-go/v2/internal/internalapi"
	"github.com/tink-crypto/tink-go/v2/internal/internalregistry"
	"github.com/tink-crypto/tink-go/v2/internal/monitoringutil"
	"github.com/tink-crypto/tink-go/v2/internal/primitiveset"
	"github.com/tink-crypto/tink-go/v2/keyset"
	"github.com/tink-crypto/tink-go/v2/monitoring"
	"github.com/tink-crypto/tink-go/v2/tink"
)

// New returns an AEAD primitive from the given keyset handle.
func New(handle *keyset.Handle) (tink.AEAD, error) {
	ps, err := keyset.Primitives[tink.AEAD](handle, internalapi.Token{})
	if err != nil {
		return nil, fmt.Errorf("aead_factory: cannot obtain primitive set: %s", err)
	}
	return newWrappedAead(ps)
}

// NewWithConfig creates an AEAD primitive from the given [keyset.Handle] using
// the provided [Config].
func NewWithConfig(handle *keyset.Handle, config keyset.Config) (tink.AEAD, error) {
	ps, err := keyset.Primitives[tink.AEAD](handle, internalapi.Token{}, keyset.WithConfig(config))
	if err != nil {
		return nil, fmt.Errorf("aead_factory: cannot obtain primitive set with config: %s", err)
	}
	return newWrappedAead(ps)
}

// wrappedAead is an AEAD implementation that uses the underlying primitive set for encryption
// and decryption.
type wrappedAead struct {
	primary    aeadAndKeyID
	primitives map[string][]aeadAndKeyID

	encLogger monitoring.Logger
	decLogger monitoring.Logger
}

type aeadAndKeyID struct {
	primitive tink.AEAD
	keyID     uint32
}

func (a *aeadAndKeyID) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
	return a.primitive.Encrypt(plaintext, associatedData)
}

func (a *aeadAndKeyID) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
	return a.primitive.Decrypt(ciphertext, associatedData)
}

// aeadPrimitiveAdapter is an adapter that turns a non-full [tink.AEAD]
// primitive into a full [tink.AEAD] primitive.
type fullAEADPrimitiveAdapter struct {
	primitive tink.AEAD
	prefix    []byte
}

func (a *fullAEADPrimitiveAdapter) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
	ct, err := a.primitive.Encrypt(plaintext, associatedData)
	if err != nil {
		return nil, err
	}
	return slices.Concat(a.prefix, ct), nil
}

func (a *fullAEADPrimitiveAdapter) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
	return a.primitive.Decrypt(ciphertext[len(a.prefix):], associatedData)
}

// extractFullAEAD returns a full aeadAndKeyID primitive from the given
// [primitiveset.Entry[tink.AEAD]].
func extractFullAEAD(entry *primitiveset.Entry[tink.AEAD]) (*aeadAndKeyID, error) {
	if entry.FullPrimitive != nil {
		return &aeadAndKeyID{primitive: entry.FullPrimitive, keyID: entry.KeyID}, nil
	}
	return &aeadAndKeyID{
		primitive: &fullAEADPrimitiveAdapter{primitive: entry.Primitive, prefix: []byte(entry.Prefix)},
		keyID:     entry.KeyID,
	}, nil
}

func newWrappedAead(ps *primitiveset.PrimitiveSet[tink.AEAD]) (*wrappedAead, error) {
	primary, err := extractFullAEAD(ps.Primary)
	if err != nil {
		return nil, err
	}
	primitives := make(map[string][]aeadAndKeyID)
	for _, entries := range ps.Entries {
		for _, entry := range entries {
			p, err := extractFullAEAD(entry)
			if err != nil {
				return nil, err
			}
			primitives[entry.Prefix] = append(primitives[entry.Prefix], *p)
		}
	}
	encLogger, decLogger, err := createLoggers(ps)
	if err != nil {
		return nil, err
	}
	return &wrappedAead{
		primary:    *primary,
		primitives: primitives,
		encLogger:  encLogger,
		decLogger:  decLogger,
	}, nil
}

func createLoggers(ps *primitiveset.PrimitiveSet[tink.AEAD]) (monitoring.Logger, monitoring.Logger, error) {
	if len(ps.Annotations) == 0 {
		return &monitoringutil.DoNothingLogger{}, &monitoringutil.DoNothingLogger{}, nil
	}
	client := internalregistry.GetMonitoringClient()
	keysetInfo, err := monitoringutil.KeysetInfoFromPrimitiveSet(ps)
	if err != nil {
		return nil, nil, err
	}
	encLogger, err := client.NewLogger(&monitoring.Context{
		Primitive:   "aead",
		APIFunction: "encrypt",
		KeysetInfo:  keysetInfo,
	})
	if err != nil {
		return nil, nil, err
	}
	decLogger, err := client.NewLogger(&monitoring.Context{
		Primitive:   "aead",
		APIFunction: "decrypt",
		KeysetInfo:  keysetInfo,
	})
	if err != nil {
		return nil, nil, err
	}
	return encLogger, decLogger, nil
}

// Encrypt encrypts the given plaintext with the given associatedData.
// It returns the concatenation of the primary's identifier and the ciphertext.
func (a *wrappedAead) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
	ct, err := a.primary.Encrypt(plaintext, associatedData)
	if err != nil {
		a.encLogger.LogFailure()
		return nil, err
	}
	a.encLogger.Log(a.primary.keyID, len(plaintext))
	return ct, nil
}

// Decrypt decrypts the given ciphertext and authenticates it with the given
// associatedData. It returns the corresponding plaintext if the
// ciphertext is authenticated.
func (a *wrappedAead) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
	// Try non-raw keys.
	prefixSize := cryptofmt.NonRawPrefixSize
	if len(ciphertext) > prefixSize {
		prefix := ciphertext[:prefixSize]
		primitivesForPrefix, ok := a.primitives[string(prefix)]
		if ok {
			for _, primitive := range primitivesForPrefix {
				pt, err := primitive.Decrypt(ciphertext, associatedData)
				if err == nil {
					numBytes := len(ciphertext[prefixSize:])
					a.decLogger.Log(primitive.keyID, numBytes)
					return pt, nil
				}
			}
		}
	}
	// Try raw keys.
	rawPrimitives, ok := a.primitives[cryptofmt.RawPrefix]
	if ok {
		for _, primitive := range rawPrimitives {
			pt, err := primitive.Decrypt(ciphertext, associatedData)
			if err == nil {
				a.decLogger.Log(primitive.keyID, len(ciphertext))
				return pt, nil
			}
		}
	}
	// Nothing worked.
	a.decLogger.LogFailure()
	return nil, fmt.Errorf("aead_factory: decryption failed")
}