Search code examples
arduinoesp8266esp32arduino-esp8266arduino-esp32

Options to hide ssid password in an ESP32 sketch


I am using ESP32, but I assume the question is applicable to esp8266 or Arduino WIFI. That is why I extended my tags. Please let me know if I am wrong.

I have a working sketch that uses WIFI to send http requests.

My current code includes SSID and password in clear text:

const char *ssid = "my_secure_router";
const char *password = "clear_text_password_is_bad";

void initWifi(){
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(WiFi.status());
    Serial.print("*");
  }
  Serial.print("WiFi connected with IP: ");
  Serial.println(WiFi.localIP());
}

While the code is working, I am not able to push the code to a git repository since it includes the password in clear text.

Is there any easy option to eliminate the clear text password from the above code?


Solution

  • People often do this by using a second file that's not checked into the repository. They'll often name the file secrets.h or config.h.

    Then you'd change your code to look like:

    #include "secrets.h"
    
    void initWifi(){
      WiFi.mode(WIFI_STA);
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.println("");
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println(WiFi.status());
        Serial.print("*");
      }
      Serial.print("WiFi connected with IP: ");
      Serial.println(WiFi.localIP());
    }
    

    and put this in secrets.h:

    #pragma once
    
    #define WIFI_SSID "my_secure_router";
    #define WIFI_PASSWORD "clear_text_password_is_bad";
    

    The #pragma line stops the file from being processed if it's included twice, which avoids errors from WIFI_SSID and WIFI_PASSWORD being defined multiple times.

    Then add secrets.h to .gitignore so that git won't check it in.

    As a bonus, you might create a secrets.h-example file that has dummy strings for all the secrets that are stored in it.

    Note that I changed the two strings from being C++ character array variables to preprocessor constants. There's really no benefit in this case to storing the strings in variables, and using preprocessor constants simplifies their use.