Skip to content

Commit

Permalink
wip: HMAC for key generation
Browse files Browse the repository at this point in the history
  • Loading branch information
tcsullivan committed Apr 3, 2024
1 parent d092937 commit 01d3cba
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
8 changes: 5 additions & 3 deletions noisemeter-device/noisemeter-device.ino
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,9 @@ void printReadingToConsole(double reading) {
void saveNetworkCreds(WebServer& httpServer) {
// Confirm that the form was actually submitted.
if (httpServer.hasArg("ssid") && httpServer.hasArg("psk")) {
const auto ssid = Secret().encrypt(httpServer.arg("ssid"));
const auto psk = Secret().encrypt(httpServer.arg("psk"));
const auto id = String(buildDeviceId());
const auto ssid = Secret(id).encrypt(httpServer.arg("ssid"));
const auto psk = Secret(id).encrypt(httpServer.arg("psk"));

// Confirm that the given credentials will fit in the allocated EEPROM space.
if (!ssid.isEmpty() && Creds.canStore(ssid) && Creds.canStore(psk)) {
Expand Down Expand Up @@ -321,7 +322,8 @@ int tryWifiConnection()
const auto psk = Creds.get(Storage::Entry::Passkey);

WiFi.mode(WIFI_STA);
const auto stat = WiFi.begin(Secret().decrypt(ssid).c_str(), Secret().decrypt(psk).c_str());
const auto id = String(buildDeviceId());
const auto stat = WiFi.begin(Secret(id).decrypt(ssid).c_str(), Secret(id).decrypt(psk).c_str());
if (stat == WL_CONNECT_FAILED)
return -1;

Expand Down
20 changes: 10 additions & 10 deletions noisemeter-device/secret-store.h
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
#include <esp_hmac.h>
#include <mbedtls/aes.h>

class Secret
{
constexpr static int BITS = 128;
constexpr static int BITS = 256; // do not change
mbedtls_aes_context aes;
unsigned char key[BITS / 8];
uint8_t hmac[BITS / 8];

void generateKey() {
const auto id = String(DEVICE_ID);
for (unsigned i = 0; i < sizeof(key); ++i)
key[i] = id[i % id.length()];
bool generateKey(String key) {
const auto result = esp_hmac_calculate(HMAC_KEY4, key.c_str(), key.length(), hmac);
return result == ESP_OK;
}

String process(String in, int mode) {
Expand All @@ -19,22 +19,22 @@ class Secret
}

public:
Secret() {
Secret(String key) {
mbedtls_aes_init(&aes);
generateKey();
generateKey(key);
}

~Secret() {
mbedtls_aes_free(&aes);
}

String encrypt(String in) {
mbedtls_aes_setkey_enc(&aes, key, BITS);
mbedtls_aes_setkey_enc(&aes, hmac, BITS);
return process(in, MBEDTLS_AES_ENCRYPT);
}

String decrypt(String in) {
mbedtls_aes_setkey_dec(&aes, key, BITS);
mbedtls_aes_setkey_dec(&aes, hmac, BITS);
return process(in, MBEDTLS_AES_DECRYPT);
}
};
Expand Down

0 comments on commit 01d3cba

Please sign in to comment.