xref: /aosp_15_r20/external/tink/go/hybrid/internal/hpke/aes_gcm_aead_test.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	"bytes"
21	"fmt"
22	"testing"
23)
24
25func TestAESGCMAEADSealOpen(t *testing.T) {
26	i := 0
27	vecs := aeadRFCVectors(t)
28	for k, v := range vecs {
29		if k.aeadID != aes128GCM && k.aeadID != aes256GCM {
30			continue
31		}
32
33		i++
34		t.Run(fmt.Sprintf("%d", k.id), func(t *testing.T) {
35			{
36				aead, err := newAEAD(k.aeadID)
37				if err != nil {
38					t.Fatalf("newAEAD(%d): got err %q, want success", k.aeadID, err)
39				}
40
41				ciphertext, err := aead.seal(v.key, v.nonce, v.plaintext, v.associatedData)
42				if err != nil {
43					t.Fatalf("seal: got err %q, want success", err)
44				}
45				if !bytes.Equal(ciphertext, v.ciphertext) {
46					t.Errorf("seal: got %x, want %x", ciphertext, v.ciphertext)
47				}
48
49				plaintext, err := aead.open(v.key, v.nonce, v.ciphertext, v.associatedData)
50				if err != nil {
51					t.Fatalf("open: got err %q, want success", err)
52				}
53				if !bytes.Equal(plaintext, v.plaintext) {
54					t.Errorf("open: got %x, want %x", plaintext, v.plaintext)
55				}
56			}
57
58			// Test exactly as above, except instantiate aesGcmHpkeAead with a key
59			// length that does not match the length of the key passed into seal and
60			// open.
61			{
62				var wrongID uint16
63				switch k.aeadID {
64				case aes128GCM:
65					wrongID = aes256GCM
66				case aes256GCM:
67					wrongID = aes128GCM
68				default:
69					t.Fatalf("AEAD ID %d is not supported", k.aeadID)
70				}
71				aead, err := newAEAD(wrongID)
72				if err != nil {
73					t.Fatalf("newAEAD(%d): got err %q, want success", wrongID, err)
74				}
75
76				if _, err := aead.seal(v.key, v.nonce, v.plaintext, v.associatedData); err == nil {
77					t.Error("seal with unexpected key length: got success, want err")
78				}
79				if _, err := aead.open(v.key, v.nonce, v.ciphertext, v.associatedData); err == nil {
80					t.Error("open with unexpected key length: got success, want err")
81				}
82			}
83		})
84	}
85	if i < 2 {
86		t.Errorf("number of vectors tested = %d, want > %d", i, 2)
87	}
88}
89