diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/C++/Base64.cpp	Thu Sep 11 17:21:51 2014 +0200
@@ -0,0 +1,66 @@
+/*
+ * Base64.cpp -- base64 encoding and decoding
+ *
+ * Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <iterator>
+#include <sstream>
+
+#include "Base64.h"
+
+char Base64::lookup(int value) noexcept
+{
+	static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+	return table[value];
+}
+
+int Base64::rlookup(char ch)
+{
+	if (ch == '+')
+		return 62;
+	if (ch == '/')
+		return 63;
+
+	if (ch >= '0' && ch <= '9')
+		return ch + 4;
+	if (ch >= 'A' && ch <= 'Z')
+		return ch - 65;
+	if (ch >= 'a' && ch <= 'z')
+		return ch - 71;
+
+	throw std::invalid_argument("not a valid base64 string");
+}
+
+std::string Base64::encode(const std::string &input)
+{
+	std::string result;
+	std::istringstream iss(input, std::istringstream::in);
+
+	encode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));
+
+	return result;
+}
+
+std::string Base64::decode(const std::string &input)
+{
+	std::string result;
+	std::istringstream iss(input, std::istringstream::in);
+
+	decode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));
+
+	return result;
+}
\ No newline at end of file