ESPHome 2025.10.1
Loading...
Searching...
No Matches
sha256.h
Go to the documentation of this file.
1#pragma once
2
4
5// Only define SHA256 on platforms that support it
6#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_LIBRETINY) || defined(USE_HOST)
7
8#include <cstdint>
9#include <string>
10#include <memory>
12
13#if defined(USE_ESP32) || defined(USE_LIBRETINY)
14#include "mbedtls/sha256.h"
15#elif defined(USE_ESP8266) || defined(USE_RP2040)
16#include <bearssl/bearssl_hash.h>
17#elif defined(USE_HOST)
18#include <openssl/evp.h>
19#else
20#error "SHA256 not supported on this platform"
21#endif
22
23namespace esphome::sha256 {
24
25class SHA256 : public esphome::HashBase {
26 public:
27 SHA256() = default;
28 ~SHA256() override;
29
30 void init() override;
31 void add(const uint8_t *data, size_t len) override;
32 using HashBase::add; // Bring base class overload into scope
33 void add(const std::string &data) { this->add((const uint8_t *) data.c_str(), data.length()); }
34
35 void calculate() override;
36
38 size_t get_size() const override { return 32; }
39
40 protected:
41#if defined(USE_ESP32) || defined(USE_LIBRETINY)
42 // CRITICAL: The mbedtls context MUST be stack-allocated (not a pointer) for ESP32-S3 hardware SHA acceleration.
43 // The ESP32-S3 DMA engine references this structure's memory addresses. If the context is passed to another
44 // function (crossing stack frames) or if VLAs are present, the DMA operations will corrupt memory and produce
45 // truncated/incorrect hash results.
46 mbedtls_sha256_context ctx_{};
47#elif defined(USE_ESP8266) || defined(USE_RP2040)
48 br_sha256_context ctx_{};
49 bool calculated_{false};
50#elif defined(USE_HOST)
51 EVP_MD_CTX *ctx_{nullptr};
52 bool calculated_{false};
53#else
54#error "SHA256 not supported on this platform"
55#endif
56};
57
58} // namespace esphome::sha256
59
60#endif // Platform check
Base class for hash algorithms.
Definition hash_base.h:11
virtual void add(const uint8_t *data, size_t len)=0
Add bytes of data for the hash.
void calculate() override
Definition sha256.cpp:55
size_t get_size() const override
Get the size of the hash in bytes (32 for SHA256)
Definition sha256.h:38
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:53
void add(const std::string &data)
Definition sha256.h:33
mbedtls_sha256_context ctx_
Definition sha256.h:46
void init() override
Definition sha256.cpp:48
std::string size_t len
Definition helpers.h:304