ESPHome 2025.10.0-dev
Loading...
Searching...
No Matches
sha256.cpp
Go to the documentation of this file.
1#include "sha256.h"
2
3// Only compile SHA256 implementation on platforms that support it
4#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_LIBRETINY) || defined(USE_HOST)
5
7#include <cstring>
8
9namespace esphome::sha256 {
10
11#if defined(USE_ESP32) || defined(USE_LIBRETINY)
12
13SHA256::~SHA256() { mbedtls_sha256_free(&this->ctx_); }
14
16 mbedtls_sha256_init(&this->ctx_);
17 mbedtls_sha256_starts(&this->ctx_, 0); // 0 = SHA256, not SHA224
18}
19
20void SHA256::add(const uint8_t *data, size_t len) { mbedtls_sha256_update(&this->ctx_, data, len); }
21
22void SHA256::calculate() { mbedtls_sha256_finish(&this->ctx_, this->digest_); }
23
24#elif defined(USE_ESP8266) || defined(USE_RP2040)
25
26SHA256::~SHA256() = default;
27
28void SHA256::init() {
29 br_sha256_init(&this->ctx_);
30 this->calculated_ = false;
31}
32
33void SHA256::add(const uint8_t *data, size_t len) { br_sha256_update(&this->ctx_, data, len); }
34
35void SHA256::calculate() {
36 if (!this->calculated_) {
37 br_sha256_out(&this->ctx_, this->digest_);
38 this->calculated_ = true;
39 }
40}
41
42#elif defined(USE_HOST)
43
45 if (this->ctx_) {
46 EVP_MD_CTX_free(this->ctx_);
47 }
48}
49
50void SHA256::init() {
51 if (this->ctx_) {
52 EVP_MD_CTX_free(this->ctx_);
53 }
54 this->ctx_ = EVP_MD_CTX_new();
55 EVP_DigestInit_ex(this->ctx_, EVP_sha256(), nullptr);
56 this->calculated_ = false;
57}
58
59void SHA256::add(const uint8_t *data, size_t len) {
60 if (!this->ctx_) {
61 this->init();
62 }
63 EVP_DigestUpdate(this->ctx_, data, len);
64}
65
66void SHA256::calculate() {
67 if (!this->ctx_) {
68 this->init();
69 }
70 if (!this->calculated_) {
71 unsigned int len = 32;
72 EVP_DigestFinal_ex(this->ctx_, this->digest_, &len);
73 this->calculated_ = true;
74 }
75}
76
77#else
78#error "SHA256 not supported on this platform"
79#endif
80
81} // namespace esphome::sha256
82
83#endif // Platform check
uint8_t digest_[32]
Definition hash_base.h:53
void calculate() override
Definition sha256.cpp:22
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:20
mbedtls_sha256_context ctx_
Definition sha256.h:42
void init() override
Definition sha256.cpp:15
std::string size_t len
Definition helpers.h:291