Skip to content

Instantly share code, notes, and snippets.

@alexastrum
Last active July 29, 2020 18:22
Show Gist options
  • Save alexastrum/55b954d4d4b0412bf641102ce66641a0 to your computer and use it in GitHub Desktop.
Save alexastrum/55b954d4d4b0412bf641102ce66641a0 to your computer and use it in GitHub Desktop.
#define WIFI_SSID ""
#define WIFI_PASSWORD ""
// Firebase
#define PROJECT_ID ""
#define DEVICE_ID "TestDevice"
// Firebase Auth
#define FUNCTIONS_REGION "us-central1"
#define NONCE 1
#include <ArduinoECCX08.h>
#include <utility/ECCX08JWS.h>
void setupCrypto()
{
if (!ECCX08.begin())
{
displaySuspend("No ECCX08 present!");
}
if (!ECCX08.locked())
{
displaySuspend("The ECCX08 on your board is not locked!");
}
String publicKey = ECCX08JWS.publicKey(/* slot */ 0, false);
if (publicKey == "")
{
displaySuspend("Key missing. Generate a new key pair!");
}
}
String getDeviceToken()
{
String header = "";
DynamicJsonDocument json(1024);
// ATECCx08 crypto chips only support ES256:
// https://github.com/MicrochipTech/cryptoauthlib/blob/master/lib/jwt/atca_jwt.c
json["alg"] = "ES256";
json["kid"] = DEVICE_ID;
serializeJson(json, header);
String payload;
json.clear();
json["nonce"] = NONCE;
serializeJson(json, payload);
return ECCX08JWS.sign(/* slot */ 0, header, payload);
}
String getIdToken(String deviceToken)
{
displayStatus("Fetching idToken...");
String host = String(FUNCTIONS_REGION) + "-" + String(PROJECT_ID) + ".cloudfunctions.net";
WiFiSSLClient wifiClient;
HttpClient httpClient = HttpClient(wifiClient, host, 443);
httpClient.post("/getIdToken", "text/plain", deviceToken);
int statusCode = httpClient.responseStatusCode();
String response = httpClient.responseBody();
httpClient.stop();
if (statusCode != 200) {
displayError(String(statusCode) + " " + response);
return "";
}
displayStatus("Received idToken.");
DynamicJsonDocument json = toJsonDocument(response);
return json["idToken"].as<String>();
}
#include "config.h"
#include "display.h"
#include "crypto.h"
#include "wifi.h"
#include "http_client.h"
#include "firebase_auth.h"
#include "firebase_database.h"
void setup()
{
setupDisplay();
setupCrypto();
setupWiFi();
}
void loop()
{
String deviceToken = getDeviceToken();
displayStatus("Device token: " + deviceToken);
String idToken = getIdToken(deviceToken);
displayStatus("Id token: " + idToken);
DynamicJsonDocument json(1024);
json["now"] = "secured";
firebaseDatabasePut(DEVICE_ID, json, idToken);
displaySuspend("All done!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment