Today I’m going to show you how to make an Arduino door lock that can be opened with an OTP code generated by your smartphone.
Video
First, a short video about the project (english subtitles are available):
OTP
OTP (one-time password) is an access code you can use only one time: its main advantage is that – even if someone steals your code when you use it – it doesn’t work anymore.
Usually OTP codes also have a temporal validity, i.e. they can be used for a short period (tipically 30 seconds); those codes are called TOTP (time-based one-time password). OTP codes are widely used for secure access to home-banking websites, remote connections (VPN)…
In the past, the TOTP codes were usually generated by hardware tokens
but recently software tokens, that are smartphones applications, are becoming common:
OATH and Google Authenticator
Open Authentication (OATH) is an industry-wide collaboration to define open standards for strong authentication mechanisms. One of those standards (RFC 6238) defines an algorithm to generate TOTP codes.
The algorithm starts with a secret key (shared secret) and the actual timestamp (the number of seconds from the date 01/01/1970). With the use of an hash function (HMAC-SHA-1) on the key-timestamp pair and a truncate function on the result, you get a code of 6 numbers:
The algorithm requires therefore that the token (which generates the codes) and the server (which validates them)
[checklist]
- share the same secret key
- are in sync
[/checklist]
Google Authenticator is an opensource application you can use to obtain TOTP codes that are compliant to the algorithm described by the RFC.
It’s available for Android, iOS and Blackberry smartphones:
Google Authenticator genrates OTP codes with a validity of 30 seconds and requires a private key of 10 characters.
In the next page, I’m going to show you how to generate and validate TOTP codes with Arduino…
# 1!!!!
Great article.
I have the sketch up and running. Everything compiles and uploads beautifully.
However I am having synchronization problems. Which time zone are we to use? I cannot tell rather my phone simply uses the GMT as its system clock or rather it is GMT adjusted with an offset for my time zone.
I have tried using both GMT and GMT adjusted for my time zone with less than 5 seconds of difference between the Arduino’s time and the phone’s time. Either way the codes generated never match up.
Hi! Google Authenticator uses GMT even if your phone displays time in your timezone, so you have to configure arduino with the same timezone.
can you please share circuit diagram?
Ottimo articolo fa venir voglia di utilizzare questa serratura….
hi,i have configured arduino with the same timezone as GMT,but the codes generated never match up
Hi! make sure you’re using the same shared secret, it must work
Salve!!! Grazie per la condivisione del progetto.
Volevo chiederLe cosa si intende per:
“Choose an account name:”, presente nel sito http://www.lucadentella.it/OTP/. Si intende un nome fittizio?
Alle righe 64 e 65 dello sketch è presente una specifica data e ora, mi chiedevo se andava cambiata. Come avrà capito il mio problema è la mancata sincronizzazione dei due codici OTP. Potrebbe spiegarmi come impostare la sincronizzazione dei codici?
ciao! il nome è fittizio ed è quello che poi comparirà nella app sul cellulare. Nell’esempio va inserito “a mano” l’orario corrente appunto alle righe 64-65 dello sketch, altrimenti si potrebbe leggere l’orario da un RTC…
Grazie mille per la risposta, modificherò le righe dello sketch. Se non ho capito male, la data e l’ora, da impostare alle righe 64-65 è la stessa di quando viene premuto il pulsante “GO” e viene generata la chiave nel sito http://www.lucadentella.it/OTP/. Giusto?? 🙂 Grazie di nuovo!!!
in realtà data/ora devono essere quelle attuali di quando si compila e carica lo sketch su Arduino
Ciao, complimenti per il tuo enorme lavoro che metti a disposizione di tutti !!!
Gentilmente sapresti indicarmi come posso modificare totp.h per generare il codice con una chiave di 16 caratteri e non 10.
Ti ringrazio infinitamente
Gianni
Ciao Gianni, la libreria TOTP gestisce chiavi con lunghezza arbitraria: il secondo parametro è proprio la lunghezza della chiave: http://www.lucadentella.it/totp-libreria-per-arduino/
L’unico problema è che l’app di google accetta solo password a 10 caratteri quindi non puoi usarla se cambi la lunghezza chiave lato Arduino.
Bellissimo progetto!!
Ho provato a scaricare sia lo sketch che le librerie necessarie, ma quando clicco su “verifica” mi compare un errore facendo riferimento a “shal.h”;
infatti non ho una libreria con quel nome.
Come posso risolvere?
Grazie 1000
Complimenti ancora per il progetto
Matteo
Ciao Matteo, sha1.h è incluso in Cryptosuite (https://github.com/maniacbug/Cryptosuite) verifica che sia effettivamente installata nell’IDE.
Hello, and thank you for the inspiration.
My system, based on the BeagleBoard and in javascript has been in production for the last 3 months. It has multiple users, and the software can identify which user is typing the OTP.
Also, every user has 2 possible OTPs – one opens the door, and the other opens the door and alert the police. It also logs all accesses to a dropbox file.
Eventually I will migrate this to arduino+rtc+wifi. Do you know how many OTP tests per second can your system execute?
Best regards, OP
Salve, ho provato a compilare il tutto e sembra funzionare, ma non riesco a sincronizzare la data.
Mi spieghi come posso risolvere?
codice inserito: 794370
il codice corretto e’: 028137
Ciao Francesco… tieni conto che la data che devi configurare è UTC, non con il fuso orario italiano.
ciao
bellissimo progetto ho un problema pero a trovare la libreria “sha1.h” dove la posso trovare??
sul link che hai lasciato a mettao non mi va!!
grazie 🙂
Ciao Lorenzo, eppure è proprio presente in quel repository github
questo problema sono riuscito a risolverlo
me ora ne ho un altro cioè che( boolean setClockWithTimestamp(unsigned long timeT, int yearT = 0); mi da questo errore quando compilo lo skech
grazie mille per la disponibilità
ancora complimenti per il progetto 🙂
Ciao, che errore ti da in fase di compilazione?
ciao
l’errore che mi da è questo!!
( boolean setClockWithTimestamp(unsigned long timeT, int yearT = 0);
grazie ancora
ciao! ma stai usando il mio sketch? quel metodo (setClockWithTimestamp) non c’è proprio nel sorgente…
ciao
si sto usando il tuo skecht
mi da tutti questi errori
Arduino:1.6.7 (Windows 10), Scheda:”Arduino/Genuino Uno”
In file included from C:\Users\canto\Desktop\TOTP_DoorLock\TOTP_DoorLock.ino:4:0:
C:\Users\canto\OneDrive\Documenti\Arduino\libraries\swRTC-master/swRTC.h:531:6: error: prototype for ‘byte swRTC::setClockWithTimestamp(long unsigned int, int)’ does not match any in class ‘swRTC’
byte swRTC::setClockWithTimestamp(unsigned long timeT, int yearRef) {
^
C:\Users\canto\OneDrive\Documenti\Arduino\libraries\swRTC-master/swRTC.h:92:11: error: candidate is: boolean swRTC::setClockWithTimestamp(long unsigned int, int)
boolean setClockWithTimestamp(unsigned long timeT, int yearT = 0);
^
exit status 1
Errore durante la compilazione
Questo report potrebbe essere più ricco di informazioni con
“Mostra un output dettagliato durante la compilazione”
abilitato in “File > Impostazioni”
cosa posso fare??
grazie mille
ciao, sembra un problema della libreria swRTC… purtroppo non è mia: hai preso l’ultima versione?
ciao
io ho lo scaricata da git hub!! se riesci mi gireresti il link grazie mille
Ciao
Bellisimmo progetto
Però anche io ho lo stesso problema di Lorenzo… Cosa posso fare
Please, how you sync the RTC in arduino to take the same time from android ?
I usually use my RTCSetup software 😉
ciao Luca, complimenti per i tuoi lavori e per la scelta di condividerli. Ho provato a replicare il tuo progetto: con l’IDE 1.6.5 mi dava problemi di librerie e ho provato con l’1.0.6. Il programma gira ma produce un codice diverso da quello della app. Mi potresti aiutare? Ho inserito data e ora sullo sketch spaccando quasi il secondo nell’upload, cioè ho inserito un orario tenendo conto dei secondi per l’upload ma senza esito positivo. Ho usato l’UTC come richiesto. Ho trovato questo tuo progetto su elettronica in e cercando su google ho trovato il tuo sito…
Ciao Giorgio… molto strano: sei sicuro che la password sia la stessa che hai configurato nell’app? Prova a far generare (come fa lo sketch che ho scritto per Elettronica In) 3 codici (t-30, t e t+30) e verificare se uno di questi è valido così ti “proteggi” da piccoli disallineamenti di orario
Hi luca, how to configure hardware RTC with your sketch? i tried with DS3231 but i get error because timestamp in your sketch is long but function gettime() from DS3231 is DateTime variable. thanks
Hi Tito, you need a timestamp value not a DateTime… check if your library can return it
Hi
Awesome project !
Got an question about the TOTP interval. Is there an maximum ?
and if i change it to 3600 secounds will this then break the security ?
Thanks
Hi Thomas, no maximum but of course the more the interval is long, the less is the security
Ciao Luca,
il tuo sito web e’ un punto di riferimento prezioso. Intanto GRAZIE per tutto quello che condividi.
Vorrei generare off line il Google Authenticator code. C’e’ del codice da poter scaricare o un riferimeto?
Grazie ancora.
ciao, essendo un algoritmo “pubblico” puoi usare un qualsiasi programma che supporti la RFC6238. Ad esempio questa è una applicazione opensource che si basa sul codice di Google Authenticator.
Hi Luca. Can I change the time limit for TOTP.
yes, but the application and your code on arduino MUST use the same timestep.
but where the complete code to make OTP and send it on mobile , to verify that OTP and to open the doorl lock after verification of valid OTP. please help me.
You don’t need to send anything… both the Arduino and the mobile generate their “own” codes, but using the same algorithm with the same private key makes it possible to generate the same sequence of codes.
Ciao,
Vorrei realizzare una tastiera per aprire le porte da utilizzare nei b e b o piccoli hotel.
Praticamente utilizzando i codici OTP da comunicare al cliente per l’apertura Della camera.
Ma questo codice dovrebbe aprire la camera per i giorni che il cliente soggiorna, cioè se il cliente rimane 3 giorni, per 3 giorni il codice non dovrà modificarsi.
È possibile ciò?
Buongiorno Giuseppe… è sicuramente possibile (esistono prodotti commerciali che lo fanno) ma è un approccio completamente diverso (attualmente la serratura viene aperta con un codice valido una sola volta e entro 30s dalla sua generazione).
Ciao Luca se possibile vorrei farti alcune domande: è possibile cambiare il tempo di utilizzo del codice da 30s a 3min? Nel caso non volessi usare l’OTP cos’altro posso usare come generatore di codici random?
Grazie in anticipo.
ciao giuseppe, la libreria supporta un timeStep (durata di ogni singolo codice) variabile, guarda il metodo:
TOTP::TOTP(uint8_t* hmacKey, int keyLength, int timeStep)
Per generare i codici con cellulare vi sono moltissime app, basta che cerchi nel market “TOTP”.