Using an Arduino as a TOTP Token

TOTP (time-based One-Time-Passwords) as super neat and widely supported. I will not go into the background or theory, but it is possible to use an Arduino and a RTC module as a TOTP token for your email provider.

DISCLAIMER: STORING YOUR KEY ON AN ARDUINO IS ONLY AS SECURE AS THE PHYSICAL ACCESS TO THE ARDUINO.

The Arduino TOTP library is pretty simple but there are a couple pitfalls:

Your RTC module needs to be set to UTC and fairly close to real time.

If you used the method that I previously posted, you will need to set the timezone on your workstation to UTC. You might also need to set an offset because this method sets the RTC behind your computer because there is a gap between when your computer complies it and when it’s pushed to the RTC.

You could also just add or subtract the appropriate amount of seconds to bring your local time zone to UTC.

You also need to know what format your seed phrase is in.

The string of characters you get from your provider is likely in “Base32”. This Arduino library needs the hex version of a Unicode string. So, if the Base32 string from your provider is this:

JBSWY3DPEHPK3PXP

You need to convert it to Unicode:

Hello!Þ­¾ï

And then convert it to hex in this format:

0x48,0x65,0x6c,0x6c,0x6f,0x21,0xde,0xad,0xbe,0xef

(Ha get it “DEADBEEF”.)

This is all doable using a tool called CyberChef.

This is the bare minimum code needed to return a valid token:

#include <Wire.h>
#include "RTClib.h"
#include <TOTP.h>

RTC_DS3231 rtc;

//Passcode in Base32: JBSWY3DPEHPK3PXP
uint8_t hmacKey[] = {0x48,0x65,0x6c,0x6c,0x6f,0x21,0xde,0xad,0xbe,0xef};

TOTP totp = TOTP(hmacKey, 10);

//Difference in seconds between actual Unix time and what your RTC is saying
int drift = 6;

void setup() {

  Wire.begin();
  Serial.begin(115200);
  delay(1000); // wait for console opening
}

void loop() {
  
    DateTime now = rtc.now();

    char* token = totp.getCode(now.unixtime()+drift);
    Serial.print("TOKEN: ");
    Serial.println(token);

    delay(1000);
}

To verify you can use this website.

From here you can do cool things like give it a battery and OLED display or destroy it because it’s not safe to keep your key lying around.

This entry was posted in Arduino and tagged . Bookmark the permalink.