From b7a8bdf07b293e81bba2bd2ef2e442c19b7f5670 Mon Sep 17 00:00:00 2001 From: Bernhard Kirchen Date: Sun, 5 May 2024 23:46:20 +0200 Subject: [PATCH] remove rweather/Crypt lib from firmware (save 2.1k of flash) mbedtls is already integral part of the firmware. use it in favor of rweather/Crypto library to calculate a sha256 checksum of a string, as used in the HTTP power meter implementation. --- platformio.ini | 1 - src/HttpPowerMeter.cpp | 34 +++++++++++++++------------------- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/platformio.ini b/platformio.ini index f5bab6794..498fa5ba0 100644 --- a/platformio.ini +++ b/platformio.ini @@ -47,7 +47,6 @@ lib_deps = https://github.com/coryjfowler/MCP_CAN_lib plerup/EspSoftwareSerial @ ^8.0.1 https://github.com/dok-net/ghostl @ ^1.0.1 - rweather/Crypto@^0.4.0 extra_scripts = pre:pio-scripts/auto_firmware_version.py diff --git a/src/HttpPowerMeter.cpp b/src/HttpPowerMeter.cpp index 429d317ec..dbe9aa79a 100644 --- a/src/HttpPowerMeter.cpp +++ b/src/HttpPowerMeter.cpp @@ -4,8 +4,7 @@ #include "MessageOutput.h" #include #include -#include -#include +#include "mbedtls/sha256.h" #include #include #include @@ -324,27 +323,24 @@ bool HttpPowerMeterClass::extractUrlComponents(String url, String& _protocol, St return true; } -#define HASH_SIZE 32 - String HttpPowerMeterClass::sha256(const String& data) { - SHA256 sha256; - uint8_t hash[HASH_SIZE]; - - sha256.reset(); - sha256.update(data.c_str(), data.length()); - sha256.finalize(hash, HASH_SIZE); - - String hashStr = ""; - for (int i = 0; i < HASH_SIZE; i++) { - String hex = String(hash[i], HEX); - if (hex.length() == 1) { - hashStr += "0"; - } - hashStr += hex; + uint8_t hash[32]; + + mbedtls_sha256_context ctx; + mbedtls_sha256_init(&ctx); + mbedtls_sha256_starts(&ctx, 0); // select SHA256 + mbedtls_sha256_update(&ctx, reinterpret_cast(data.c_str()), data.length()); + mbedtls_sha256_finish(&ctx, hash); + mbedtls_sha256_free(&ctx); + + char res[sizeof(hash) * 2 + 1]; + for (int i = 0; i < sizeof(hash); i++) { + snprintf(res + (i*2), sizeof(res) - (i*2), "%02x", hash[i]); } - return hashStr; + return res; } + void HttpPowerMeterClass::prepareRequest(uint32_t timeout, const char* httpHeader, const char* httpValue) { httpClient.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); httpClient.setUserAgent("OpenDTU-OnBattery");