2 * Samsung Ukraine R&D Center (SRK under a contract between)
3 * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
20 * @brief Base64 encoder/decoder
21 * @date Created Apr 06, 2018
22 * @author Mail to: <A HREF="mailto:d.lomtev@samsung.com">Dmytro Lomtev, d.lomtev@samsung.com</A>
33 string base64_encode(const string& source)
35 static const char list_code[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
39 for (auto it = source.cbegin(); it != source.cend();) {
40 int word = ((int)(unsigned char) * it) << 16;
43 if (++it != source.cend()) {
44 word |= ((int)(unsigned char) * it) << 8;
47 if (++it != source.cend()) {
48 word |= ((int)(unsigned char) * it);
54 for (int i = 0; i < 4; i++) {
56 int index = (word >> (18 - i * 6)) & 0x3f;
57 result.push_back(list_code[index]);
59 result.push_back('=');
67 string base64_decode(const string& source)
69 static const char reverse_table[128] =
71 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
72 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
73 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
74 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
75 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
76 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
77 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
78 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64
83 for (auto i = source.cbegin(); i != source.cend();) {
84 int bits_collected = 0;
85 unsigned int accumulator = 0;
87 for (bits_collected = 0; bits_collected < 24 && i != source.cend(); ++i) {
89 // Skip whitespace and padding. Be liberal in what you accept.
90 if (std::isspace(c) || c == '=') {
94 if ((c > 127) || (c < 0) || (reverse_table[c] > 63)) {
95 throw std::invalid_argument("Source contains characters not legal in a base64 encoded string.");
98 accumulator = (accumulator << 6) | reverse_table[c];
102 if (bits_collected < 8) {
103 throw std::invalid_argument("Wrong source length");
106 while (bits_collected >= 8) {
108 result.push_back((char)((accumulator >> bits_collected) & 0xff));