Neha
Neha

Reputation: 1

Time based OTP produces different result from same key

For a two-factor authentication system I generate a base32 key and use it to generate a time based OTP every 30 seconds using the same key. I used this code on a Badger 2040 in MicroPython.

On Windows and Linux this generates the same OTP from the same key (tested using this site). But on a Badger 2040 it generates a different OTP from that same key. Why?

Upvotes: 0

Views: 247

Answers (1)

FiguredIT
FiguredIT

Reputation: 21

A little late to the game I know, but this might help others.

Possible cause for out of sync code generation

From what I understand, OTP uses a synchronised time to generate the code, and a quick glance at your code shows that you don't set the time before using it in otp(), thus your generated code on the 2040 is based on the default epoch (IIRC that's Jan 1st 2021 00:00:00.00 by default on a RPI pico).

Setting the time with an RTC object

To set the time you can use micropython's machine RTC class to set the time like so (reproduced from linked doc):

rtc = machine.RTC()
rtc.datetime((2020, 1, 21, 2, 10, 32, 36, 0))
print(rtc.datetime())

(2020, 1, 21, 2, 10, 32, 36, 0) is a tuple of length 8 with the following format:

(year, month, day of month, timezone, hour, minutes, seconds, miliseconds)

Caveat

Note that if you don't have a battery backed RTC module like a DS3231 or a DS1307, it means the rp2040 will lose track of the time as soon as it looses power and it will have to be set again.
An alternative to using a battery backed RTC module is have the rp2040's RTC automatically synced when plugged via USB either with a python script or alternatively, by using rshell, which automatically sets the date/time, e.g:

$ rshell exit
Connecting to /dev/ttyACM0 (buffer-size 512)...
Trying to connect to REPL  connected
Retrieving sysname ... rp2
Testing if sys.stdin.buffer exists ... Y
Retrieving root directories ... 
Setting time ... Dec 22, 2022 16:02:28
Evaluating board_name ... pyboard
Retrieving time epoch ... Jan 01, 1970

Upvotes: 0

Related Questions