• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 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 "tink/daead/subtle/aead_or_daead.h"
18 
19 #include <memory>
20 #include <string>
21 #include <utility>
22 
23 #include "gmock/gmock.h"
24 #include "gtest/gtest.h"
25 #include "tink/util/test_matchers.h"
26 #include "tink/util/test_util.h"
27 
28 namespace crypto {
29 namespace tink {
30 namespace subtle {
31 namespace {
32 
33 using ::crypto::tink::test::IsOk;
34 using ::crypto::tink::util::StatusOr;
35 
36 // Checks whether Decrypt(Encrypt(message)) == message with the given
37 // aead_or_daead.
EncryptThenDecrypt(const AeadOrDaead & aead_or_daead,absl::string_view message,absl::string_view associated_data)38 crypto::tink::util::Status EncryptThenDecrypt(
39     const AeadOrDaead& aead_or_daead, absl::string_view message,
40     absl::string_view associated_data) {
41   StatusOr<std::string> encryption_or =
42       aead_or_daead.Encrypt(message, associated_data);
43   if (!encryption_or.status().ok()) return encryption_or.status();
44   StatusOr<std::string> decryption_or =
45       aead_or_daead.Decrypt(encryption_or.value(), associated_data);
46   if (!decryption_or.status().ok()) return decryption_or.status();
47   if (decryption_or.value() != message) {
48     return crypto::tink::util::Status(absl::StatusCode::kInternal,
49                                       "Message/Decryption mismatch");
50   }
51   return util::OkStatus();
52 }
53 
TEST(AeadOrDaead,testWithAeadPrimitive)54 TEST(AeadOrDaead, testWithAeadPrimitive) {
55   std::unique_ptr<Aead> aead = absl::make_unique<test::DummyAead>("TestAead");
56   AeadOrDaead aead_or_daead(std::move(aead));
57 
58   EXPECT_THAT(EncryptThenDecrypt(aead_or_daead, "test_plaintext", "aad"),
59               IsOk());
60 }
61 
TEST(AeadOrDaead,testWithDeterministicAeadPrimitive)62 TEST(AeadOrDaead, testWithDeterministicAeadPrimitive) {
63   std::unique_ptr<DeterministicAead> daead =
64       absl::make_unique<test::DummyDeterministicAead>("TestDaead");
65   AeadOrDaead aead_or_daead(std::move(daead));
66 
67   EXPECT_THAT(EncryptThenDecrypt(aead_or_daead, "test_plaintext", "aad"),
68               IsOk());
69 }
70 
71 }  // namespace
72 }  // namespace subtle
73 }  // namespace tink
74 }  // namespace crypto
75