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/obtain_and_use_a_primitive.h"
18
19 #include <memory>
20 #include <ostream>
21 #include <string>
22 #include <utility>
23
24 #include "gmock/gmock.h"
25 #include "absl/strings/string_view.h"
26 #include "tink/aead/aead_config.h"
27 #include "walkthrough/load_cleartext_keyset.h"
28 #include "tink/util/statusor.h"
29 #include "tink/util/test_matchers.h"
30
31 namespace tink_walkthrough {
32 namespace {
33
34 constexpr absl::string_view kSerializedKeyset = R"string({
35 "key": [
36 {
37 "keyData": {
38 "keyMaterialType": "SYMMETRIC",
39 "typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
40 "value": "GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
41 },
42 "keyId": 294406504,
43 "outputPrefixType": "TINK",
44 "status": "ENABLED"
45 }
46 ],
47 "primaryKeyId": 294406504
48 })string";
49
50 using ::crypto::tink::KeysetHandle;
51 using ::crypto::tink::test::IsOk;
52 using ::crypto::tink::test::IsOkAndHolds;
53 using ::crypto::tink::util::StatusOr;
54
TEST(LoadKeysetTest,EncryptDecrypt)55 TEST(LoadKeysetTest, EncryptDecrypt) {
56 ASSERT_THAT(crypto::tink::AeadConfig::Register(), IsOk());
57 StatusOr<std::unique_ptr<KeysetHandle>> master_key_keyset =
58 LoadKeyset(kSerializedKeyset);
59 ASSERT_THAT(master_key_keyset, IsOk());
60 constexpr absl::string_view kPlaintext = "Some data";
61 constexpr absl::string_view kAssociatedData = "Some associated data";
62 StatusOr<std::string> ciphertext =
63 AeadEncrypt(**master_key_keyset, kPlaintext, kAssociatedData);
64 ASSERT_THAT(ciphertext, IsOk());
65 EXPECT_THAT(AeadDecrypt(**master_key_keyset, *ciphertext, kAssociatedData),
66 IsOkAndHolds(kPlaintext));
67 }
68
69 } // namespace
70 } // namespace tink_walkthrough
71