xref: /aosp_15_r20/external/openscreen/util/base64.cc (revision 3f982cf4871df8771c9d4abe6e9a6f8d829b2736)
1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "util/base64.h"
6 
7 #include <stddef.h>
8 
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 #include "third_party/modp_b64/modp_b64.h"
14 #include "util/osp_logging.h"
15 #include "util/std_util.h"
16 
17 namespace openscreen {
18 namespace base64 {
19 
Encode(absl::Span<const uint8_t> input)20 std::string Encode(absl::Span<const uint8_t> input) {
21   return Encode(absl::string_view(reinterpret_cast<const char*>(input.data()),
22                                   input.size()));
23 }
24 
Encode(absl::string_view input)25 std::string Encode(absl::string_view input) {
26   std::string out;
27   out.resize(modp_b64_encode_len(input.size()));
28 
29   const size_t output_size =
30       modp_b64_encode(data(out), input.data(), input.size());
31   if (output_size == MODP_B64_ERROR) {
32     return {};
33   }
34 
35   // The encode_len is generally larger than needed.
36   out.resize(output_size);
37   return out;
38 }
39 
Decode(absl::string_view input,std::vector<uint8_t> * output)40 bool Decode(absl::string_view input, std::vector<uint8_t>* output) {
41   std::vector<uint8_t> out(modp_b64_decode_len(input.size()));
42 
43   const size_t output_size = modp_b64_decode(
44       reinterpret_cast<char*>(out.data()), input.data(), input.size());
45   if (output_size == MODP_B64_ERROR) {
46     return false;
47   }
48 
49   // The output size from decode_len is generally larger than needed.
50   out.resize(output_size);
51   *output = std::move(out);
52   return true;
53 }
54 
55 }  // namespace base64
56 }  // namespace openscreen
57