comparison C++/Base64.cpp @ 238:b97d75a78e22

Add Base64, base64 encoding and decoding
author David Demelier <markand@malikania.fr>
date Thu, 11 Sep 2014 17:21:51 +0200
parents
children
comparison
equal deleted inserted replaced
237:887d43215b90 238:b97d75a78e22
1 /*
2 * Base64.cpp -- base64 encoding and decoding
3 *
4 * Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <iterator>
20 #include <sstream>
21
22 #include "Base64.h"
23
24 char Base64::lookup(int value) noexcept
25 {
26 static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
27
28 return table[value];
29 }
30
31 int Base64::rlookup(char ch)
32 {
33 if (ch == '+')
34 return 62;
35 if (ch == '/')
36 return 63;
37
38 if (ch >= '0' && ch <= '9')
39 return ch + 4;
40 if (ch >= 'A' && ch <= 'Z')
41 return ch - 65;
42 if (ch >= 'a' && ch <= 'z')
43 return ch - 71;
44
45 throw std::invalid_argument("not a valid base64 string");
46 }
47
48 std::string Base64::encode(const std::string &input)
49 {
50 std::string result;
51 std::istringstream iss(input, std::istringstream::in);
52
53 encode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));
54
55 return result;
56 }
57
58 std::string Base64::decode(const std::string &input)
59 {
60 std::string result;
61 std::istringstream iss(input, std::istringstream::in);
62
63 decode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));
64
65 return result;
66 }