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 <optional>
22 #include <string>
23 #include <vector>
24
25 #include <openssl/evp.h>
26
27 namespace cuttlefish {
28
29 namespace {
30
31 // EVP_EncodedLength is boringssl specific so it can't be used outside of
32 // android.
EncodedLength(size_t len)33 std::optional<size_t> EncodedLength(size_t len) {
34 if (len + 2 < len) {
35 return std::nullopt;
36 }
37 len += 2;
38 len /= 3;
39
40 if (((len << 2) >> 2) != len) {
41 return std::nullopt;
42 }
43 len <<= 2;
44
45 if (len + 1 < len) {
46 return std::nullopt;
47 }
48 len++;
49
50 return {len};
51 }
52
53 // EVP_DecodedLength is boringssl specific so it can't be used outside of
54 // android.
DecodedLength(size_t len)55 std::optional<size_t> DecodedLength(size_t len) {
56 if (len % 4 != 0) {
57 return std::nullopt;
58 }
59
60 return {(len / 4) * 3};
61 }
62
63 } // namespace
64
EncodeBase64(const void * data,std::size_t size,std::string * out)65 bool EncodeBase64(const void *data, std::size_t size, std::string *out) {
66 auto len_res = EncodedLength(size);
67 if (!len_res) {
68 return false;
69 }
70 out->resize(*len_res);
71 auto enc_res =
72 EVP_EncodeBlock(reinterpret_cast<std::uint8_t *>(out->data()),
73 reinterpret_cast<const std::uint8_t *>(data), size);
74 if (enc_res < 0) {
75 return false;
76 }
77 out->resize(enc_res); // Don't count the terminating \0 character
78 return true;
79 }
80
DecodeBase64(const std::string & data,std::vector<std::uint8_t> * buffer)81 bool DecodeBase64(const std::string &data, std::vector<std::uint8_t> *buffer) {
82 auto len_res = DecodedLength(data.size());
83 if (!len_res) {
84 return false;
85 }
86 auto out_len = *len_res;
87 buffer->resize(out_len);
88 auto actual_len = EVP_DecodeBlock(buffer->data(),
89 reinterpret_cast<const uint8_t *>(data.data()),
90 data.size());
91 if (actual_len < 0) {
92 return false;
93 }
94
95 // DecodeBlock leaves null characters at the end of the buffer when the
96 // decoded message is not a multiple of 3.
97 while (!buffer->empty() && buffer->back() == '\0') {
98 buffer->pop_back();
99 }
100
101 return true;
102 }
103
104 } // namespace cuttlefish
105