Remove boost dependency
[platform/core/appfw/app-installers.git] / src / common / utils / base64.cc
1 // Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by a apache 2.0 license that can be
3 // found in the LICENSE file.
4
5 #include "common/utils/base64.h"
6
7 #include <algorithm>
8 #include <sstream>
9 #include <string>
10
11 namespace {
12
13 const char kBase64Chars[] =
14     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
15     "0123456789+/";
16
17 }  // namespace
18
19 namespace common_installer {
20
21 // from https://stackoverflow.com/a/13935718
22 std::string EncodeBase64(unsigned char* val, size_t len) {
23   std::string ret;
24   int i = 0;
25   int j = 0;
26   unsigned char char_array_3[3];
27   unsigned char char_array_4[4];
28
29   while (len--) {
30     char_array_3[i++] = *(val++);
31     if (i == 3) {
32       char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
33       char_array_4[1] = ((char_array_3[0] & 0x03) << 4) +
34           ((char_array_3[1] & 0xf0) >> 4);
35       char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) +
36           ((char_array_3[2] & 0xc0) >> 6);
37       char_array_4[3] = char_array_3[2] & 0x3f;
38
39       for(i = 0; (i <4) ; i++)
40         ret += kBase64Chars[char_array_4[i]];
41       i = 0;
42     }
43   }
44
45   if (i) {
46     for(j = i; j < 3; j++)
47       char_array_3[j] = '\0';
48
49     char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
50     char_array_4[1] = ((char_array_3[0] & 0x03) << 4) +
51         ((char_array_3[1] & 0xf0) >> 4);
52     char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) +
53         ((char_array_3[2] & 0xc0) >> 6);
54     char_array_4[3] = char_array_3[2] & 0x3f;
55
56     for (j = 0; (j < i + 1); j++)
57       ret += kBase64Chars[char_array_4[j]];
58
59     while((i++ < 3))
60       ret += '=';
61   }
62
63   return ret;
64 }
65
66 }  // namespace common_installer