Skip to content

Commit

Permalink
remove rweather/Crypt lib from firmware (save 2.1k of flash)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
schlimmchen committed May 6, 2024
1 parent 1dd64a5 commit b7a8bdf
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 20 deletions.
1 change: 0 additions & 1 deletion platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 15 additions & 19 deletions src/HttpPowerMeter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
#include "MessageOutput.h"
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <Crypto.h>
#include <SHA256.h>
#include "mbedtls/sha256.h"
#include <base64.h>
#include <memory>
#include <ESPmDNS.h>
Expand Down Expand Up @@ -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<const unsigned char*>(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");
Expand Down

0 comments on commit b7a8bdf

Please sign in to comment.