ESPHome 2026.1.3
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
38class SHA256 : public esphome::HashBase {
39 public:
40 SHA256() = default;
41 ~SHA256() override;
42
43 void init() override;
44 void add(const uint8_t *data, size_t len) override;
45 using HashBase::add; // Bring base class overload into scope
46 void add(const std::string &data) { this->add((const uint8_t *) data.c_str(), data.length()); }
47
48 void calculate() override;
49
51 size_t get_size() const override { return 32; }
52
53 protected:
54#if defined(USE_ESP32) || defined(USE_LIBRETINY)
55 // The mbedtls context for ESP32-S3 hardware SHA requires proper alignment and stack frame constraints.
56 // See class documentation above for critical requirements.
57 mbedtls_sha256_context ctx_{};
58#elif defined(USE_ESP8266) || defined(USE_RP2040)
59 br_sha256_context ctx_{};
60 bool calculated_{false};
61#elif defined(USE_HOST)
62 EVP_MD_CTX *ctx_{nullptr};
63 bool calculated_{false};
64#else
65#error "SHA256 not supported on this platform"
66#endif
67};
68
69} // namespace esphome::sha256
70
71#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:38
void calculate() override
Definition sha256.cpp:56
size_t get_size() const override
Get the size of the hash in bytes (32 for SHA256)
Definition sha256.h:51
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:54
void add(const std::string &data)
Definition sha256.h:46
mbedtls_sha256_context ctx_
Definition sha256.h:57
void init() override
Definition sha256.cpp:49
std::string size_t len
Definition helpers.h:595