If you don’t know what multi-factor authentication is please read this before continuing. I am going to assume you understand the security concepts mentioned in this post…

In plain English: two-factor authentication is something you know (your password) and something you have (your token). I will focus on the token in this post. Apps like Google Authenticator and Authy generate one-time time-based tokens, or passwords. They generate them by hashing a shared secret combined with the current time. By default, the resulting token changes every 30 seconds giving the user a short window to authenticate to a service.
You can set it up with GitHub for example; in your user security settings you enable 2-factor authentication, GitHub then generates the shared secret for you which you import into the authenticator app. From then on when you login you must provide your password plus the generated token. Because both you and GitHub have access to the shared secret, both can generate the same token at the same time. If the user provided and the GitHub generated tokens match, the authentication succeeds and you’re logged in.

So what is this post about anyways? What I set-out to do today was to generate the one-time tokens programmatically from a C++ program. I wanted to test this by feeding the same shared secret to Authy and see that both my program and Authy generate the same tokens. With this working I, or you the reader, could add two-factor authentication to our applications, which is cool 🙂

Initially I started reading about the algorithm used to generate the tokens: Time-based One-time Password Algorithm. I sure as hell didn’t want to implement all of this from scratch, so I started looking for an OpenSSL implementation. During my search I came across a free (and available on Mac and Linux) framework to do what I wanted: OATH Toolkit. Once I started reading the documentation the rest fell in place very easily. I generated a dummy shared secret: 00112233445566778899 and fed it to Authy as well as my program (Google Authenticator requires it to be base32 encoded).

Below are screenshots of Authy and my program generating the same tokens. And of course the code!


Screenshot.

One Reply to “Two-factor authentication”

Leave a Reply