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 <openssl/base64.h>
20
21 namespace cuttlefish {
22
EncodeBase64(const void * data,size_t size,std::string * out)23 bool EncodeBase64(const void *data, size_t size, std::string *out) {
24 size_t enc_len = 0;
25 auto len_res = EVP_EncodedLength(&enc_len, size);
26 if (!len_res) {
27 return false;
28 }
29 out->resize(enc_len);
30 auto enc_res = EVP_EncodeBlock(reinterpret_cast<uint8_t *>(out->data()),
31 reinterpret_cast<const uint8_t *>(data), size);
32 if (enc_res < 0) {
33 return false;
34 }
35 out->resize(enc_res); // Don't count the terminating \0 character
36 return true;
37 }
38
DecodeBase64(const std::string & data,std::vector<uint8_t> * buffer)39 bool DecodeBase64(const std::string &data, std::vector<uint8_t> *buffer) {
40 size_t out_len;
41 auto len_res = EVP_DecodedLength(&out_len, data.size());
42 if (!len_res) {
43 return false;
44 }
45 buffer->resize(out_len);
46 return EVP_DecodeBase64(buffer->data(), &out_len, out_len,
47 reinterpret_cast<const uint8_t *>(data.data()),
48 data.size());
49 }
50
51 } // namespace cuttlefish
52