66 lines
3.7 KiB
C
Raw Normal View History

2019-06-26 22:11:22 +02:00
#pragma once
#include <string>
#include <string_view>
#include <cstring>
2019-07-07 19:03:08 +02:00
#include <cassert>
2019-06-26 22:11:22 +02:00
#ifdef NO_OPEN_SSL
2019-07-07 19:13:11 +02:00
#define SHA_DIGEST_LENGTH (20)
2019-07-07 18:05:22 +02:00
#define SHA256_DIGEST_LENGTH (32)
#define SHA512_DIGEST_LENGTH (64)
2019-06-26 22:11:22 +02:00
2019-07-07 18:05:22 +02:00
#define DECLARE_DIGEST(name, _unused_, digestLength) \
namespace tomcrypt { \
2019-07-07 18:35:04 +02:00
extern void name(const char* input, size_t length, uint8_t* result); \
2019-07-07 18:05:22 +02:00
} \
inline std::string name(const std::string& input) { \
uint8_t result[digestLength]; \
tomcrypt::name(input.data(), input.length(), result); \
2019-07-07 19:02:28 +02:00
auto _result = std::string((const char*) result, (size_t) digestLength); \
2019-07-07 19:04:20 +02:00
assert(_result.length() == digestLength); \
2019-07-07 19:02:28 +02:00
return _result; \
2019-07-07 18:05:22 +02:00
} \
\
2019-07-07 18:06:02 +02:00
inline std::string name(const char* input, int64_t length = -1) { \
2019-07-07 18:05:22 +02:00
if(length == -1) length = strlen(input); \
uint8_t result[digestLength]; \
tomcrypt::name(input, length, result); \
2019-07-07 19:02:28 +02:00
auto _result = std::string((const char*) result, (size_t) digestLength); \
2019-07-07 19:04:20 +02:00
assert(_result.length() == digestLength); \
2019-07-07 19:02:28 +02:00
return _result; \
2019-07-07 18:05:22 +02:00
} \
\
2019-07-07 18:35:04 +02:00
\
inline void name(const char* input, size_t length, uint8_t* result) { \
tomcrypt::name(input, length, result); \
2019-07-07 18:05:22 +02:00
}
2019-06-26 22:11:22 +02:00
#else
#include <openssl/sha.h>
2019-07-07 18:05:22 +02:00
#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, (size_t) digestLength); \
} \
\
inline std::string name(const char* input, ssize_t length = -1) { \
if(length == -1) length = strlen(input); \
return name(std::string(input, (size_t) length)); \
} \
2019-07-07 18:35:04 +02:00
\
inline void name(const char* input, size_t length, uint8_t* result) { \
method((u_char*) input, length, result); \
2019-06-26 22:11:22 +02:00
}
#endif
namespace digest {
DECLARE_DIGEST(sha1, SHA1, SHA_DIGEST_LENGTH)
DECLARE_DIGEST(sha256, SHA256, SHA256_DIGEST_LENGTH)
DECLARE_DIGEST(sha512, SHA512, SHA512_DIGEST_LENGTH)
}
2019-07-07 16:57:21 +02:00
#undef DECLARE_DIGEST