How to generate and verify TOTP 2FA codes (in C#)
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 WPF app from GitHub.
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.
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?
- QRCoder: A pure C# open source QR Code implementation
- Otp.NET: Implementation of TOTP and HOTP for 2FA codes
- 2FAQrCode: Sample usage of the above two libraries in C# (compiled version)
Comments / Reactions