2 * Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <symbol-visibility.h>
24 int base64EncodeGenericImpl(const void* input, size_t inputLen, void* output);
27 int base64DecodeGenericImpl(const void* input, size_t inputLen, void* output, size_t outputLen);
29 template <typename Output, typename Input>
30 Output base64EncodeGeneric(const Input& input)
32 // For each 3 input bytes (rounded up), 4 encoded bytes and a null terminator.
33 Output output((input.size() + 2) / 3 * 4 + 1, '\0');
35 static_assert(sizeof(input[0]) == 1);
36 static_assert(sizeof(output[0]) == 1);
37 int length = base64EncodeGenericImpl(input.data(), input.size(), &output[0]);
39 output.resize(length);
43 // Due to backwards compatibility, this function contains a few quirks. All '\n' newlines will be
44 // removed, other non-base64 characters will throw an exception, and base64 must be implemented
45 // using the OpenSSL BIO API. The last fact also implies that this function can accept padding in
46 // the middle of text, or too much padding at the end.
47 template <typename Output, typename Input>
48 Output base64DecodeGeneric(Input input)
50 input.erase(std::remove(input.begin(), input.end(), '\n'), input.end());
52 // For each 4 encoded bytes (rounded up), 3 decoded bytes.
53 Output output((input.size() + 3) / 4 * 3, '\0');
55 static_assert(sizeof(input[0]) == 1);
56 static_assert(sizeof(output[0]) == 1);
57 size_t length = base64DecodeGenericImpl(input.data(), input.size(), &output[0], output.size());
59 output.resize(length);