58 lines
2.4 KiB
C++
58 lines
2.4 KiB
C++
#pragma once
|
|
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <cstring>
|
|
|
|
#ifdef NO_OPEN_SSL
|
|
#include <tomcrypt.h>
|
|
|
|
#define SHA_DIGEST_LENGTH 20
|
|
#define SHA256_DIGEST_LENGTH 32
|
|
#define SHA512_DIGEST_LENGTH 64
|
|
|
|
#define DECLARE_DIGEST(name, _unused_, digestLength) \
|
|
inline std::string name(const std::string& input) { \
|
|
hash_state hash{}; \
|
|
\
|
|
uint8_t buffer[digestLength]; \
|
|
\
|
|
name ##_init(&hash); \
|
|
name ##_process(&hash, (uint8_t*) input.data(), input.length()); \
|
|
name ##_done(&hash, buffer); \
|
|
\
|
|
return std::string((const char*) buffer, digestLength); \
|
|
} \
|
|
\
|
|
inline std::string name(const char* input, int64_t length = -1) { \
|
|
if(length == -1) length = strlen(input); \
|
|
return name(std::string{input, (size_t) length}); \
|
|
} \
|
|
|
|
#else
|
|
#include <openssl/sha.h>
|
|
|
|
#define DECLARE_DIGEST(name, method, digestLength) \
|
|
inline std::string name(const std::string& input) { \
|
|
u_char buffer[digestLength]; \
|
|
method((u_char*) input.data(), input.length(), buffer); \
|
|
return std::string((const char*) buffer, digestLength); \
|
|
} \
|
|
\
|
|
inline std::string name(const char* input, ssize_t length = -1) { \
|
|
if(length == -1) length = strlen(input); \
|
|
return name(std::string(input, length)); \
|
|
} \
|
|
\
|
|
inline void name(const char* input, size_t length, uint8_t(& result)[digestLength]) { \
|
|
method((u_char*) input, length, result); \
|
|
}
|
|
#endif
|
|
|
|
namespace digest {
|
|
DECLARE_DIGEST(sha1, SHA1, SHA_DIGEST_LENGTH)
|
|
DECLARE_DIGEST(sha256, SHA256, SHA256_DIGEST_LENGTH)
|
|
DECLARE_DIGEST(sha512, SHA512, SHA512_DIGEST_LENGTH)
|
|
}
|
|
|
|
#undef DECLARE_DIGEST |