ESPHome 2026.5.0-dev
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)
14#include <esp_idf_version.h>
15#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
16// mbedtls 4.0 (IDF 6.0) removed the legacy mbedtls_sha256_* API.
17// Use the PSA Crypto API instead. PSA crypto is auto-initialized by
18// ESP-IDF at startup (esp_psa_crypto_init.c, priority 104).
19#define USE_SHA256_PSA
20#include <psa/crypto.h>
21#else
22#define USE_SHA256_MBEDTLS
23#include "mbedtls/sha256.h"
24#endif
25#elif defined(USE_LIBRETINY)
26#define USE_SHA256_MBEDTLS
27#include "mbedtls/sha256.h"
28#elif defined(USE_ESP8266) || defined(USE_RP2040)
29#include <bearssl/bearssl_hash.h>
30#elif defined(USE_HOST)
31#include <openssl/evp.h>
32#else
33#error "SHA256 not supported on this platform"
34#endif
35
36namespace esphome::sha256 {
37
51class SHA256 final : public esphome::HashBase {
52 public:
53 SHA256() = default;
54 ~SHA256() override;
55
56 void init() override;
57 void add(const uint8_t *data, size_t len) override;
58 using HashBase::add; // Bring base class overload into scope
59 void add(const std::string &data) { this->add((const uint8_t *) data.c_str(), data.length()); }
60
61 void calculate() override;
62
64 size_t get_size() const override { return 32; }
65
66 protected:
67#if defined(USE_SHA256_PSA)
68 psa_hash_operation_t op_ = PSA_HASH_OPERATION_INIT;
69#elif defined(USE_SHA256_MBEDTLS)
70 // The mbedtls context for ESP32-S3 hardware SHA requires proper alignment and stack frame constraints.
71 // See class documentation above for critical requirements.
72 mbedtls_sha256_context ctx_{};
73#elif defined(USE_ESP8266) || defined(USE_RP2040)
74 br_sha256_context ctx_{};
75 bool calculated_{false};
76#elif defined(USE_HOST)
77 EVP_MD_CTX *ctx_{nullptr};
78 bool calculated_{false};
79#else
80#error "SHA256 not supported on this platform"
81#endif
82};
83
84} // namespace esphome::sha256
85
86#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.
SHA256 hash implementation.
Definition sha256.h:51
void calculate() override
Definition sha256.cpp:27
size_t get_size() const override
Get the size of the hash in bytes (32 for SHA256)
Definition sha256.h:64
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:25
psa_hash_operation_t op_
Definition sha256.h:68
void add(const std::string &data)
Definition sha256.h:59
mbedtls_sha256_context ctx_
Definition sha256.h:72
void init() override
Definition sha256.cpp:19
std::string size_t len
Definition helpers.h:1045