Nowadays using authentication mobile apps for 2FA is very common. I was always wondered how does it work in the background. How mobile app generates code which can be validated by the application to grant access.
I was reading about it, did some research on Google and developed an eclipse client to test also.
- When we create account in application, application generates "Secret Key"
- Application keeps this Secret Key for each user
- User register this Secret Key in Authentication App as well
- Authentication App generated 6 digit code every 30 seconds using this Secret Key
- When user tries to login, user is asked to enter the 6 digit code from the Authentication App. At the same time application also generates the 6 digit code using the Secret Key which is stored with the application. Both the codes, application and authentication app generated codes, are compared, if they match, user will be granted the access to application.
I validated this flow from eclipse client.
Here are the libraries which will be used for this Java client:
Code to generate Secret Key, this will return the Secret Key which you need to store and register in Authentication App like Google Authentication App.
Sample Secret Key: RDOVRBFZFT54DZ7E3LWTJPUNTRQINUJO
You can also generate the QR code using this Secret Key which can be used by App for registration
Code to Generate 6 Digit Code (TOTP), you need to pass the same Secret Key. This method will be there at application end.
main method to test:
You will be asked to enter the 6 digit code from authentication app which will be validated against the 6 digit code generated by application.
Important things:
- Time must be in sync
- Secret Key is the main thing, if you setup your eclipse client, you don't even need the authentication app for 2FA
Good Resources:
- https://www.protectimus.com/blog/time-drift-in-totp-hardware-tokens/