#pragma once #include "mbedtls/md.h" #include #include #include #include #include #include const char *secret = "542ff224606c61fb3024e22f76ef9ac8"; // Preferences für persistente Speicherung Preferences preferences; String licence; // Prototype für Funktionen String getUniqueDeviceID(); String hmacSHA256(const String &key, const String &message); bool checkLicense(const String &deviceID, const String &licenseKey); void setupLicenceAPI(AsyncWebServer &server); void saveLicenceToPrefs(); void loadLicenceFromPrefs(); String getUniqueDeviceID() { uint8_t mac[6]; esp_wifi_get_mac(WIFI_IF_STA, mac); // Use STA MAC for uniqueness char id[13]; sprintf(id, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return String(id); } String hmacSHA256(const String &key, const String &message) { byte hmacResult[32]; mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; mbedtls_md_init(&ctx); const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type); mbedtls_md_setup(&ctx, md_info, 1); mbedtls_md_hmac_starts(&ctx, (const unsigned char *)key.c_str(), key.length()); mbedtls_md_hmac_update(&ctx, (const unsigned char *)message.c_str(), message.length()); mbedtls_md_hmac_finish(&ctx, hmacResult); mbedtls_md_free(&ctx); String result = ""; for (int i = 0; i < 32; i++) { char buf[3]; sprintf(buf, "%02X", hmacResult[i]); result += buf; } return result; } int getLicenseTier(const String &deviceID, const String &licenseKey) { for (int tier = 1; tier <= 4; ++tier) { String data = deviceID + ":" + String(tier); String expected = hmacSHA256(secret, data); if (licenseKey.equalsIgnoreCase(expected)) { return tier; // Found matching tier } } return 0; // No valid tier found } void setupLicenceAPI(AsyncWebServer &server) { server.on("/api/get-licence", HTTP_GET, [](AsyncWebServerRequest *request) { Serial.println("Received request to get licence"); loadLicenceFromPrefs(); String deviceID = getUniqueDeviceID(); int tier = getLicenseTier(deviceID, licence); String json = "{\"licence\":\"" + licence + "\"," "\"valid\":" + String(tier > 0 ? "true" : "false") + ",\"tier\":" + String(tier) + "}"; request->send(200, "application/json", json); }); server.on("/api/set-licence", HTTP_POST, [](AsyncWebServerRequest *request) { Serial.println("Received request to set licence"); if (request->hasParam("licence", true)) { licence = request->getParam("licence", true)->value(); Serial.println("Received request to set licence " + licence); saveLicenceToPrefs(); // eigene Funktion request->send(200, "application/json", "{\"success\":true}"); } else { request->send(400, "application/json", "{\"success\":false}"); } }); Serial.println("Licence API setup complete"); } void saveLicenceToPrefs() { preferences.begin("key", false); preferences.putString("key", licence); preferences.end(); } void loadLicenceFromPrefs() { preferences.begin("key", true); licence = preferences.getString("key", ""); preferences.end(); }