PyOTP 2.5.1__tar.gz → 2.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- Copyright (C) 2011-2017 Mark Percival <m@mdp.im>,
1
+ Copyright (C) 2011-2021 Mark Percival <m@mdp.im>,
2
2
  Nathan Reynolds <email@nreynolds.co.uk>, Andrey Kislyuk <kislyuk@gmail.com>,
3
3
  and PyOTP contributors
4
4
 
@@ -1,4 +1,3 @@
1
1
  include LICENSE
2
2
  include README.rst
3
- include requirements.txt
4
3
  include test.py
pyotp-2.7.0/PKG-INFO ADDED
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyotp
3
+ Version: 2.7.0
4
+ Summary: Python One Time Password Library
5
+ Home-page: https://github.com/pyotp/pyotp
6
+ Author: PyOTP contributors
7
+ Author-email: kislyuk@gmail.com
8
+ License: MIT License
9
+ Platform: MacOS X
10
+ Platform: Posix
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.6
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.6
24
+ License-File: LICENSE
25
+
26
+ PyOTP - The Python One-Time Password Library
27
+ ============================================
28
+
29
+ PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement two-factor (2FA)
30
+ or multi-factor (MFA) authentication methods in web applications and in other systems that require users to log in.
31
+
32
+ Open MFA standards are defined in `RFC 4226 <https://tools.ietf.org/html/rfc4226>`_ (HOTP: An HMAC-Based One-Time
33
+ Password Algorithm) and in `RFC 6238 <https://tools.ietf.org/html/rfc6238>`_ (TOTP: Time-Based One-Time Password
34
+ Algorithm). PyOTP implements server-side support for both of these standards. Client-side support can be enabled by
35
+ sending authentication codes to users over SMS or email (HOTP) or, for TOTP, by instructing users to use `Google
36
+ Authenticator <https://en.wikipedia.org/wiki/Google_Authenticator>`_, `Authy <https://www.authy.com/>`_, or another
37
+ compatible app. Users can set up auth tokens in their apps easily by using their phone camera to scan `otpauth://
38
+ <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>`_ QR codes provided by PyOTP.
39
+
40
+ Implementers should read and follow the `HOTP security requirements <https://tools.ietf.org/html/rfc4226#section-7>`_
41
+ and `TOTP security considerations <https://tools.ietf.org/html/rfc6238#section-5>`_ sections of the relevant RFCs. At
42
+ minimum, application implementers should follow this checklist:
43
+
44
+ - Ensure transport confidentiality by using HTTPS
45
+ - Ensure HOTP/TOTP secret confidentiality by storing secrets in a controlled access database
46
+ - Deny replay attacks by rejecting one-time passwords that have been used by the client (this requires storing the most
47
+ recently authenticated timestamp, OTP, or hash of the OTP in your database, and rejecting the OTP when a match is seen)
48
+ - Throttle (rate limit) brute-force attacks against your application's login functionality
49
+ - When implementing a "greenfield" application, consider supporting
50
+ `FIDO U2F <https://en.wikipedia.org/wiki/Universal_2nd_Factor>`_/`WebAuthn <https://www.w3.org/TR/webauthn/>`_ in
51
+ addition to HOTP/TOTP. U2F uses asymmetric cryptography to avoid using a shared secret design, which strengthens your
52
+ MFA solution against server-side attacks. Hardware U2F also sequesters the client secret in a dedicated single-purpose
53
+ device, which strengthens your clients against client-side attacks. And by automating scoping of credentials to
54
+ relying party IDs (application origin/domain names), U2F adds protection against phishing attacks. One implementation of
55
+ FIDO U2F/WebAuthn is PyOTP's sister project, `PyWARP <https://github.com/pyauth/pywarp>`_.
56
+
57
+ We also recommend that implementers read the
58
+ `OWASP Authentication Cheat Sheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md>`_ and
59
+ `NIST SP 800-63-3: Digital Authentication Guideline <https://pages.nist.gov/800-63-3/>`_ for a high level overview of
60
+ authentication best practices.
61
+
62
+ Quick overview of using One Time Passwords on your phone
63
+ --------------------------------------------------------
64
+
65
+ * OTPs involve a shared secret, stored both on the phone and the server
66
+ * OTPs can be generated on a phone without internet connectivity
67
+ * OTPs should always be used as a second factor of authentication (if your phone is lost, you account is still secured with a password)
68
+ * Google Authenticator and other OTP client apps allow you to store multiple OTP secrets and provision those using a QR Code
69
+
70
+ Installation
71
+ ------------
72
+ ::
73
+
74
+ pip install pyotp
75
+
76
+ Usage
77
+ -----
78
+
79
+ Time-based OTPs
80
+ ~~~~~~~~~~~~~~~
81
+ ::
82
+
83
+ totp = pyotp.TOTP('base32secret3232')
84
+ totp.now() # => '492039'
85
+
86
+ # OTP verified for current time
87
+ totp.verify('492039') # => True
88
+ time.sleep(30)
89
+ totp.verify('492039') # => False
90
+
91
+ Counter-based OTPs
92
+ ~~~~~~~~~~~~~~~~~~
93
+ ::
94
+
95
+ hotp = pyotp.HOTP('base32secret3232')
96
+ hotp.at(0) # => '260182'
97
+ hotp.at(1) # => '055283'
98
+ hotp.at(1401) # => '316439'
99
+
100
+ # OTP verified with a counter
101
+ hotp.verify('316439', 1401) # => True
102
+ hotp.verify('316439', 1402) # => False
103
+
104
+ Generating a Secret Key
105
+ ~~~~~~~~~~~~~~~~~~~~~~~
106
+ A helper function is provided to generate a 32-character base32 secret, compatible with Google Authenticator and other OTP apps::
107
+
108
+ pyotp.random_base32()
109
+
110
+ Some applications want the secret key to be formatted as a hex-encoded string::
111
+
112
+ pyotp.random_hex() # returns a 40-character hex-encoded secret
113
+
114
+ Google Authenticator Compatible
115
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116
+
117
+ PyOTP works with the Google Authenticator iPhone and Android app, as well as other OTP apps like Authy. PyOTP includes the
118
+ ability to generate provisioning URIs for use with the QR Code scanner built into these MFA client apps::
119
+
120
+ pyotp.totp.TOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name='alice@google.com', issuer_name='Secure App')
121
+
122
+ >>> 'otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App'
123
+
124
+ pyotp.hotp.HOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name="alice@google.com", issuer_name="Secure App", initial_count=0)
125
+
126
+ >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
127
+
128
+ This URL can then be rendered as a QR Code (for example, using https://github.com/soldair/node-qrcode) which can then be scanned
129
+ and added to the users list of OTP credentials.
130
+
131
+ Parsing these URLs is also supported::
132
+
133
+ pyotp.parse_uri('otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App')
134
+
135
+ >>> <pyotp.totp.TOTP object at 0xFFFFFFFF>
136
+
137
+ pyotp.parse_uri('otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
138
+
139
+ >>> <pyotp.totp.HOTP object at 0xFFFFFFFF>
140
+
141
+ Working example
142
+ ~~~~~~~~~~~~~~~
143
+
144
+ Scan the following barcode with your phone's OTP app (e.g. Google Authenticator):
145
+
146
+ .. image:: https://chart.apis.google.com/chart?cht=qr&chs=250x250&chl=otpauth%3A%2F%2Ftotp%2Falice%40google.com%3Fsecret%3DJBSWY3DPEHPK3PXP
147
+
148
+ Now run the following and compare the output::
149
+
150
+ import pyotp
151
+ totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
152
+ print("Current OTP:", totp.now())
153
+
154
+ Links
155
+ ~~~~~
156
+
157
+ * `Project home page (GitHub) <https://github.com/pyauth/pyotp>`_
158
+ * `Documentation <https://pyauth.github.io/pyotp/>`_
159
+ * `Package distribution (PyPI) <https://pypi.python.org/pypi/pyotp>`_
160
+ * `Change log <https://github.com/pyauth/pyotp/blob/master/Changes.rst>`_
161
+ * `RFC 4226: HOTP: An HMAC-Based One-Time Password <https://tools.ietf.org/html/rfc4226>`_
162
+ * `RFC 6238: TOTP: Time-Based One-Time Password Algorithm <https://tools.ietf.org/html/rfc6238>`_
163
+ * `ROTP <https://github.com/mdp/rotp>`_ - Original Ruby OTP library by `Mark Percival <https://github.com/mdp>`_
164
+ * `OTPHP <https://github.com/lelag/otphp>`_ - PHP port of ROTP by `Le Lag <https://github.com/lelag>`_
165
+ * `OWASP Authentication Cheat Sheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md>`_
166
+ * `NIST SP 800-63-3: Digital Authentication Guideline <https://pages.nist.gov/800-63-3/>`_
167
+
168
+ For new applications:
169
+
170
+ * `WebAuthn <https://www.w3.org/TR/webauthn/>`_
171
+ * `PyWARP <https://github.com/pyauth/pywarp>`_
172
+
173
+ .. image:: https://github.com/pyauth/pyotp/workflows/Python%20package/badge.svg
174
+ :target: https://github.com/pyauth/pyotp/actions
175
+ .. image:: https://img.shields.io/codecov/c/github/pyauth/pyotp/master.svg
176
+ :target: https://codecov.io/github/pyauth/pyotp?branch=master
177
+ .. image:: https://img.shields.io/pypi/v/pyotp.svg
178
+ :target: https://pypi.python.org/pypi/pyotp
179
+ .. image:: https://img.shields.io/pypi/l/pyotp.svg
180
+ :target: https://pypi.python.org/pypi/pyotp
181
+ .. image:: https://readthedocs.org/projects/pyotp/badge/?version=latest
182
+ :target: https://pyotp.readthedocs.io/
@@ -20,7 +20,7 @@ minimum, application implementers should follow this checklist:
20
20
  - Ensure HOTP/TOTP secret confidentiality by storing secrets in a controlled access database
21
21
  - Deny replay attacks by rejecting one-time passwords that have been used by the client (this requires storing the most
22
22
  recently authenticated timestamp, OTP, or hash of the OTP in your database, and rejecting the OTP when a match is seen)
23
- - Throttle brute-force attacks against your application's login functionality
23
+ - Throttle (rate limit) brute-force attacks against your application's login functionality
24
24
  - When implementing a "greenfield" application, consider supporting
25
25
  `FIDO U2F <https://en.wikipedia.org/wiki/Universal_2nd_Factor>`_/`WebAuthn <https://www.w3.org/TR/webauthn/>`_ in
26
26
  addition to HOTP/TOTP. U2F uses asymmetric cryptography to avoid using a shared secret design, which strengthens your
@@ -78,13 +78,13 @@ Counter-based OTPs
78
78
 
79
79
  Generating a Secret Key
80
80
  ~~~~~~~~~~~~~~~~~~~~~~~
81
- A helper function is provided to generate a 16 character base32 secret, compatible with Google Authenticator and other OTP apps::
81
+ A helper function is provided to generate a 32-character base32 secret, compatible with Google Authenticator and other OTP apps::
82
82
 
83
83
  pyotp.random_base32()
84
84
 
85
85
  Some applications want the secret key to be formatted as a hex-encoded string::
86
86
 
87
- pyotp.random_hex() # returns a 32-character hex-encoded secret
87
+ pyotp.random_hex() # returns a 40-character hex-encoded secret
88
88
 
89
89
  Google Authenticator Compatible
90
90
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -100,7 +100,7 @@ ability to generate provisioning URIs for use with the QR Code scanner built int
100
100
 
101
101
  >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
102
102
 
103
- This URL can then be rendered as a QR Code (for example, using https://github.com/neocotic/qrious) which can then be scanned
103
+ This URL can then be rendered as a QR Code (for example, using https://github.com/soldair/node-qrcode) which can then be scanned
104
104
  and added to the users list of OTP credentials.
105
105
 
106
106
  Parsing these URLs is also supported::
@@ -0,0 +1,5 @@
1
+ [tool.black]
2
+ line-length = 120
3
+ [tool.isort]
4
+ profile = "black"
5
+ line_length = 120
@@ -1,9 +1,6 @@
1
- [bdist_wheel]
2
- universal = 1
3
-
4
1
  [flake8]
5
2
  max-line-length = 120
6
- ignore = E401, W504
3
+ extend-ignore = E203
7
4
 
8
5
  [egg_info]
9
6
  tag_build =
@@ -1,21 +1,19 @@
1
1
  #!/usr/bin/env python
2
2
 
3
- import os
4
3
  from setuptools import setup
5
4
 
6
- install_requires = [line.rstrip() for line in open(os.path.join(os.path.dirname(__file__), "requirements.txt"))]
7
-
8
5
  setup(
9
6
  name="pyotp",
10
- version="2.5.1",
7
+ version="2.7.0",
11
8
  url="https://github.com/pyotp/pyotp",
12
9
  license="MIT License",
13
10
  author="PyOTP contributors",
14
11
  author_email="kislyuk@gmail.com",
15
12
  description="Python One Time Password Library",
16
13
  long_description=open("README.rst").read(),
17
- install_requires=install_requires,
18
- packages=["pyotp"],
14
+ python_requires=">=3.6",
15
+ install_requires=[],
16
+ packages=["pyotp", "pyotp.contrib"],
19
17
  package_dir={"": "src"},
20
18
  package_data={"pyotp": ["py.typed"]},
21
19
  platforms=["MacOS X", "Posix"],
@@ -27,10 +25,12 @@ setup(
27
25
  "Operating System :: MacOS :: MacOS X",
28
26
  "Operating System :: POSIX",
29
27
  "Programming Language :: Python",
30
- "Programming Language :: Python :: 3.4",
31
- "Programming Language :: Python :: 3.5",
28
+ "Programming Language :: Python :: 3",
32
29
  "Programming Language :: Python :: 3.6",
33
30
  "Programming Language :: Python :: 3.7",
34
- "Topic :: Software Development :: Libraries :: Python Modules"
35
- ]
31
+ "Programming Language :: Python :: 3.8",
32
+ "Programming Language :: Python :: 3.9",
33
+ "Programming Language :: Python :: 3.10",
34
+ "Topic :: Software Development :: Libraries :: Python Modules",
35
+ ],
36
36
  )
@@ -0,0 +1,98 @@
1
+ import hashlib
2
+ from re import split
3
+ from typing import Any, Dict, Sequence
4
+ from urllib.parse import parse_qsl, unquote, urlparse
5
+
6
+ from . import contrib # noqa:F401
7
+ from .compat import random
8
+ from .hotp import HOTP as HOTP
9
+ from .otp import OTP as OTP
10
+ from .totp import TOTP as TOTP
11
+
12
+
13
+ def random_base32(length: int = 32, chars: Sequence[str] = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")) -> str:
14
+ # Note: the otpauth scheme DOES NOT use base32 padding for secret lengths not divisible by 8.
15
+ # Some third-party tools have bugs when dealing with such secrets.
16
+ # We might consider warning the user when generating a secret of length not divisible by 8.
17
+ if length < 32:
18
+ raise ValueError("Secrets should be at least 160 bits")
19
+
20
+ return "".join(random.choice(chars) for _ in range(length))
21
+
22
+
23
+ def random_hex(length: int = 40, chars: Sequence[str] = list("ABCDEF0123456789")) -> str:
24
+ if length < 40:
25
+ raise ValueError("Secrets should be at least 160 bits")
26
+ return random_base32(length=length, chars=chars)
27
+
28
+
29
+ def parse_uri(uri: str) -> OTP:
30
+ """
31
+ Parses the provisioning URI for the OTP; works for either TOTP or HOTP.
32
+
33
+ See also:
34
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
35
+
36
+ :param uri: the hotp/totp URI to parse
37
+ :returns: OTP object
38
+ """
39
+
40
+ # Secret (to be filled in later)
41
+ secret = None
42
+
43
+ # Data we'll parse to the correct constructor
44
+ otp_data = {} # type: Dict[str, Any]
45
+
46
+ # Parse with URLlib
47
+ parsed_uri = urlparse(unquote(uri))
48
+
49
+ if parsed_uri.scheme != "otpauth":
50
+ raise ValueError("Not an otpauth URI")
51
+
52
+ # Parse issuer/accountname info
53
+ accountinfo_parts = split(":|%3A", parsed_uri.path[1:], maxsplit=1)
54
+ if len(accountinfo_parts) == 1:
55
+ otp_data["name"] = accountinfo_parts[0]
56
+ else:
57
+ otp_data["issuer"] = accountinfo_parts[0]
58
+ otp_data["name"] = accountinfo_parts[1]
59
+
60
+ # Parse values
61
+ for key, value in parse_qsl(parsed_uri.query):
62
+ if key == "secret":
63
+ secret = value
64
+ elif key == "issuer":
65
+ if "issuer" in otp_data and otp_data["issuer"] is not None and otp_data["issuer"] != value:
66
+ raise ValueError("If issuer is specified in both label and parameters, it should be equal.")
67
+ otp_data["issuer"] = value
68
+ elif key == "algorithm":
69
+ if value == "SHA1":
70
+ otp_data["digest"] = hashlib.sha1
71
+ elif value == "SHA256":
72
+ otp_data["digest"] = hashlib.sha256
73
+ elif value == "SHA512":
74
+ otp_data["digest"] = hashlib.sha512
75
+ else:
76
+ raise ValueError("Invalid value for algorithm, must be SHA1, SHA256 or SHA512")
77
+ elif key == "digits":
78
+ digits = int(value)
79
+ if digits not in [6, 7, 8]:
80
+ raise ValueError("Digits may only be 6, 7, or 8")
81
+ otp_data["digits"] = digits
82
+ elif key == "period":
83
+ otp_data["interval"] = int(value)
84
+ elif key == "counter":
85
+ otp_data["initial_count"] = int(value)
86
+ elif key != "image":
87
+ raise ValueError("{} is not a valid parameter".format(key))
88
+
89
+ if not secret:
90
+ raise ValueError("No secret found in URI")
91
+
92
+ # Create objects
93
+ if parsed_uri.netloc == "totp":
94
+ return TOTP(secret, **otp_data)
95
+ elif parsed_uri.netloc == "hotp":
96
+ return HOTP(secret, **otp_data)
97
+
98
+ raise ValueError("Not a supported OTP type")
@@ -0,0 +1 @@
1
+ from .steam import Steam # noqa:F401
@@ -0,0 +1,42 @@
1
+ import hashlib
2
+ from typing import Optional
3
+
4
+ from ..totp import TOTP
5
+
6
+ STEAM_CHARS = "23456789BCDFGHJKMNPQRTVWXY" # steam's custom alphabet
7
+ STEAM_DEFAULT_DIGITS = 5 # Steam TOTP code length
8
+
9
+
10
+ class Steam(TOTP):
11
+ """
12
+ Steam's custom TOTP. Subclass of `pyotp.totp.TOTP`.
13
+ """
14
+
15
+ def __init__(self, s: str, name: Optional[str] = None, issuer: Optional[str] = None, interval: int = 30) -> None:
16
+ """
17
+ :param s: secret in base32 format
18
+ :param interval: the time interval in seconds for OTP. This defaults to 30.
19
+ :param name: account name
20
+ :param issuer: issuer
21
+ """
22
+ self.interval = interval
23
+ super().__init__(s=s, digits=10, digest=hashlib.sha1, name=name, issuer=issuer)
24
+
25
+ def generate_otp(self, input: int) -> str:
26
+ """
27
+ :param input: the HMAC counter value to use as the OTP input.
28
+ Usually either the counter, or the computed integer based on the Unix timestamp
29
+ """
30
+ str_code = super().generate_otp(input)
31
+ int_code = int(str_code)
32
+
33
+ steam_code = ""
34
+ total_chars = len(STEAM_CHARS)
35
+
36
+ for _ in range(STEAM_DEFAULT_DIGITS):
37
+ pos = int_code % total_chars
38
+ char = STEAM_CHARS[int(pos)]
39
+ steam_code += char
40
+ int_code //= total_chars
41
+
42
+ return steam_code
@@ -9,8 +9,16 @@ class HOTP(OTP):
9
9
  """
10
10
  Handler for HMAC-based OTP counters.
11
11
  """
12
- def __init__(self, s: str, digits: int = 6, digest: Any = hashlib.sha1, name: Optional[str] = None,
13
- issuer: Optional[str] = None, initial_count: int = 0) -> None:
12
+
13
+ def __init__(
14
+ self,
15
+ s: str,
16
+ digits: int = 6,
17
+ digest: Any = hashlib.sha1,
18
+ name: Optional[str] = None,
19
+ issuer: Optional[str] = None,
20
+ initial_count: int = 0,
21
+ ) -> None:
14
22
  """
15
23
  :param s: secret in base32 format
16
24
  :param initial_count: starting HMAC counter value, defaults to 0
@@ -41,11 +49,12 @@ class HOTP(OTP):
41
49
  return utils.strings_equal(str(otp), str(self.at(counter)))
42
50
 
43
51
  def provisioning_uri(
44
- self,
45
- name: Optional[str] = None,
46
- initial_count: Optional[int] = None,
47
- issuer_name: Optional[str] = None,
48
- image: Optional[str] = None) -> str:
52
+ self,
53
+ name: Optional[str] = None,
54
+ initial_count: Optional[int] = None,
55
+ issuer_name: Optional[str] = None,
56
+ image: Optional[str] = None,
57
+ ) -> str:
49
58
  """
50
59
  Returns the provisioning URI for the OTP. This can then be
51
60
  encoded in a QR Code and used to provision an OTP app like
@@ -8,12 +8,19 @@ class OTP(object):
8
8
  """
9
9
  Base class for OTP handlers.
10
10
  """
11
- def __init__(self, s: str, digits: int = 6, digest: Any = hashlib.sha1, name: Optional[str] = None,
12
- issuer: Optional[str] = None) -> None:
11
+
12
+ def __init__(
13
+ self,
14
+ s: str,
15
+ digits: int = 6,
16
+ digest: Any = hashlib.sha1,
17
+ name: Optional[str] = None,
18
+ issuer: Optional[str] = None,
19
+ ) -> None:
13
20
  self.digits = digits
14
21
  self.digest = digest
15
22
  self.secret = s
16
- self.name = name or 'Secret'
23
+ self.name = name or "Secret"
17
24
  self.issuer = issuer
18
25
 
19
26
  def generate_otp(self, input: int) -> str:
@@ -22,25 +29,28 @@ class OTP(object):
22
29
  Usually either the counter, or the computed integer based on the Unix timestamp
23
30
  """
24
31
  if input < 0:
25
- raise ValueError('input must be positive integer')
32
+ raise ValueError("input must be positive integer")
26
33
  hasher = hmac.new(self.byte_secret(), self.int_to_bytestring(input), self.digest)
27
34
  hmac_hash = bytearray(hasher.digest())
28
- offset = hmac_hash[-1] & 0xf
29
- code = ((hmac_hash[offset] & 0x7f) << 24 |
30
- (hmac_hash[offset + 1] & 0xff) << 16 |
31
- (hmac_hash[offset + 2] & 0xff) << 8 |
32
- (hmac_hash[offset + 3] & 0xff))
33
- str_code = str(code % 10 ** self.digits)
35
+ offset = hmac_hash[-1] & 0xF
36
+ code = (
37
+ (hmac_hash[offset] & 0x7F) << 24
38
+ | (hmac_hash[offset + 1] & 0xFF) << 16
39
+ | (hmac_hash[offset + 2] & 0xFF) << 8
40
+ | (hmac_hash[offset + 3] & 0xFF)
41
+ )
42
+ str_code = str(code % 10**self.digits)
34
43
  while len(str_code) < self.digits:
35
- str_code = '0' + str_code
44
+ str_code = "0" + str_code
36
45
 
37
46
  return str_code
38
47
 
39
48
  def byte_secret(self) -> bytes:
40
- missing_padding = len(self.secret) % 8
49
+ secret = self.secret
50
+ missing_padding = len(secret) % 8
41
51
  if missing_padding != 0:
42
- self.secret += '=' * (8 - missing_padding)
43
- return base64.b32decode(self.secret, casefold=True)
52
+ secret += "=" * (8 - missing_padding)
53
+ return base64.b32decode(secret, casefold=True)
44
54
 
45
55
  @staticmethod
46
56
  def int_to_bytestring(i: int, padding: int = 8) -> bytes:
@@ -56,4 +66,4 @@ class OTP(object):
56
66
  # It's necessary to convert the final result from bytearray to bytes
57
67
  # because the hmac functions in python 2.6 and 3.3 don't work with
58
68
  # bytearray
59
- return bytes(bytearray(reversed(result)).rjust(padding, b'\0'))
69
+ return bytes(bytearray(reversed(result)).rjust(padding, b"\0"))
@@ -2,7 +2,7 @@ import calendar
2
2
  import datetime
3
3
  import hashlib
4
4
  import time
5
- from typing import Any, Union, Optional
5
+ from typing import Any, Optional, Union
6
6
 
7
7
  from . import utils
8
8
  from .otp import OTP
@@ -12,8 +12,16 @@ class TOTP(OTP):
12
12
  """
13
13
  Handler for time-based OTP counters.
14
14
  """
15
- def __init__(self, s: str, digits: int = 6, digest: Any = hashlib.sha1, name: Optional[str] = None,
16
- issuer: Optional[str] = None, interval: int = 30) -> None:
15
+
16
+ def __init__(
17
+ self,
18
+ s: str,
19
+ digits: int = 6,
20
+ digest: Any = hashlib.sha1,
21
+ name: Optional[str] = None,
22
+ issuer: Optional[str] = None,
23
+ interval: int = 30,
24
+ ) -> None:
17
25
  """
18
26
  :param s: secret in base32 format
19
27
  :param interval: the time interval in seconds for OTP. This defaults to 30.
@@ -70,8 +78,9 @@ class TOTP(OTP):
70
78
 
71
79
  return utils.strings_equal(str(otp), str(self.at(for_time)))
72
80
 
73
- def provisioning_uri(self, name: Optional[str] = None, issuer_name: Optional[str] = None,
74
- image: Optional[str] = None) -> str:
81
+ def provisioning_uri(
82
+ self, name: Optional[str] = None, issuer_name: Optional[str] = None, image: Optional[str] = None
83
+ ) -> str:
75
84
 
76
85
  """
77
86
  Returns the provisioning URI for the OTP. This can then be
@@ -82,10 +91,15 @@ class TOTP(OTP):
82
91
  https://github.com/google/google-authenticator/wiki/Key-Uri-Format
83
92
 
84
93
  """
85
- return utils.build_uri(self.secret, name if name else self.name,
86
- issuer=issuer_name if issuer_name else self.issuer,
87
- algorithm=self.digest().name,
88
- digits=self.digits, period=self.interval, image=image)
94
+ return utils.build_uri(
95
+ self.secret,
96
+ name if name else self.name,
97
+ issuer=issuer_name if issuer_name else self.issuer,
98
+ algorithm=self.digest().name,
99
+ digits=self.digits,
100
+ period=self.interval,
101
+ image=image,
102
+ )
89
103
 
90
104
  def timecode(self, for_time: datetime.datetime) -> int:
91
105
  """