xref: /aosp_15_r20/external/tink/go/hybrid/internal/hpke/chacha20poly1305_aead.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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	"fmt"
21
22	"golang.org/x/crypto/chacha20poly1305"
23	internalaead "github.com/google/tink/go/internal/aead"
24)
25
26// chaCha20Poly1305AEAD is a ChaCha20-Poly1305 HPKE AEAD variant that
27// implements interface aead.
28type chaCha20Poly1305AEAD struct{}
29
30var _ aead = (*chaCha20Poly1305AEAD)(nil)
31
32func (c *chaCha20Poly1305AEAD) seal(key, nonce, plaintext, associatedData []byte) ([]byte, error) {
33	if len(key) != chacha20poly1305.KeySize {
34		return nil, fmt.Errorf("unexpected key length: got %d, want %d", len(key), chacha20poly1305.KeySize)
35	}
36	cc, err := internalaead.NewChaCha20Poly1305InsecureNonce(key)
37	if err != nil {
38		return nil, fmt.Errorf("NewChaCha20Poly1305InsecureNonce: %v", err)
39	}
40	return cc.Encrypt(nonce, plaintext, associatedData)
41}
42
43func (c *chaCha20Poly1305AEAD) open(key, nonce, ciphertext, associatedData []byte) ([]byte, error) {
44	if len(key) != chacha20poly1305.KeySize {
45		return nil, fmt.Errorf("unexpected key length: got %d, want %d", len(key), chacha20poly1305.KeySize)
46	}
47	cc, err := internalaead.NewChaCha20Poly1305InsecureNonce(key)
48	if err != nil {
49		return nil, fmt.Errorf("NewChaCha20Poly1305InsecureNonce: %v", err)
50	}
51	return cc.Decrypt(nonce, ciphertext, associatedData)
52}
53
54func (c *chaCha20Poly1305AEAD) id() uint16 {
55	return chaCha20Poly1305
56}
57
58func (c *chaCha20Poly1305AEAD) keyLength() int {
59	return chacha20poly1305.KeySize
60}
61
62func (c *chaCha20Poly1305AEAD) nonceLength() int {
63	return chacha20poly1305.NonceSize
64}
65