xref: /aosp_15_r20/external/tink/cc/examples/walkthrough/create_keyset_test.cc (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 
17 #include "walkthrough/create_keyset.h"
18 
19 #include <memory>
20 #include <string>
21 
22 #include "gmock/gmock.h"
23 #include "absl/strings/string_view.h"
24 #include "tink/aead.h"
25 #include "tink/aead/aead_config.h"
26 #include "tink/registry.h"
27 #include "tink/util/statusor.h"
28 #include "tink/util/test_matchers.h"
29 
30 namespace tink_walkthrough {
31 namespace {
32 
33 using ::crypto::tink::test::IsOk;
34 using ::crypto::tink::test::IsOkAndHolds;
35 using ::crypto::tink::util::StatusOr;
36 using ::testing::Not;
37 using ::testing::Test;
38 
39 class CreateAead128GcmKeysetTest : public Test {
40  public:
TearDown()41   void TearDown() override { crypto::tink::Registry::Reset(); }
42 };
43 
TEST_F(CreateAead128GcmKeysetTest,CreateAead128GcmKeysetFailsIfAeadNotRegistered)44 TEST_F(CreateAead128GcmKeysetTest,
45        CreateAead128GcmKeysetFailsIfAeadNotRegistered) {
46   EXPECT_THAT(CreateAead128GcmKeyset(), Not(IsOk()));
47 }
48 
TEST_F(CreateAead128GcmKeysetTest,CreateAead128GcmKeysetSucceeds)49 TEST_F(CreateAead128GcmKeysetTest, CreateAead128GcmKeysetSucceeds) {
50   ASSERT_THAT(crypto::tink::AeadConfig::Register(), IsOk());
51   StatusOr<std::unique_ptr<crypto::tink::KeysetHandle>> keyset_handle =
52       CreateAead128GcmKeyset();
53   ASSERT_THAT(keyset_handle, IsOk());
54   constexpr absl::string_view plaintext = "Some plaintext";
55   constexpr absl::string_view associated_data = "Some associated_data";
56   StatusOr<std::unique_ptr<crypto::tink::Aead>> aead =
57       (*keyset_handle)->GetPrimitive<crypto::tink::Aead>();
58   ASSERT_THAT(aead, IsOk());
59   StatusOr<std::string> ciphertext =
60       (*aead)->Encrypt(plaintext, associated_data);
61   ASSERT_THAT(ciphertext, IsOk());
62   EXPECT_THAT((*aead)->Decrypt(*ciphertext, associated_data),
63               IsOkAndHolds(plaintext));
64 }
65 
66 }  // namespace
67 }  // namespace tink_walkthrough
68