Guest User

totp.py

a guest
Oct 18th, 2022
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.47 KB | None | 0 0
  1. import base64
  2. import calendar
  3. import datetime
  4. import hashlib
  5. import hmac
  6. import sys
  7. import time
  8. from typing import Any
  9.  
  10. """
  11. Copyright (C) 2011-2021 Mark Percival <[email protected]>,
  12. Nathan Reynolds <[email protected]>, Andrey Kislyuk <[email protected]>,
  13. and PyOTP contributors
  14. Permission is hereby granted, free of charge, to any person obtaining a copy
  15. of this software and associated documentation files (the "Software"), to deal
  16. in the Software without restriction, including without limitation the rights
  17. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. copies of the Software, and to permit persons to whom the Software is
  19. furnished to do so, subject to the following conditions:
  20. The above copyright notice and this permission notice shall be included in
  21. all copies or substantial portions of the Software.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  24. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  25. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  26. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  28. THE SOFTWARE.
  29. """
  30.  
  31.  
  32. def int_to_bytestring(i: int, padding: int = 8) -> bytes:
  33. """
  34. Turns an integer to the OATH specified
  35. bytestring, which is fed to the HMAC
  36. along with the secret
  37. """
  38. result = bytearray()
  39. while i != 0:
  40. result.append(i & 0xFF)
  41. i >>= 8
  42. # It's necessary to convert the final result from bytearray to bytes
  43. # because the hmac functions in python 2.6 and 3.3 don't work with
  44. # bytearray
  45. return bytes(bytearray(reversed(result)).rjust(padding, b"\0"))
  46.  
  47.  
  48. def timecode(for_time: datetime.datetime, interval: int = 30) -> int:
  49. """
  50. Accepts either a timezone naive (`for_time.tzinfo is None`) or
  51. a timezone aware datetime as argument and returns the
  52. corresponding counter value (timecode).
  53. """
  54. if for_time.tzinfo:
  55. return int(calendar.timegm(for_time.utctimetuple()) / interval)
  56. else:
  57. return int(time.mktime(for_time.timetuple()) / interval)
  58.  
  59.  
  60. def byte_secret(secret) -> bytes:
  61. missing_padding = len(secret) % 8
  62. if missing_padding != 0:
  63. secret += "=" * (8 - missing_padding)
  64. return base64.b32decode(secret, casefold=True)
  65.  
  66.  
  67. def generate_otp(
  68. secret: bytes, input: int, digest: Any = hashlib.sha1, digits: int = 6
  69. ) -> str:
  70. """
  71. :param input: the HMAC counter value to use as the OTP input.
  72. Usually either the counter, or the computed integer based on the Unix timestamp
  73. """
  74. if input < 0:
  75. raise ValueError("input must be positive integer")
  76.  
  77. hasher = hmac.new(secret, int_to_bytestring(input), digest)
  78. hmac_hash = bytearray(hasher.digest())
  79.  
  80. offset = hmac_hash[-1] & 0xF
  81.  
  82. code = (
  83. (hmac_hash[offset] & 0x7F) << 24
  84. | (hmac_hash[offset + 1] & 0xFF) << 16
  85. | (hmac_hash[offset + 2] & 0xFF) << 8
  86. | (hmac_hash[offset + 3] & 0xFF)
  87. )
  88.  
  89. str_code = str(code % 10**digits)
  90.  
  91. while len(str_code) < digits:
  92. str_code = "0" + str_code
  93.  
  94. return str_code
  95.  
  96.  
  97. def easy_totp(secret):
  98. return generate_otp(byte_secret(secret), timecode(datetime.datetime.now()))
  99.  
  100.  
  101. if __name__ == "__main__":
  102. for secret in sys.argv[1:]:
  103. print(easy_totp(secret))
Add Comment
Please, Sign In to add comment