Release 0.1.65
[platform/core/security/key-manager.git] / common / base64_generic.h
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved
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 #pragma once
18
19 #include <algorithm>
20
21 #include <symbol-visibility.h>
22
23 COMMON_API
24 int base64EncodeGenericImpl(const void* input, size_t inputLen, void* output);
25
26 COMMON_API
27 int base64DecodeGenericImpl(const void* input, size_t inputLen, void* output, size_t outputLen);
28
29 template <typename Output, typename Input>
30 Output base64EncodeGeneric(const Input& input)
31 {
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');
34
35         static_assert(sizeof(input[0]) == 1);
36         static_assert(sizeof(output[0]) == 1);
37         int length = base64EncodeGenericImpl(input.data(), input.size(), &output[0]);
38
39         output.resize(length);
40         return output;
41 }
42
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)
49 {
50         input.erase(std::remove(input.begin(), input.end(), '\n'), input.end());
51
52         // For each 4 encoded bytes (rounded up), 3 decoded bytes.
53         Output output((input.size() + 3) / 4 * 3, '\0');
54
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());
58
59         output.resize(length);
60         return output;
61 }