hotp.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import annotations
  5. import base64
  6. import typing
  7. from urllib.parse import quote, urlencode
  8. from cryptography.hazmat.primitives import constant_time, hmac
  9. from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512
  10. from cryptography.hazmat.primitives.twofactor import InvalidToken
  11. HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512]
  12. def _generate_uri(
  13. hotp: HOTP,
  14. type_name: str,
  15. account_name: str,
  16. issuer: str | None,
  17. extra_parameters: list[tuple[str, int]],
  18. ) -> str:
  19. parameters = [
  20. ("digits", hotp._length),
  21. ("secret", base64.b32encode(hotp._key)),
  22. ("algorithm", hotp._algorithm.name.upper()),
  23. ]
  24. if issuer is not None:
  25. parameters.append(("issuer", issuer))
  26. parameters.extend(extra_parameters)
  27. label = (
  28. f"{quote(issuer)}:{quote(account_name)}"
  29. if issuer
  30. else quote(account_name)
  31. )
  32. return f"otpauth://{type_name}/{label}?{urlencode(parameters)}"
  33. class HOTP:
  34. def __init__(
  35. self,
  36. key: bytes,
  37. length: int,
  38. algorithm: HOTPHashTypes,
  39. backend: typing.Any = None,
  40. enforce_key_length: bool = True,
  41. ) -> None:
  42. if len(key) < 16 and enforce_key_length is True:
  43. raise ValueError("Key length has to be at least 128 bits.")
  44. if not isinstance(length, int):
  45. raise TypeError("Length parameter must be an integer type.")
  46. if length < 6 or length > 8:
  47. raise ValueError("Length of HOTP has to be between 6 and 8.")
  48. if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
  49. raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")
  50. self._key = key
  51. self._length = length
  52. self._algorithm = algorithm
  53. def generate(self, counter: int) -> bytes:
  54. truncated_value = self._dynamic_truncate(counter)
  55. hotp = truncated_value % (10**self._length)
  56. return "{0:0{1}}".format(hotp, self._length).encode()
  57. def verify(self, hotp: bytes, counter: int) -> None:
  58. if not constant_time.bytes_eq(self.generate(counter), hotp):
  59. raise InvalidToken("Supplied HOTP value does not match.")
  60. def _dynamic_truncate(self, counter: int) -> int:
  61. ctx = hmac.HMAC(self._key, self._algorithm)
  62. ctx.update(counter.to_bytes(length=8, byteorder="big"))
  63. hmac_value = ctx.finalize()
  64. offset = hmac_value[len(hmac_value) - 1] & 0b1111
  65. p = hmac_value[offset : offset + 4]
  66. return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF
  67. def get_provisioning_uri(
  68. self, account_name: str, counter: int, issuer: str | None
  69. ) -> str:
  70. return _generate_uri(
  71. self, "hotp", account_name, issuer, [("counter", int(counter))]
  72. )