ESPHome 2025.10.0-dev
Loading...
Searching...
No Matches
hash_base.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <cstddef>
5#include <cstring>
7
8namespace esphome {
9
11class HashBase {
12 public:
13 virtual ~HashBase() = default;
14
16 virtual void init() = 0;
17
19 virtual void add(const uint8_t *data, size_t len) = 0;
20 void add(const char *data, size_t len) { this->add((const uint8_t *) data, len); }
21
23 virtual void calculate() = 0;
24
26 void get_bytes(uint8_t *output) { memcpy(output, this->digest_, this->get_size()); }
27
29 void get_hex(char *output) {
30 for (size_t i = 0; i < this->get_size(); i++) {
31 uint8_t byte = this->digest_[i];
32 output[i * 2] = format_hex_char(byte >> 4);
33 output[i * 2 + 1] = format_hex_char(byte & 0x0F);
34 }
35 }
36
38 bool equals_bytes(const uint8_t *expected) { return memcmp(this->digest_, expected, this->get_size()) == 0; }
39
41 bool equals_hex(const char *expected) {
42 uint8_t parsed[this->get_size()];
43 if (!parse_hex(expected, parsed, this->get_size())) {
44 return false;
45 }
46 return this->equals_bytes(parsed);
47 }
48
50 virtual size_t get_size() const = 0;
51
52 protected:
53 uint8_t digest_[32]; // Storage sized for max(MD5=16, SHA256=32) bytes
54};
55
56} // namespace esphome
Base class for hash algorithms.
Definition hash_base.h:11
void get_hex(char *output)
Retrieve the hash as hex characters.
Definition hash_base.h:29
uint8_t digest_[32]
Definition hash_base.h:53
virtual ~HashBase()=default
bool equals_hex(const char *expected)
Compare the hash against a provided hex-encoded hash.
Definition hash_base.h:41
virtual void calculate()=0
Compute the hash based on provided data.
virtual void init()=0
Initialize a new hash computation.
bool equals_bytes(const uint8_t *expected)
Compare the hash against a provided byte-encoded hash.
Definition hash_base.h:38
virtual size_t get_size() const =0
Get the size of the hash in bytes (16 for MD5, 32 for SHA256)
void add(const char *data, size_t len)
Definition hash_base.h:20
virtual void add(const uint8_t *data, size_t len)=0
Add bytes of data for the hash.
void get_bytes(uint8_t *output)
Retrieve the hash as bytes.
Definition hash_base.h:26
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:291
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:239
char format_hex_char(uint8_t v)
Convert a nibble (0-15) to lowercase hex char.
Definition helpers.h:395