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/load_cleartext_keyset.h"
18
19 #include <memory>
20 #include <string>
21
22 #include "gmock/gmock.h"
23 #include "absl/status/status.h"
24 #include "absl/strings/string_view.h"
25 #include "tink/aead/aead_config.h"
26 #include "tink/util/statusor.h"
27 #include "tink/util/test_matchers.h"
28
29 namespace tink_walkthrough {
30 namespace {
31
32 constexpr absl::string_view kSerializedKeyset = R"json({
33 "key": [
34 {
35 "keyData": {
36 "keyMaterialType": "SYMMETRIC",
37 "typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
38 "value": "GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
39 },
40 "keyId": 294406504,
41 "outputPrefixType": "TINK",
42 "status": "ENABLED"
43 }
44 ],
45 "primaryKeyId": 294406504
46 })json";
47
48 using ::crypto::tink::test::IsOk;
49 using ::crypto::tink::test::IsOkAndHolds;
50 using ::crypto::tink::test::StatusIs;
51 using ::crypto::tink::util::StatusOr;
52
TEST(LoadKeysetTest,LoadKeysetFailsWithInvalidKeyset)53 TEST(LoadKeysetTest, LoadKeysetFailsWithInvalidKeyset) {
54 EXPECT_THAT(LoadKeyset("Invalid").status(),
55 StatusIs(absl::StatusCode::kInvalidArgument));
56 }
57
TEST(LoadKeysetTest,LoadKeysetSucceeds)58 TEST(LoadKeysetTest, LoadKeysetSucceeds) {
59 StatusOr<std::unique_ptr<crypto::tink::KeysetHandle>> keyset_handle =
60 LoadKeyset(kSerializedKeyset);
61 ASSERT_THAT(keyset_handle, IsOk());
62 ASSERT_THAT(crypto::tink::AeadConfig::Register(), IsOk());
63 // Make sure we can extract the Aead primitive and encrypt/decrypt with it.
64 constexpr absl::string_view plaintext = "Some plaintext";
65 constexpr absl::string_view associated_data = "Some associated_data";
66 StatusOr<std::unique_ptr<crypto::tink::Aead>> aead =
67 (*keyset_handle)->GetPrimitive<crypto::tink::Aead>();
68 ASSERT_THAT(aead, IsOk());
69 StatusOr<std::string> ciphertext =
70 (*aead)->Encrypt(plaintext, associated_data);
71 ASSERT_THAT(ciphertext, IsOk());
72 EXPECT_THAT((*aead)->Decrypt(*ciphertext, associated_data),
73 IsOkAndHolds(plaintext));
74 }
75
76 } // namespace
77 } // namespace tink_walkthrough
78