osquery-1/osquery/utils/base64.cpp
Filipe Manco a67525fae1 Fix LICENSE information on file headers (#5375)
Summary:
Pull Request resolved: https://github.com/facebook/osquery/pull/5375

LICENSE is now defined in a single file on the root of the project, update the
header to contain that information.

**Project LICENSE did not change.**

Reviewed By: akindyakov

Differential Revision: D13750575

fbshipit-source-id: 1e608a81b260b8395f9d008fc67f463160c1fc2b
2019-01-21 11:51:54 -08:00

70 lines
1.8 KiB
C++

/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed as defined on the LICENSE file found in the
* root directory of this source tree.
*/
#include "base64.h"
#include <boost/algorithm/string.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <osquery/logger.h>
namespace bai = boost::archive::iterators;
namespace osquery {
namespace base64 {
namespace {
typedef bai::binary_from_base64<const char*> base64_str;
typedef bai::transform_width<base64_str, 8, 6> base64_dec;
typedef bai::transform_width<std::string::const_iterator, 6, 8> base64_enc;
typedef bai::base64_from_binary<base64_enc> it_base64;
} // namespace
std::string decode(std::string encoded) {
boost::erase_all(encoded, "\r\n");
boost::erase_all(encoded, "\n");
boost::trim_right_if(encoded, boost::is_any_of("="));
if (encoded.empty()) {
return encoded;
}
try {
return std::string(base64_dec(encoded.data()),
base64_dec(encoded.data() + encoded.size()));
} catch (const boost::archive::iterators::dataflow_exception& e) {
LOG(INFO) << "Could not base64 decode string: " << e.what();
return "";
}
}
std::string encode(const std::string& unencoded) {
if (unencoded.empty()) {
return unencoded;
}
size_t writePaddChars = (3U - unencoded.length() % 3U) % 3U;
try {
auto encoded =
std::string(it_base64(unencoded.begin()), it_base64(unencoded.end()));
encoded.append(std::string(writePaddChars, '='));
return encoded;
} catch (const boost::archive::iterators::dataflow_exception& e) {
LOG(INFO) << "Could not base64 decode string: " << e.what();
return "";
}
}
} // namespace base64
} // namespace osquery