xref: /aosp_15_r20/external/tink/cc/daead/subtle/aead_or_daead.h (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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 #ifndef TINK_DAEAD_SUBTLE_AEAD_OR_DAEAD_H_
18 #define TINK_DAEAD_SUBTLE_AEAD_OR_DAEAD_H_
19 
20 #include <memory>
21 #include <string>
22 #include <utility>
23 
24 #include "absl/types/variant.h"
25 #include "tink/aead.h"
26 #include "tink/deterministic_aead.h"
27 
28 namespace crypto {
29 namespace tink {
30 namespace subtle {
31 
32 // This wrapper class abstracts away the differences between Deterministic Aead
33 // and non-determinstic Aead primitives. This can be useful for building
34 // higher-level functionality in which either of these primitives can be used.
35 class AeadOrDaead {
36  public:
AeadOrDaead(std::unique_ptr<Aead> aead_primitive)37   explicit AeadOrDaead(std::unique_ptr<Aead> aead_primitive)
38       : primitive_variant_(std::move(aead_primitive)) {}
39 
AeadOrDaead(std::unique_ptr<DeterministicAead> deterministic_aead_primitive)40   explicit AeadOrDaead(
41       std::unique_ptr<DeterministicAead> deterministic_aead_primitive)
42       : primitive_variant_(std::move(deterministic_aead_primitive)) {}
43 
44   // Encrypts 'plaintext' using the underlying aead or determnistic aead
45   // primitive, and returns the resulting ciphertext.
46   crypto::tink::util::StatusOr<std::string> Encrypt(
47       absl::string_view plaintext, absl::string_view associated_data) const;
48 
49   // Decrypts 'ciphertext' using the underlying aead or determnistic aead
50   // primitive, and returns the resulting plaintext.
51   crypto::tink::util::StatusOr<std::string> Decrypt(
52       absl::string_view ciphertext, absl::string_view associated_data) const;
53 
54  private:
55   absl::variant<std::unique_ptr<const Aead>,
56                 std::unique_ptr<const DeterministicAead>>
57       primitive_variant_;
58 };
59 
60 }  // namespace subtle
61 }  // namespace tink
62 }  // namespace crypto
63 
64 #endif  // TINK_DAEAD_SUBTLE_AEAD_OR_DAEAD_H_
65