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 5from __future__ import absolute_import, division, print_function 6 7import struct 8 9import six 10 11from cryptography.exceptions import UnsupportedAlgorithm, _Reasons 12from cryptography.hazmat.backends import _get_backend 13from cryptography.hazmat.backends.interfaces import HMACBackend 14from cryptography.hazmat.primitives import constant_time, hmac 15from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 16from cryptography.hazmat.primitives.twofactor import InvalidToken 17from cryptography.hazmat.primitives.twofactor.utils import _generate_uri 18 19 20class HOTP(object): 21 def __init__( 22 self, key, length, algorithm, backend=None, enforce_key_length=True 23 ): 24 backend = _get_backend(backend) 25 if not isinstance(backend, HMACBackend): 26 raise UnsupportedAlgorithm( 27 "Backend object does not implement HMACBackend.", 28 _Reasons.BACKEND_MISSING_INTERFACE, 29 ) 30 31 if len(key) < 16 and enforce_key_length is True: 32 raise ValueError("Key length has to be at least 128 bits.") 33 34 if not isinstance(length, six.integer_types): 35 raise TypeError("Length parameter must be an integer type.") 36 37 if length < 6 or length > 8: 38 raise ValueError("Length of HOTP has to be between 6 to 8.") 39 40 if not isinstance(algorithm, (SHA1, SHA256, SHA512)): 41 raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.") 42 43 self._key = key 44 self._length = length 45 self._algorithm = algorithm 46 self._backend = backend 47 48 def generate(self, counter): 49 truncated_value = self._dynamic_truncate(counter) 50 hotp = truncated_value % (10 ** self._length) 51 return "{0:0{1}}".format(hotp, self._length).encode() 52 53 def verify(self, hotp, counter): 54 if not constant_time.bytes_eq(self.generate(counter), hotp): 55 raise InvalidToken("Supplied HOTP value does not match.") 56 57 def _dynamic_truncate(self, counter): 58 ctx = hmac.HMAC(self._key, self._algorithm, self._backend) 59 ctx.update(struct.pack(">Q", counter)) 60 hmac_value = ctx.finalize() 61 62 offset = six.indexbytes(hmac_value, len(hmac_value) - 1) & 0b1111 63 p = hmac_value[offset : offset + 4] 64 return struct.unpack(">I", p)[0] & 0x7FFFFFFF 65 66 def get_provisioning_uri(self, account_name, counter, issuer): 67 return _generate_uri( 68 self, "hotp", account_name, issuer, [("counter", int(counter))] 69 ) 70