pyauth / pyotp

Python One-Time Password Library
https://pyauth.github.io/pyotp/
Other
2.98k stars 324 forks source link

Time remaining in totp.now() #87

Closed mirrormirage0 closed 4 years ago

mirrormirage0 commented 4 years ago

Not a bug. Feature request. How do we get the Time remaining for totp.now()

tilkinsc commented 4 years ago

You can get it by (current_time / time_block) - (totp_now_time / time_block) where time_block is probably 30, then you can compare in terms of how many steps ahead the key generated lasts. For example, if it lasts 1 in the past and 1 in the future, then that equation results to ((current_time / time_block) - (totp_now_time / time_block)) <= 1 where 0 would be its within 30 seconds.

If you want to do it without the time_block divisor, then you would remove the divisor and calculate using the said 1 in the past and 1 in the future by 30 in the past and 30 in the future.

So, (totp_now_time + 30) - current_time and use it like (totp_now_time + 30) - current_time <= 30 probably won't use this without the following comparison ((totp_now_time + 30) - current_time) > 0 still exists if current_time is not greater than totp_now_time + 30

It makes sense to use either or, but the former constrains it to 30 second intervals/normalized.

kislyuk commented 4 years ago

Using modulo arithmetic:

import pyotp, datetime
totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
time_remaining = totp.interval - datetime.datetime.now().timestamp() % totp.interval

Added an example to the docs in https://github.com/pyauth/pyotp/commit/a25a1f480f33241db76d26ef6566cb41e5805a6d