xref: /aosp_15_r20/external/tink/cc/aead/internal/aead_from_zero_copy.cc (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2021 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 #include "tink/aead/internal/aead_from_zero_copy.h"
17 
18 #include <string>
19 
20 #include "absl/memory/memory.h"
21 #include "tink/aead/internal/zero_copy_aead.h"
22 #include "tink/subtle/subtle_util.h"
23 #include "tink/util/statusor.h"
24 
25 namespace crypto {
26 namespace tink {
27 namespace internal {
28 
Encrypt(absl::string_view plaintext,absl::string_view associated_data) const29 util::StatusOr<std::string> AeadFromZeroCopy::Encrypt(
30     absl::string_view plaintext, absl::string_view associated_data) const {
31   std::string result;
32   subtle::ResizeStringUninitialized(&result,
33                                     aead_->MaxEncryptionSize(plaintext.size()));
34   util::StatusOr<uint64_t> written_bytes = aead_->Encrypt(
35       plaintext, associated_data, absl::MakeSpan(&result[0], result.size()));
36   if (!written_bytes.ok()) {
37     return written_bytes.status();
38   }
39   result.resize(*written_bytes);
40   return result;
41 }
42 
Decrypt(absl::string_view ciphertext,absl::string_view associated_data) const43 util::StatusOr<std::string> AeadFromZeroCopy::Decrypt(
44     absl::string_view ciphertext, absl::string_view associated_data) const {
45   std::string result;
46   subtle::ResizeStringUninitialized(
47       &result, aead_->MaxDecryptionSize(ciphertext.size()));
48   util::StatusOr<uint64_t> bytes_written = aead_->Decrypt(
49       ciphertext, associated_data, absl::MakeSpan(&result[0], result.size()));
50   if (!bytes_written.ok()) {
51     return bytes_written.status();
52   }
53   result.resize(*bytes_written);
54   return result;
55 }
56 
57 }  // namespace internal
58 }  // namespace tink
59 }  // namespace crypto
60