How to generate and verify TOTP 2FA codes (in C#)

Full article

A few days ago I wrote about how to create a TOTP 2FA code for your app, and I mentioned at the end of it that I'd like to work out an implementation in C#. Here it is!

Grab the source code for the WPF app from GitHub (or get the compiled version). The label, issuer and secret will be prepopulated at startup, but feel free to change them. As you do, the QR code is regenerated. When you're ready, scan it with your phone to add it like any other 2FA code.

Enter the code from your phone into the bottom field to verify that it's valid.
Enter an invalid TOTP code and ... it tells you. Hm. Pretty exciting stuff.

The numbers at the very bottom, in parentheses, represent the number of steps, or possible codes that could've been generated since the Unix epoch in 1970:

= seconds since unix epoch / time between codes, usually 30 seconds

One of the recommendations I read was to allow ยฑ1 step, in case your server and a user's phone have slightly different times, or the user is a bit slow to enter the code and it changes. That's why I display three codes (past, current, next).

During the elapsed time between the two screenshots, you can see a new "current" code has been generated, so the previously "current" code is now the current "previous" code. Clear as mud?



Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.

Comments / Reactions

One of the most enjoyable things about blogging is engaging with and learning from others. Leave a comment below with your questions, comments, or ideas. Let's start a conversation!