PyOTP 2.6.0__tar.gz → 2.8.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,3 @@
1
1
  include LICENSE
2
2
  include README.rst
3
- include requirements.txt
4
3
  include test.py
pyotp-2.8.0/PKG-INFO ADDED
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyotp
3
+ Version: 2.8.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.7
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 (see RFC 4226, section 7.3)
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
+ import pyotp
84
+ import time
85
+
86
+ totp = pyotp.TOTP('base32secret3232')
87
+ totp.now() # => '492039'
88
+
89
+ # OTP verified for current time
90
+ totp.verify('492039') # => True
91
+ time.sleep(30)
92
+ totp.verify('492039') # => False
93
+
94
+ Counter-based OTPs
95
+ ~~~~~~~~~~~~~~~~~~
96
+ ::
97
+
98
+ import pyotp
99
+
100
+ hotp = pyotp.HOTP('base32secret3232')
101
+ hotp.at(0) # => '260182'
102
+ hotp.at(1) # => '055283'
103
+ hotp.at(1401) # => '316439'
104
+
105
+ # OTP verified with a counter
106
+ hotp.verify('316439', 1401) # => True
107
+ hotp.verify('316439', 1402) # => False
108
+
109
+ Generating a Secret Key
110
+ ~~~~~~~~~~~~~~~~~~~~~~~
111
+ A helper function is provided to generate a 32-character base32 secret, compatible with Google Authenticator and other OTP apps::
112
+
113
+ pyotp.random_base32()
114
+
115
+ Some applications want the secret key to be formatted as a hex-encoded string::
116
+
117
+ pyotp.random_hex() # returns a 40-character hex-encoded secret
118
+
119
+ Google Authenticator Compatible
120
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
121
+
122
+ PyOTP works with the Google Authenticator iPhone and Android app, as well as other OTP apps like Authy. PyOTP includes the
123
+ ability to generate provisioning URIs for use with the QR Code scanner built into these MFA client apps::
124
+
125
+ pyotp.totp.TOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name='alice@google.com', issuer_name='Secure App')
126
+
127
+ >>> 'otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App'
128
+
129
+ pyotp.hotp.HOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name="alice@google.com", issuer_name="Secure App", initial_count=0)
130
+
131
+ >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
132
+
133
+ This URL can then be rendered as a QR Code (for example, using https://github.com/soldair/node-qrcode) which can then be scanned
134
+ and added to the users list of OTP credentials.
135
+
136
+ Parsing these URLs is also supported::
137
+
138
+ pyotp.parse_uri('otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App')
139
+
140
+ >>> <pyotp.totp.TOTP object at 0xFFFFFFFF>
141
+
142
+ pyotp.parse_uri('otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
143
+
144
+ >>> <pyotp.totp.HOTP object at 0xFFFFFFFF>
145
+
146
+ Working example
147
+ ~~~~~~~~~~~~~~~
148
+
149
+ Scan the following barcode with your phone's OTP app (e.g. Google Authenticator):
150
+
151
+ .. image:: https://chart.apis.google.com/chart?cht=qr&chs=250x250&chl=otpauth%3A%2F%2Ftotp%2Falice%40google.com%3Fsecret%3DJBSWY3DPEHPK3PXP
152
+
153
+ Now run the following and compare the output::
154
+
155
+ import pyotp
156
+ totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
157
+ print("Current OTP:", totp.now())
158
+
159
+ Links
160
+ ~~~~~
161
+
162
+ * `Project home page (GitHub) <https://github.com/pyauth/pyotp>`_
163
+ * `Documentation <https://pyauth.github.io/pyotp/>`_
164
+ * `Package distribution (PyPI) <https://pypi.python.org/pypi/pyotp>`_
165
+ * `Change log <https://github.com/pyauth/pyotp/blob/master/Changes.rst>`_
166
+ * `RFC 4226: HOTP: An HMAC-Based One-Time Password <https://tools.ietf.org/html/rfc4226>`_
167
+ * `RFC 6238: TOTP: Time-Based One-Time Password Algorithm <https://tools.ietf.org/html/rfc6238>`_
168
+ * `ROTP <https://github.com/mdp/rotp>`_ - Original Ruby OTP library by `Mark Percival <https://github.com/mdp>`_
169
+ * `OTPHP <https://github.com/lelag/otphp>`_ - PHP port of ROTP by `Le Lag <https://github.com/lelag>`_
170
+ * `OWASP Authentication Cheat Sheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md>`_
171
+ * `NIST SP 800-63-3: Digital Authentication Guideline <https://pages.nist.gov/800-63-3/>`_
172
+
173
+ For new applications:
174
+
175
+ * `WebAuthn <https://www.w3.org/TR/webauthn/>`_
176
+ * `PyWARP <https://github.com/pyauth/pywarp>`_
177
+
178
+ .. image:: https://github.com/pyauth/pyotp/workflows/Python%20package/badge.svg
179
+ :target: https://github.com/pyauth/pyotp/actions
180
+ .. image:: https://img.shields.io/codecov/c/github/pyauth/pyotp/master.svg
181
+ :target: https://codecov.io/github/pyauth/pyotp?branch=master
182
+ .. image:: https://img.shields.io/pypi/v/pyotp.svg
183
+ :target: https://pypi.python.org/pypi/pyotp
184
+ .. image:: https://img.shields.io/pypi/l/pyotp.svg
185
+ :target: https://pypi.python.org/pypi/pyotp
186
+ .. image:: https://readthedocs.org/projects/pyotp/badge/?version=latest
187
+ :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 (see RFC 4226, section 7.3)
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
@@ -55,6 +55,9 @@ Time-based OTPs
55
55
  ~~~~~~~~~~~~~~~
56
56
  ::
57
57
 
58
+ import pyotp
59
+ import time
60
+
58
61
  totp = pyotp.TOTP('base32secret3232')
59
62
  totp.now() # => '492039'
60
63
 
@@ -67,6 +70,8 @@ Counter-based OTPs
67
70
  ~~~~~~~~~~~~~~~~~~
68
71
  ::
69
72
 
73
+ import pyotp
74
+
70
75
  hotp = pyotp.HOTP('base32secret3232')
71
76
  hotp.at(0) # => '260182'
72
77
  hotp.at(1) # => '055283'
@@ -78,13 +83,13 @@ Counter-based OTPs
78
83
 
79
84
  Generating a Secret Key
80
85
  ~~~~~~~~~~~~~~~~~~~~~~~
81
- A helper function is provided to generate a 16 character base32 secret, compatible with Google Authenticator and other OTP apps::
86
+ A helper function is provided to generate a 32-character base32 secret, compatible with Google Authenticator and other OTP apps::
82
87
 
83
88
  pyotp.random_base32()
84
89
 
85
90
  Some applications want the secret key to be formatted as a hex-encoded string::
86
91
 
87
- pyotp.random_hex() # returns a 32-character hex-encoded secret
92
+ pyotp.random_hex() # returns a 40-character hex-encoded secret
88
93
 
89
94
  Google Authenticator Compatible
90
95
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -100,7 +105,7 @@ ability to generate provisioning URIs for use with the QR Code scanner built int
100
105
 
101
106
  >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
102
107
 
103
- This URL can then be rendered as a QR Code (for example, using https://github.com/neocotic/qrious) which can then be scanned
108
+ 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
109
  and added to the users list of OTP credentials.
105
110
 
106
111
  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.6.0",
7
+ version="2.8.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.7",
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: 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,16 +9,27 @@ 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 = None,
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
17
25
  :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more.
18
- :param digest: digest function to use in the HMAC (expected to be sha1)
26
+ :param digest: digest function to use in the HMAC (expected to be SHA1)
19
27
  :param name: account name
20
28
  :param issuer: issuer
21
29
  """
30
+ if digest is None:
31
+ digest = hashlib.sha1
32
+
22
33
  self.initial_count = initial_count
23
34
  super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
24
35
 
@@ -41,11 +52,12 @@ class HOTP(OTP):
41
52
  return utils.strings_equal(str(otp), str(self.at(counter)))
42
53
 
43
54
  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:
55
+ self,
56
+ name: Optional[str] = None,
57
+ initial_count: Optional[int] = None,
58
+ issuer_name: Optional[str] = None,
59
+ image: Optional[str] = None,
60
+ ) -> str:
49
61
  """
50
62
  Returns the provisioning URI for the OTP. This can then be
51
63
  encoded in a QR Code and used to provision an OTP app like
@@ -8,12 +8,21 @@ 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
21
+ if digits > 10:
22
+ raise ValueError("digits must be no greater than 10")
14
23
  self.digest = digest
15
24
  self.secret = s
16
- self.name = name or 'Secret'
25
+ self.name = name or "Secret"
17
26
  self.issuer = issuer
18
27
 
19
28
  def generate_otp(self, input: int) -> str:
@@ -22,25 +31,24 @@ class OTP(object):
22
31
  Usually either the counter, or the computed integer based on the Unix timestamp
23
32
  """
24
33
  if input < 0:
25
- raise ValueError('input must be positive integer')
34
+ raise ValueError("input must be positive integer")
26
35
  hasher = hmac.new(self.byte_secret(), self.int_to_bytestring(input), self.digest)
27
36
  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)
34
- while len(str_code) < self.digits:
35
- str_code = '0' + str_code
36
-
37
- return str_code
37
+ offset = hmac_hash[-1] & 0xF
38
+ code = (
39
+ (hmac_hash[offset] & 0x7F) << 24
40
+ | (hmac_hash[offset + 1] & 0xFF) << 16
41
+ | (hmac_hash[offset + 2] & 0xFF) << 8
42
+ | (hmac_hash[offset + 3] & 0xFF)
43
+ )
44
+ str_code = str(10_000_000_000 + (code % 10**self.digits))
45
+ return str_code[-self.digits :]
38
46
 
39
47
  def byte_secret(self) -> bytes:
40
48
  secret = self.secret
41
49
  missing_padding = len(secret) % 8
42
50
  if missing_padding != 0:
43
- secret += '=' * (8 - missing_padding)
51
+ secret += "=" * (8 - missing_padding)
44
52
  return base64.b32decode(secret, casefold=True)
45
53
 
46
54
  @staticmethod
@@ -57,4 +65,4 @@ class OTP(object):
57
65
  # It's necessary to convert the final result from bytearray to bytes
58
66
  # because the hmac functions in python 2.6 and 3.3 don't work with
59
67
  # bytearray
60
- return bytes(bytearray(reversed(result)).rjust(padding, b'\0'))
68
+ 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,16 +12,27 @@ 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 = None,
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.
20
28
  :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more.
21
- :param digest: digest function to use in the HMAC (expected to be sha1)
29
+ :param digest: digest function to use in the HMAC (expected to be SHA1)
22
30
  :param name: account name
23
31
  :param issuer: issuer
24
32
  """
33
+ if digest is None:
34
+ digest = hashlib.sha1
35
+
25
36
  self.interval = interval
26
37
  super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
27
38
 
@@ -29,7 +40,9 @@ class TOTP(OTP):
29
40
  """
30
41
  Accepts either a Unix timestamp integer or a datetime object.
31
42
 
32
- To get the time until the next timecode change (seconds until the current OTP expires), use this instead::
43
+ To get the time until the next timecode change (seconds until the current OTP expires), use this instead:
44
+
45
+ .. code:: python
33
46
 
34
47
  totp = pyotp.TOTP(...)
35
48
  time_remaining = totp.interval - datetime.datetime.now().timestamp() % totp.interval
@@ -70,8 +83,9 @@ class TOTP(OTP):
70
83
 
71
84
  return utils.strings_equal(str(otp), str(self.at(for_time)))
72
85
 
73
- def provisioning_uri(self, name: Optional[str] = None, issuer_name: Optional[str] = None,
74
- image: Optional[str] = None) -> str:
86
+ def provisioning_uri(
87
+ self, name: Optional[str] = None, issuer_name: Optional[str] = None, image: Optional[str] = None
88
+ ) -> str:
75
89
 
76
90
  """
77
91
  Returns the provisioning URI for the OTP. This can then be
@@ -82,10 +96,15 @@ class TOTP(OTP):
82
96
  https://github.com/google/google-authenticator/wiki/Key-Uri-Format
83
97
 
84
98
  """
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)
99
+ return utils.build_uri(
100
+ self.secret,
101
+ name if name else self.name,
102
+ issuer=issuer_name if issuer_name else self.issuer,
103
+ algorithm=self.digest().name,
104
+ digits=self.digits,
105
+ period=self.interval,
106
+ image=image,
107
+ )
89
108
 
90
109
  def timecode(self, for_time: datetime.datetime) -> int:
91
110
  """