Python TOTP
I recently created an implementation of the TOTP standard in Python which can be found here. It was a fun little project to do over a few days, and was probably the first time I’ve really implemented a commonly used algorithm from scratch.
I found a great writeup on the University of Melbourne site, which has now sadly been placed behind a login screen, which went into a great amount of detail about the TOTP algorithm and how it works. Using a mix of this and the RFC TOTP specification I was able to wrap my head around the algorithm really quickly.
I won’t go into too much detail, but for anyone who’s interested the basic concept is combining a (ideally cryptographically random) key, with the current time. This is however done in 30 second blocks (this time can be different, but 30 seconds is standard) to ensure that if a user is slow in typing their TOTP code into a site or application, they will not be rejected entry. Often sites also implement a “grace period” where a key that is one or multiple blocks ahead or behind will also be allowed. This helps counteract problems such as time desync between the server and the user causing the user to be unable to log in.
Overall, writing the library was a lot of fun, and I learned a great deal. I feel like I more fully understand the security provided by TOTP and no longer have to wonder what exactly is being done to generate the codes every time I use them.