libravatarserv/src/hash.cpp

88 lines
2.6 KiB
C++

/* This file is part of libravatarserv.
* Copyright © 2022 tastytea <tastytea@tastytea.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hash.hpp"
#include "types.hpp"
#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 // necessary for MD5
#include <cryptopp/cryptlib.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
namespace libravatarserv::hash {
std::string generate_hash(const algorithm_t algo, const std::string_view text) {
using namespace CryptoPP;
SHA256 sha256;
Weak::MD5 md5;
HashTransformation *algo_to_use{&sha256}; // HashFilter calls free()?
if (algo == algorithm_t::MD5) {
algo_to_use = &md5;
}
std::string hash;
StringSource s(text.data(), true,
new HashFilter(*algo_to_use,
new HexEncoder(new StringSink(hash))));
std::transform(hash.begin(), hash.end(), hash.begin(), ::tolower);
return hash;
}
std::string find_email(const request_t &req, const fs::path &directory) {
bool default_present{false};
for (const fs::path &path : fs::recursive_directory_iterator(directory)) {
if (fs::is_regular_file(path)) {
std::string email = path.filename();
std::transform(email.begin(), email.end(), email.begin(),
::tolower);
if (generate_hash(req.algo, email) == req.hash) {
return email;
}
if (email == "default") {
default_present = true;
}
}
}
return default_present ? "default" : "";
}
bool is_valid(const std::string_view hash) {
auto not_hex{[](const char c) {
if (c >= 0x61 && c <= 0x66) { // a-f
return false;
}
if (c >= 0x30 && c <= 0x39) { // 0-9
return false;
}
return true;
}};
return !std::any_of(hash.begin(), hash.end(), not_hex);
}
} // namespace libravatarserv::hash