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 "third_party/modp_b64/modp_b64.h" 10 #include "util/osp_logging.h" 11 #include "util/std_util.h" 12 13 namespace openscreen { 14 namespace base64 { 15 Encode(absl::Span<const uint8_t> input)16std::string Encode(absl::Span<const uint8_t> input) { 17 return Encode(absl::string_view(reinterpret_cast<const char*>(input.data()), 18 input.size())); 19 } 20 Encode(absl::string_view input)21std::string Encode(absl::string_view input) { 22 std::string out; 23 out.resize(modp_b64_encode_len(input.size())); 24 25 const size_t output_size = 26 modp_b64_encode(data(out), input.data(), input.size()); 27 if (output_size == MODP_B64_ERROR) { 28 return {}; 29 } 30 31 // The encode_len is generally larger than needed. 32 out.resize(output_size); 33 return out; 34 } 35 Decode(absl::string_view input,std::string * output)36bool Decode(absl::string_view input, std::string* output) { 37 std::string out; 38 out.resize(modp_b64_decode_len(input.size())); 39 40 // We don't null terminate the result since it is binary data. 41 const size_t output_size = 42 modp_b64_decode(data(out), input.data(), input.size()); 43 if (output_size == MODP_B64_ERROR) { 44 return false; 45 } 46 47 // The output size from decode_len is generally larger than needed. 48 out.resize(output_size); 49 output->swap(out); 50 return true; 51 } 52 53 } // namespace base64 54 } // namespace openscreen 55