• 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 max_length = 0;
30   if (EVP_EncodedLength(&max_length, size) == 0) {
31     return false;
32   }
33 
34   out->resize(max_length);
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   buffer->resize(data.size());
47   std::size_t actual_len = 0;
48   int success = EVP_DecodeBase64(buffer->data(), &actual_len, buffer->size(),
49                                  reinterpret_cast<const uint8_t *>(data.data()),
50                                  data.size());
51   if (success != 1) {
52     return false;
53   }
54   buffer->resize(actual_len);
55 
56   return true;
57 }
58 
59 }  // namespace cuttlefish
60