A sample C# app for generating and verifying TOTP 2FA codes

0

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? 😏

Resources

Author

Grant Winney

Is there anything more satisfying than sharing knowledge? Of teaching someone and witnessing their "ah ha" moment? I usually write about tech, but no promises. I hope you find something interesting!



Comments