ESPHome 2026.4.0-dev
Loading...
Searching...
No Matches
hmac_sha256.h
Go to the documentation of this file.
1#pragma once
2
4#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_LIBRETINY) || defined(USE_HOST)
5
6#include <string>
7
8#if defined(USE_ESP32)
9#include <esp_idf_version.h>
10#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
11// mbedtls 4.0 (IDF 6.0) removed the legacy mbedtls_md HMAC API.
12// Use the PSA Crypto MAC API instead.
13#define USE_HMAC_SHA256_PSA
14#include <psa/crypto.h>
15#else
16#define USE_HMAC_SHA256_MBEDTLS
17#include "mbedtls/md.h"
18#endif
19#elif defined(USE_LIBRETINY)
20#define USE_HMAC_SHA256_MBEDTLS
21#include "mbedtls/md.h"
22#else
24#endif
25
26namespace esphome::hmac_sha256 {
27
29 public:
30 HmacSHA256() = default;
32
34 void init(const uint8_t *key, size_t len);
35 void init(const char *key, size_t len) { this->init((const uint8_t *) key, len); }
36 void init(const std::string &key) { this->init(key.c_str(), key.length()); }
37
39 void add(const uint8_t *data, size_t len);
40 void add(const char *data, size_t len) { this->add((const uint8_t *) data, len); }
41
43 void calculate();
44
47 void get_bytes(uint8_t *output);
48
51 void get_hex(char *output);
52
54 bool equals_bytes(const uint8_t *expected);
55
57 bool equals_hex(const char *expected);
58
59 protected:
60#if defined(USE_HMAC_SHA256_PSA)
61 static constexpr size_t SHA256_DIGEST_SIZE = 32;
62 psa_mac_operation_t op_ = PSA_MAC_OPERATION_INIT;
63 mbedtls_svc_key_id_t key_id_ = MBEDTLS_SVC_KEY_ID_INIT;
65#elif defined(USE_HMAC_SHA256_MBEDTLS)
66 static constexpr size_t SHA256_DIGEST_SIZE = 32;
67 mbedtls_md_context_t ctx_{};
68 uint8_t digest_[SHA256_DIGEST_SIZE]{};
69#else
72#endif
73};
74
75} // namespace esphome::hmac_sha256
76#endif
bool equals_bytes(const uint8_t *expected)
Compare the digest against a provided byte-encoded digest (32 bytes).
mbedtls_md_context_t ctx_
Definition hmac_sha256.h:67
mbedtls_svc_key_id_t key_id_
Definition hmac_sha256.h:63
bool equals_hex(const char *expected)
Compare the digest against a provided hex-encoded digest (64 bytes).
void add(const char *data, size_t len)
Definition hmac_sha256.h:40
void add(const uint8_t *data, size_t len)
Add bytes of data for the digest.
void get_hex(char *output)
Retrieve the HMAC-SHA256 digest as hex characters.
void get_bytes(uint8_t *output)
Retrieve the HMAC-SHA256 digest as bytes.
void init(const std::string &key)
Definition hmac_sha256.h:36
static constexpr size_t SHA256_DIGEST_SIZE
Definition hmac_sha256.h:61
uint8_t digest_[SHA256_DIGEST_SIZE]
Definition hmac_sha256.h:64
void calculate()
Compute the digest, based on the provided data.
void init(const uint8_t *key, size_t len)
Initialize a new HMAC-SHA256 digest computation.
void init(const char *key, size_t len)
Definition hmac_sha256.h:35
SHA256 hash implementation.
Definition sha256.h:51
std::string size_t len
Definition helpers.h:1045