• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "common/libs/utils/base64.h"
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <string>
22 #include <vector>
23 
24 #include <openssl/base64.h>
25 
26 namespace cuttlefish {
27 
EncodeBase64(const void * data,std::size_t size,std::string * out)28 bool EncodeBase64(const void *data, std::size_t size, std::string *out) {
29   std::size_t enc_len = 0;
30   auto len_res = EVP_EncodedLength(&enc_len, size);
31   if (!len_res) {
32     return false;
33   }
34   out->resize(enc_len);
35   auto enc_res =
36       EVP_EncodeBlock(reinterpret_cast<std::uint8_t *>(out->data()),
37                       reinterpret_cast<const std::uint8_t *>(data), size);
38   if (enc_res < 0) {
39     return false;
40   }
41   out->resize(enc_res);  // Don't count the terminating \0 character
42   return true;
43 }
44 
DecodeBase64(const std::string & data,std::vector<std::uint8_t> * buffer)45 bool DecodeBase64(const std::string &data, std::vector<std::uint8_t> *buffer) {
46   std::size_t out_len;
47   auto len_res = EVP_DecodedLength(&out_len, data.size());
48   if (!len_res) {
49     return false;
50   }
51   buffer->resize(out_len);
52   return EVP_DecodeBase64(buffer->data(), &out_len, out_len,
53                           reinterpret_cast<const std::uint8_t *>(data.data()),
54                           data.size());
55 }
56 
57 }  // namespace cuttlefish
58