2023-08-01 13:54:17 +08:00
|
|
|
#include "SecureHashAlgorithm.h"
|
2024-10-29 21:51:37 +08:00
|
|
|
#include <mbedtls/sha256.h>
|
2023-08-01 13:54:17 +08:00
|
|
|
#include <iomanip>
|
|
|
|
#include <sstream>
|
|
|
|
|
|
|
|
class SecureHashAlgorithmPrivate {
|
|
|
|
public:
|
|
|
|
mbedtls_sha256_context context;
|
|
|
|
};
|
|
|
|
|
|
|
|
SecureHashAlgorithm::SecureHashAlgorithm() : m_d(new SecureHashAlgorithmPrivate()) {
|
|
|
|
mbedtls_sha256_init(&m_d->context);
|
|
|
|
mbedtls_sha256_starts(&m_d->context, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
SecureHashAlgorithm::~SecureHashAlgorithm() {
|
|
|
|
mbedtls_sha256_free(&m_d->context);
|
|
|
|
delete m_d;
|
|
|
|
}
|
|
|
|
|
|
|
|
int SecureHashAlgorithm::update(const unsigned char *input, size_t ilen) {
|
|
|
|
return mbedtls_sha256_update(&m_d->context, input, ilen);
|
|
|
|
}
|
|
|
|
|
|
|
|
int SecureHashAlgorithm::finish(unsigned char *output) {
|
|
|
|
return mbedtls_sha256_finish(&m_d->context, output);
|
|
|
|
}
|
|
|
|
|
|
|
|
int SecureHashAlgorithm::sha256(const unsigned char *input, size_t ilen, unsigned char *output) {
|
|
|
|
return mbedtls_sha256(input, ilen, output, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string SecureHashAlgorithm::sha256(const std::string_view &input, Sha256DigestType &digest) {
|
|
|
|
sha256(reinterpret_cast<const uint8_t *>(input.data()), input.size(), digest);
|
|
|
|
std::ostringstream oss;
|
|
|
|
for (int i = 0; i < sizeof(Sha256DigestType); ++i)
|
|
|
|
oss << std::hex << std::setfill('0') << std::setw(2) << (((uint16_t)digest[i]) & 0xFF);
|
|
|
|
return oss.str();
|
|
|
|
}
|