libravatarserv/src/hash.cpp

97 lines
2.5 KiB
C++

/* This file is part of libravatarserv.
* Copyright © 2018 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 <algorithm>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include "libravatarserv.hpp"
using namespace hash;
const string hash::md5(const string &text)
{
using namespace CryptoPP;
Weak::MD5 hash;
string digest;
StringSource s(text, true,
new HashFilter(hash,
new HexEncoder(new StringSink(digest))));
std::transform(digest.begin(), digest.end(), digest.begin(), ::tolower);
return digest;
}
const string hash::sha256(const string &text)
{
using namespace CryptoPP;
SHA256 hash;
string digest;
StringSource s(text, true,
new HashFilter(hash,
new HexEncoder(new StringSink(digest))));
std::transform(digest.begin(), digest.end(), digest.begin(), ::tolower);
return digest;
}
bool hash::fill_table()
{
for (const fs::path &path :
fs::recursive_directory_iterator(settings::avatar_dir))
{
if (fs::is_regular_file(path))
{
string email = path.filename();
std::transform(email.begin(), email.end(), email.begin(), ::tolower);
table.insert({ md5(email), email });
table.insert({ sha256(email), email });
}
}
return true;
}
bool hash::is_valid(const string &digest)
{
if (digest.length() != 64 && digest.length() != 32)
{
return false;
}
if (std::any_of(digest.begin(), digest.end(), not_hex))
{
return false;
}
return true;
}
bool hash::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;
}