Kylin/Encrypt/Encrypt.cpp

57 lines
2.0 KiB
C++
Raw Normal View History

2023-08-01 13:54:17 +08:00
#include "Encrypt.h"
#include <array>
#include <boost/algorithm/hex.hpp>
#include <boost/algorithm/string/trim.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 <boost/uuid/detail/sha1.hpp>
std::string Encrypt::encode64(const char *data, size_t size) {
using namespace boost::archive::iterators;
using Iterator = base64_from_binary<transform_width<const char *, 6, 8>>;
auto tmp = std::string(Iterator(data), Iterator(data + size));
return tmp.append((3 - size % 3) % 3, '=');
}
std::string Encrypt::encode64(const std::string_view &data) {
return encode64(data.data(), data.size());
}
std::string Encrypt::decode64(const std::string_view &data) {
using namespace boost::archive::iterators;
using Iterator = transform_width<binary_from_base64<std::string_view::const_iterator>, 8, 6>;
std::string binary(Iterator(std::cbegin(data)), Iterator(std::cend(data)));
// return boost::algorithm::trim_right_copy_if(binary, [](char c) { return c == '\0'; });
// Remove padding.
auto length = data.size();
if (binary.size() > 2 && data[length - 1] == '=' && data[length - 2] == '=') {
binary.erase(binary.end() - 2, binary.end());
} else if (binary.size() > 1 && data[length - 1] == '=') {
binary.erase(binary.end() - 1, binary.end());
}
return binary;
}
std::string Encrypt::sha1sum(const std::string_view &data, Sha1DigestType &digest) {
return sha1sum(data.data(), data.size(), digest);
}
std::string Encrypt::sha1sum(const char *data, size_t size, Sha1DigestType &digest) {
boost::uuids::detail::sha1 sha1;
sha1.process_bytes(data, size);
sha1.get_digest(digest);
std::ostringstream oss;
for (int i = 0; i < 5; ++i) oss << std::hex << std::setfill('0') << std::setw(8) << digest[i];
return oss.str();
}
std::string Encrypt::sha1sum(const std::vector<char> &data, Sha1DigestType &digest) {
return sha1sum(data.data(), data.size(), digest);
}