PyOTP 2.10.0__py3-none-any.whl

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.
pyotp/__init__.py ADDED
@@ -0,0 +1,115 @@
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] = "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] = "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
+ # Encoder (to be filled in later)
44
+ encoder = None
45
+
46
+ # Digits (to be filled in later)
47
+ digits = None
48
+
49
+ # Data we'll parse to the correct constructor
50
+ otp_data: Dict[str, Any] = {}
51
+
52
+ # Parse the URI structure first, then unquote individual components.
53
+ # Unquoting the whole URI before splitting the label would turn an
54
+ # encoded colon (%3A) inside the issuer or account name into a literal
55
+ # ":" and mis-parse the issuer:account separator (see GitHub issue #174).
56
+ parsed_uri = urlparse(uri)
57
+
58
+ if parsed_uri.scheme != "otpauth":
59
+ raise ValueError("Not an otpauth URI")
60
+
61
+ # Parse issuer/accountname info. The label uses a literal ":" as the
62
+ # issuer:account separator; a percent-encoded "%3A" is a colon that is
63
+ # part of the issuer or account name, not a separator. Split on the
64
+ # literal ":" while the components are still percent-encoded, then
65
+ # unquote each component on its own.
66
+ accountinfo_parts = split(":", parsed_uri.path[1:], maxsplit=1)
67
+ if len(accountinfo_parts) == 1:
68
+ otp_data["name"] = unquote(accountinfo_parts[0])
69
+ else:
70
+ otp_data["issuer"] = unquote(accountinfo_parts[0])
71
+ otp_data["name"] = unquote(accountinfo_parts[1])
72
+
73
+ # Parse values
74
+ for key, value in parse_qsl(parsed_uri.query):
75
+ if key == "secret":
76
+ secret = value
77
+ elif key == "issuer":
78
+ if "issuer" in otp_data and otp_data["issuer"] is not None and otp_data["issuer"] != value:
79
+ raise ValueError("If issuer is specified in both label and parameters, it should be equal.")
80
+ otp_data["issuer"] = value
81
+ elif key == "algorithm":
82
+ if value == "SHA1":
83
+ otp_data["digest"] = hashlib.sha1
84
+ elif value == "SHA256":
85
+ otp_data["digest"] = hashlib.sha256
86
+ elif value == "SHA512":
87
+ otp_data["digest"] = hashlib.sha512
88
+ else:
89
+ raise ValueError("Invalid value for algorithm, must be SHA1, SHA256 or SHA512")
90
+ elif key == "encoder":
91
+ encoder = value
92
+ elif key == "digits":
93
+ digits = int(value)
94
+ otp_data["digits"] = digits
95
+ elif key == "period":
96
+ otp_data["interval"] = int(value)
97
+ elif key == "counter":
98
+ otp_data["initial_count"] = int(value)
99
+
100
+ if encoder != "steam":
101
+ if digits is not None and digits not in [6, 7, 8]:
102
+ raise ValueError("Digits may only be 6, 7, or 8")
103
+
104
+ if not secret:
105
+ raise ValueError("No secret found in URI")
106
+
107
+ # Create objects
108
+ if encoder == "steam":
109
+ return contrib.Steam(secret, **otp_data)
110
+ if parsed_uri.netloc == "totp":
111
+ return TOTP(secret, **otp_data)
112
+ elif parsed_uri.netloc == "hotp":
113
+ return HOTP(secret, **otp_data)
114
+
115
+ raise ValueError("Not a supported OTP type")
pyotp/compat.py ADDED
@@ -0,0 +1,9 @@
1
+ import sys
2
+
3
+ # Use secrets module if available (Python version >= 3.6) per PEP 506
4
+ if sys.version_info >= (3, 6):
5
+ from secrets import SystemRandom
6
+ else:
7
+ from random import SystemRandom
8
+
9
+ random = SystemRandom()
@@ -0,0 +1 @@
1
+ from .steam import Steam # noqa:F401
pyotp/contrib/steam.py ADDED
@@ -0,0 +1,40 @@
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__(
16
+ self, s: str, name: Optional[str] = None, issuer: Optional[str] = None, interval: int = 30, digits: int = 5
17
+ ) -> None:
18
+ """
19
+ :param s: secret in base32 format
20
+ :param interval: the time interval in seconds for OTP. This defaults to 30.
21
+ :param name: account name
22
+ :param issuer: issuer
23
+ """
24
+ self.interval = interval
25
+ super().__init__(s=s, digits=10, digest=hashlib.sha1, name=name, issuer=issuer)
26
+
27
+ def generate_otp(self, input: int) -> str:
28
+ """
29
+ :param input: the HMAC counter value to use as the OTP input.
30
+ Usually either the counter, or the computed integer based on the Unix timestamp
31
+ """
32
+ int_code = int(super().generate_otp(input))
33
+ total_chars = len(STEAM_CHARS)
34
+
35
+ digits = []
36
+ for _ in range(STEAM_DEFAULT_DIGITS):
37
+ digits.append(STEAM_CHARS[int_code % total_chars])
38
+ int_code //= total_chars
39
+
40
+ return "".join(digits)
pyotp/hotp.py ADDED
@@ -0,0 +1,85 @@
1
+ import hashlib
2
+ from typing import Any, Optional
3
+
4
+ from . import utils
5
+ from .otp import OTP
6
+
7
+
8
+ class HOTP(OTP):
9
+ """
10
+ Handler for HMAC-based OTP counters.
11
+ """
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:
22
+ """
23
+ :param s: secret in base32 format
24
+ :param initial_count: starting HMAC counter value, defaults to 0
25
+ :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more.
26
+ :param digest: digest function to use in the HMAC (expected to be SHA1)
27
+ :param name: account name
28
+ :param issuer: issuer
29
+ """
30
+ if digest is None:
31
+ digest = hashlib.sha1
32
+ elif digest in [hashlib.md5, hashlib.shake_128]:
33
+ raise ValueError("selected digest function must generate digest size greater than or equals to 18 bytes")
34
+
35
+ self.initial_count = initial_count
36
+ super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
37
+
38
+ def at(self, count: int) -> str:
39
+ """
40
+ Generates the OTP for the given count.
41
+
42
+ :param count: the OTP HMAC counter
43
+ :returns: OTP
44
+ """
45
+ return self.generate_otp(self.initial_count + count)
46
+
47
+ def verify(self, otp: str, counter: int) -> bool:
48
+ """
49
+ Verifies the OTP passed in against the current counter OTP.
50
+
51
+ :param otp: the OTP to check against
52
+ :param counter: the OTP HMAC counter
53
+ """
54
+ return utils.strings_equal(str(otp), str(self.at(counter)))
55
+
56
+ def provisioning_uri(
57
+ self,
58
+ name: Optional[str] = None,
59
+ initial_count: Optional[int] = None,
60
+ issuer_name: Optional[str] = None,
61
+ **kwargs,
62
+ ) -> str:
63
+ """
64
+ Returns the provisioning URI for the OTP. This can then be
65
+ encoded in a QR Code and used to provision an OTP app like
66
+ Google Authenticator.
67
+
68
+ See also:
69
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
70
+
71
+ :param name: name of the user account
72
+ :param initial_count: starting HMAC counter value, defaults to 0
73
+ :param issuer_name: the name of the OTP issuer; this will be the
74
+ organization title of the OTP entry in Authenticator
75
+ :returns: provisioning URI
76
+ """
77
+ return utils.build_uri(
78
+ self.secret,
79
+ name=name if name else self.name,
80
+ initial_count=initial_count if initial_count else self.initial_count,
81
+ issuer=issuer_name if issuer_name else self.issuer,
82
+ algorithm=self.digest().name,
83
+ digits=self.digits,
84
+ **kwargs,
85
+ )
pyotp/otp.py ADDED
@@ -0,0 +1,72 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ from typing import Any, Optional
5
+
6
+
7
+ class OTP(object):
8
+ """
9
+ Base class for OTP handlers.
10
+ """
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:
20
+ self.digits = digits
21
+ if digits > 10:
22
+ raise ValueError("digits must be no greater than 10")
23
+ self.digest = digest
24
+ if digest in [hashlib.md5, hashlib.shake_128]:
25
+ raise ValueError("selected digest function must generate digest size greater than or equals to 18 bytes")
26
+ self.secret = s
27
+ self.name = name or "Secret"
28
+ self.issuer = issuer
29
+
30
+ def generate_otp(self, input: int) -> str:
31
+ """
32
+ :param input: the HMAC counter value to use as the OTP input.
33
+ Usually either the counter, or the computed integer based on the Unix timestamp
34
+ """
35
+ if input < 0:
36
+ raise ValueError("input must be positive integer")
37
+ hasher = hmac.new(self.byte_secret(), self.int_to_bytestring(input), self.digest)
38
+ if hasher.digest_size < 18:
39
+ raise ValueError("digest size is lower than 18 bytes, which will trigger error on otp generation")
40
+ hmac_hash = bytearray(hasher.digest())
41
+ offset = hmac_hash[-1] & 0xF
42
+ code = (
43
+ (hmac_hash[offset] & 0x7F) << 24
44
+ | (hmac_hash[offset + 1] & 0xFF) << 16
45
+ | (hmac_hash[offset + 2] & 0xFF) << 8
46
+ | (hmac_hash[offset + 3] & 0xFF)
47
+ )
48
+ str_code = str(10_000_000_000 + (code % 10**self.digits))
49
+ return str_code[-self.digits :]
50
+
51
+ def byte_secret(self) -> bytes:
52
+ secret = self.secret
53
+ missing_padding = len(secret) % 8
54
+ if missing_padding != 0:
55
+ secret += "=" * (8 - missing_padding)
56
+ return base64.b32decode(secret, casefold=True)
57
+
58
+ @staticmethod
59
+ def int_to_bytestring(i: int, padding: int = 8) -> bytes:
60
+ """
61
+ Turns an integer to the OATH specified
62
+ bytestring, which is fed to the HMAC
63
+ along with the secret
64
+ """
65
+ result = bytearray()
66
+ while i != 0:
67
+ result.append(i & 0xFF)
68
+ i >>= 8
69
+ # It's necessary to convert the final result from bytearray to bytes
70
+ # because the hmac functions in python 2.6 and 3.3 don't work with
71
+ # bytearray
72
+ return bytes(bytearray(reversed(result)).rjust(padding, b"\0"))
pyotp/py.typed ADDED
File without changes
pyotp/totp.py ADDED
@@ -0,0 +1,118 @@
1
+ import calendar
2
+ import datetime
3
+ import hashlib
4
+ import time
5
+ from typing import Any, Optional, Union
6
+
7
+ from . import utils
8
+ from .otp import OTP
9
+
10
+
11
+ class TOTP(OTP):
12
+ """
13
+ Handler for time-based OTP counters.
14
+ """
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:
25
+ """
26
+ :param s: secret in base32 format
27
+ :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more.
28
+ :param digest: digest function to use in the HMAC (expected to be SHA1)
29
+ :param name: account name
30
+ :param issuer: issuer
31
+ :param interval: the time interval in seconds for OTP. This defaults to 30.
32
+ """
33
+ if digest is None:
34
+ digest = hashlib.sha1
35
+ elif digest in [hashlib.md5, hashlib.shake_128]:
36
+ raise ValueError("selected digest function must generate digest size greater than or equals to 18 bytes")
37
+
38
+ self.interval = interval
39
+ super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
40
+
41
+ def at(self, for_time: Union[int, datetime.datetime], counter_offset: int = 0) -> str:
42
+ """
43
+ Accepts either a Unix timestamp integer or a datetime object.
44
+
45
+ To get the time until the next timecode change (seconds until the current OTP expires), use this instead:
46
+
47
+ .. code:: python
48
+
49
+ totp = pyotp.TOTP(...)
50
+ time_remaining = totp.interval - datetime.datetime.now().timestamp() % totp.interval
51
+
52
+ :param for_time: the time to generate an OTP for
53
+ :param counter_offset: the amount of ticks to add to the time counter
54
+ :returns: OTP value
55
+ """
56
+ if not isinstance(for_time, datetime.datetime):
57
+ for_time = datetime.datetime.fromtimestamp(int(for_time))
58
+ return self.generate_otp(self.timecode(for_time) + counter_offset)
59
+
60
+ def now(self) -> str:
61
+ """
62
+ Generate the current time OTP
63
+
64
+ :returns: OTP value
65
+ """
66
+ return self.generate_otp(self.timecode(datetime.datetime.now()))
67
+
68
+ def verify(self, otp: str, for_time: Optional[datetime.datetime] = None, valid_window: int = 0) -> bool:
69
+ """
70
+ Verifies the OTP passed in against the current time OTP.
71
+
72
+ :param otp: the OTP to check against
73
+ :param for_time: Time to check OTP at (defaults to now)
74
+ :param valid_window: extends the validity to this many counter ticks before and after the current one
75
+ :returns: True if verification succeeded, False otherwise
76
+ """
77
+ if for_time is None:
78
+ for_time = datetime.datetime.now()
79
+
80
+ if valid_window:
81
+ for i in range(-valid_window, valid_window + 1):
82
+ if utils.strings_equal(str(otp), str(self.at(for_time, i))):
83
+ return True
84
+ return False
85
+
86
+ return utils.strings_equal(str(otp), str(self.at(for_time)))
87
+
88
+ def provisioning_uri(self, name: Optional[str] = None, issuer_name: Optional[str] = None, **kwargs) -> str:
89
+ """
90
+ Returns the provisioning URI for the OTP. This can then be
91
+ encoded in a QR Code and used to provision an OTP app like
92
+ Google Authenticator.
93
+
94
+ See also:
95
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
96
+
97
+ """
98
+ return utils.build_uri(
99
+ self.secret,
100
+ name if name else self.name,
101
+ issuer=issuer_name if issuer_name else self.issuer,
102
+ algorithm=self.digest().name,
103
+ digits=self.digits,
104
+ period=self.interval,
105
+ **kwargs,
106
+ )
107
+
108
+ def timecode(self, for_time: datetime.datetime) -> int:
109
+ """
110
+ Accepts either a timezone naive (`for_time.tzinfo is None`) or
111
+ a timezone aware datetime as argument and returns the
112
+ corresponding counter value (timecode).
113
+
114
+ """
115
+ if for_time.tzinfo:
116
+ return int(calendar.timegm(for_time.utctimetuple()) / self.interval)
117
+ else:
118
+ return int(time.mktime(for_time.timetuple()) / self.interval)
pyotp/utils.py ADDED
@@ -0,0 +1,91 @@
1
+ import unicodedata
2
+ from hmac import compare_digest
3
+ from typing import Dict, Optional, Union
4
+ from urllib.parse import quote, urlencode, urlparse
5
+
6
+
7
+ def build_uri(
8
+ secret: str,
9
+ name: str,
10
+ initial_count: Optional[int] = None,
11
+ issuer: Optional[str] = None,
12
+ algorithm: Optional[str] = None,
13
+ digits: Optional[int] = None,
14
+ period: Optional[int] = None,
15
+ **kwargs,
16
+ ) -> str:
17
+ """
18
+ Returns the provisioning URI for the OTP; works for either TOTP or HOTP.
19
+
20
+ This can then be encoded in a QR Code and used to provision the Google
21
+ Authenticator app.
22
+
23
+ For module-internal use.
24
+
25
+ See also:
26
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
27
+
28
+ :param secret: the hotp/totp secret used to generate the URI
29
+ :param name: name of the account
30
+ :param initial_count: starting counter value, defaults to None.
31
+ If none, the OTP type will be assumed as TOTP.
32
+ :param issuer: the name of the OTP issuer; this will be the
33
+ organization title of the OTP entry in Authenticator
34
+ :param algorithm: the algorithm used in the OTP generation.
35
+ :param digits: the length of the OTP generated code.
36
+ :param period: the number of seconds the OTP generator is set to
37
+ expire every code.
38
+ :param kwargs: other query string parameters to include in the URI
39
+ :returns: provisioning uri
40
+ """
41
+ # initial_count may be 0 as a valid param
42
+ is_initial_count_present = initial_count is not None
43
+
44
+ # Handling values different from defaults
45
+ is_algorithm_set = algorithm is not None and algorithm != "sha1"
46
+ is_digits_set = digits is not None and digits != 6
47
+ is_period_set = period is not None and period != 30
48
+
49
+ otp_type = "hotp" if is_initial_count_present else "totp"
50
+ base_uri = "otpauth://{0}/{1}?{2}"
51
+
52
+ url_args: Dict[str, Union[None, int, str]] = {"secret": secret}
53
+
54
+ label = quote(name)
55
+ if issuer is not None:
56
+ label = quote(issuer) + ":" + label
57
+ url_args["issuer"] = issuer
58
+
59
+ if is_initial_count_present:
60
+ url_args["counter"] = initial_count
61
+ if is_algorithm_set:
62
+ url_args["algorithm"] = algorithm.upper() # type: ignore
63
+ if is_digits_set:
64
+ url_args["digits"] = digits
65
+ if is_period_set:
66
+ url_args["period"] = period
67
+ for k, v in kwargs.items():
68
+ if not isinstance(v, str):
69
+ raise ValueError("All otpauth uri parameters must be strings")
70
+ if k == "image":
71
+ image_uri = urlparse(v)
72
+ if image_uri.scheme != "https" or not image_uri.netloc or not image_uri.path:
73
+ raise ValueError("{} is not a valid url".format(image_uri))
74
+ url_args[k] = v
75
+
76
+ uri = base_uri.format(otp_type, label, urlencode(url_args).replace("+", "%20"))
77
+ return uri
78
+
79
+
80
+ def strings_equal(s1: str, s2: str) -> bool:
81
+ """
82
+ Timing-attack resistant string comparison.
83
+
84
+ Normal comparison using == will short-circuit on the first mismatching
85
+ character. This avoids that by scanning the whole string, though we
86
+ still reveal to a timing attack whether the strings are the same
87
+ length.
88
+ """
89
+ s1 = unicodedata.normalize("NFKC", s1)
90
+ s2 = unicodedata.normalize("NFKC", s2)
91
+ return compare_digest(s1.encode("utf-8"), s2.encode("utf-8"))
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyOTP
3
+ Version: 2.10.0
4
+ Summary: Python One Time Password Library
5
+ Project-URL: Homepage, https://github.com/pyauth/pyotp
6
+ Project-URL: Documentation, https://github.com/pyauth/pyotp
7
+ Project-URL: Source Code, https://github.com/pyauth/pyotp
8
+ Project-URL: Issue Tracker, https://github.com/pyauth/pyotp/issues
9
+ Project-URL: Change Log, https://github.com/pyauth/pyotp/blob/main/Changes.rst
10
+ Author: Andrey Kislyuk
11
+ Author-email: kislyuk@gmail.com
12
+ Maintainer: Andrey Kislyuk
13
+ Maintainer-email: kislyuk@gmail.com
14
+ License-Expression: MIT
15
+ License-File: LICENSE
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: MacOS :: MacOS X
19
+ Classifier: Operating System :: POSIX
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: Implementation :: CPython
29
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
30
+ Classifier: Topic :: Software Development
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Requires-Python: >=3.8
33
+ Provides-Extra: test
34
+ Requires-Dist: coverage; extra == 'test'
35
+ Requires-Dist: mypy; extra == 'test'
36
+ Requires-Dist: ruff; extra == 'test'
37
+ Requires-Dist: wheel; extra == 'test'
38
+ Description-Content-Type: text/x-rst
39
+
40
+ PyOTP - The Python One-Time Password Library
41
+ ============================================
42
+
43
+ PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement two-factor (2FA)
44
+ or multi-factor (MFA) authentication methods in web applications and in other systems that require users to log in.
45
+
46
+ Open MFA standards are defined in `RFC 4226 <https://tools.ietf.org/html/rfc4226>`_ (HOTP: An HMAC-Based One-Time
47
+ Password Algorithm) and in `RFC 6238 <https://tools.ietf.org/html/rfc6238>`_ (TOTP: Time-Based One-Time Password
48
+ Algorithm). PyOTP implements server-side support for both of these standards. Client-side support can be enabled by
49
+ sending authentication codes to users over SMS or email (HOTP) or, for TOTP, by instructing users to use `Google
50
+ Authenticator <https://en.wikipedia.org/wiki/Google_Authenticator>`_, `Authy <https://www.authy.com/>`_, or another
51
+ compatible app. Users can set up auth tokens in their apps easily by using their phone camera to scan `otpauth://
52
+ <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>`_ QR codes provided by PyOTP.
53
+
54
+ Implementers should read and follow the `HOTP security requirements <https://tools.ietf.org/html/rfc4226#section-7>`_
55
+ and `TOTP security considerations <https://tools.ietf.org/html/rfc6238#section-5>`_ sections of the relevant RFCs. At
56
+ minimum, application implementers should follow this checklist:
57
+
58
+ - Ensure transport confidentiality by using HTTPS
59
+ - Ensure HOTP/TOTP secret confidentiality by storing secrets in a controlled access database
60
+ - Deny replay attacks by rejecting one-time passwords that have been used by the client (this requires storing the most
61
+ recently authenticated timestamp, OTP, or hash of the OTP in your database, and rejecting the OTP when a match is
62
+ seen)
63
+ - Throttle (rate limit) brute-force attacks against your application's login functionality (see RFC 4226, section 7.3)
64
+ - When implementing a "greenfield" application, consider supporting
65
+ `FIDO U2F <https://en.wikipedia.org/wiki/Universal_2nd_Factor>`_/`WebAuthn <https://www.w3.org/TR/webauthn/>`_ in
66
+ addition to or instead of HOTP/TOTP. U2F uses asymmetric cryptography to avoid using a shared secret design, which
67
+ strengthens your MFA solution against server-side attacks. Hardware U2F also sequesters the client secret in a
68
+ dedicated single-purpose device, which strengthens your clients against client-side attacks. And by automating scoping
69
+ of credentials to relying party IDs (application origin/domain names), U2F adds protection against phishing attacks.
70
+ One implementation of FIDO U2F/WebAuthn is PyOTP's sister project, `PyWARP <https://github.com/pyauth/pywarp>`_.
71
+
72
+ We also recommend that implementers read the
73
+ `OWASP Authentication Cheat Sheet
74
+ <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md>`_ and
75
+ `NIST SP 800-63-3: Digital Authentication Guideline <https://pages.nist.gov/800-63-3/>`_ for a high level overview of
76
+ authentication best practices.
77
+
78
+ Quick overview of using One Time Passwords on your phone
79
+ --------------------------------------------------------
80
+
81
+ * OTPs involve a shared secret, stored both on the phone and the server
82
+ * OTPs can be generated on a phone without internet connectivity
83
+ * OTPs should always be used as a second factor of authentication (if your phone is lost, you account is still secured
84
+ with a password)
85
+ * Google Authenticator and other OTP client apps allow you to store multiple OTP secrets and provision those using a QR
86
+ Code
87
+
88
+ Installation
89
+ ------------
90
+ ::
91
+
92
+ pip install pyotp
93
+
94
+ Usage
95
+ -----
96
+
97
+ Time-based OTPs
98
+ ~~~~~~~~~~~~~~~
99
+ ::
100
+
101
+ import pyotp
102
+ import time
103
+
104
+ totp = pyotp.TOTP('base32secret3232')
105
+ totp.now() # => '492039'
106
+
107
+ # OTP verified for current time
108
+ totp.verify('492039') # => True
109
+ time.sleep(30)
110
+ totp.verify('492039') # => False
111
+
112
+ Counter-based OTPs
113
+ ~~~~~~~~~~~~~~~~~~
114
+ ::
115
+
116
+ import pyotp
117
+
118
+ hotp = pyotp.HOTP('base32secret3232')
119
+ hotp.at(0) # => '260182'
120
+ hotp.at(1) # => '055283'
121
+ hotp.at(1401) # => '316439'
122
+
123
+ # OTP verified with a counter
124
+ hotp.verify('316439', 1401) # => True
125
+ hotp.verify('316439', 1402) # => False
126
+
127
+ Generating a Secret Key
128
+ ~~~~~~~~~~~~~~~~~~~~~~~
129
+ A helper function is provided to generate a 32-character base32 secret, compatible with Google Authenticator and other
130
+ OTP apps::
131
+
132
+ pyotp.random_base32()
133
+
134
+ Some applications want the secret key to be formatted as a hex-encoded string::
135
+
136
+ pyotp.random_hex() # returns a 40-character hex-encoded secret
137
+
138
+ Google Authenticator Compatible
139
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
140
+
141
+ PyOTP works with the Google Authenticator iPhone and Android app, as well as other OTP apps like Authy. PyOTP includes
142
+ the ability to generate provisioning URIs for use with the QR Code scanner built into these MFA client apps::
143
+
144
+ pyotp.totp.TOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name='alice@google.com', issuer_name='Secure App')
145
+
146
+ >>> 'otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App'
147
+
148
+ pyotp.hotp.HOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name="alice@google.com", issuer_name="Secure App", initial_count=0)
149
+
150
+ >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
151
+
152
+ This URL can then be rendered as a QR Code (for example, using https://github.com/soldair/node-qrcode) which can then be
153
+ scanned and added to the users list of OTP credentials.
154
+
155
+ Parsing these URLs is also supported::
156
+
157
+ pyotp.parse_uri('otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App')
158
+
159
+ >>> <pyotp.totp.TOTP object at 0xFFFFFFFF>
160
+
161
+ pyotp.parse_uri('otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0'
162
+
163
+ >>> <pyotp.totp.HOTP object at 0xFFFFFFFF>
164
+
165
+ Working example
166
+ ~~~~~~~~~~~~~~~
167
+
168
+ Scan the following barcode with your phone's OTP app (e.g. Google Authenticator):
169
+
170
+ .. image:: https://quickchart.io/qr?size=250&text=otpauth%3A%2F%2Ftotp%2Falice%40google.com%3Fsecret%3DJBSWY3DPEHPK3PXP
171
+
172
+ Now run the following and compare the output::
173
+
174
+ import pyotp
175
+ totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
176
+ print("Current OTP:", totp.now())
177
+
178
+ Third-party contributions
179
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
180
+ The following third-party contributions are not described by a standard, not officially supported, and provided for
181
+ reference only:
182
+
183
+ * ``pyotp.contrib.Steam()``: An implementation of Steam TOTP. Uses the same API as `pyotp.TOTP()`.
184
+
185
+ Links
186
+ ~~~~~
187
+
188
+ * `Project home page (GitHub) <https://github.com/pyauth/pyotp>`_
189
+ * `Documentation <https://pyauth.github.io/pyotp/>`_
190
+ * `Package distribution (PyPI) <https://pypi.python.org/pypi/pyotp>`_
191
+ * `Change log <https://github.com/pyauth/pyotp/blob/master/Changes.rst>`_
192
+ * `RFC 4226: HOTP: An HMAC-Based One-Time Password <https://tools.ietf.org/html/rfc4226>`_
193
+ * `RFC 6238: TOTP: Time-Based One-Time Password Algorithm <https://tools.ietf.org/html/rfc6238>`_
194
+ * `ROTP <https://github.com/mdp/rotp>`_ - Original Ruby OTP library by `Mark Percival <https://github.com/mdp>`_
195
+ * `OTPHP <https://github.com/lelag/otphp>`_ - PHP port of ROTP by `Le Lag <https://github.com/lelag>`_
196
+ * `OWASP Authentication Cheat Sheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md>`_
197
+ * `NIST SP 800-63-3: Digital Authentication Guideline <https://pages.nist.gov/800-63-3/>`_
198
+
199
+ For new applications:
200
+
201
+ * `WebAuthn <https://www.w3.org/TR/webauthn/>`_
202
+ * `PyWARP <https://github.com/pyauth/pywarp>`_
203
+
204
+ Versioning
205
+ ~~~~~~~~~~
206
+ This package follows the `Semantic Versioning 2.0.0 <http://semver.org/>`_ standard. To control changes, it is
207
+ recommended that application developers pin the package version and manage it using `pip-tools
208
+ <https://github.com/jazzband/pip-tools>`_ or similar. For library developers, pinning the major version is
209
+ recommended.
210
+
211
+ .. image:: https://github.com/pyauth/pyotp/workflows/Python%20package/badge.svg
212
+ :target: https://github.com/pyauth/pyotp/actions
213
+ .. image:: https://img.shields.io/codecov/c/github/pyauth/pyotp/master.svg
214
+ :target: https://codecov.io/github/pyauth/pyotp?branch=master
215
+ .. image:: https://img.shields.io/pypi/v/pyotp.svg
216
+ :target: https://pypi.python.org/pypi/pyotp
217
+ .. image:: https://img.shields.io/pypi/l/pyotp.svg
218
+ :target: https://pypi.python.org/pypi/pyotp
219
+ .. image:: https://readthedocs.org/projects/pyotp/badge/?version=latest
220
+ :target: https://pyotp.readthedocs.io/
@@ -0,0 +1,13 @@
1
+ pyotp/__init__.py,sha256=KvbyPLPtAllp_9LfRzvsFAZJRxJGk3MvWIKwsteSJ2M,4254
2
+ pyotp/compat.py,sha256=AB2ImrQE5tA9pUVGWKlKZDU1h5qpZHKGBUCpaRiJ3rY,217
3
+ pyotp/hotp.py,sha256=krBp412C3pkF2caANi8MLJfnzynVn5CJltFDLTF6pwc,2825
4
+ pyotp/otp.py,sha256=rdvDUU7atlf80eOowvZEoIipTrQKyLWrCyx48o6Nwb4,2542
5
+ pyotp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pyotp/totp.py,sha256=eYHhCrWzBLsEjHblnFj2LFi8lyerZgMiy0ND4UhVx6A,4234
7
+ pyotp/utils.py,sha256=I9b_Ys5DLel6NgXiHGq_TE_0SZ01id8j-CTAxniU1Qs,3281
8
+ pyotp/contrib/__init__.py,sha256=2hKOYyF4NnZ09Rw3FmeoYmk1l7l631cgIpj2kjzbKfw,38
9
+ pyotp/contrib/steam.py,sha256=neSbrAjTdX4qb4iqOmmV00g8545GlIkQxIFesJn699M,1292
10
+ pyotp-2.10.0.dist-info/METADATA,sha256=khIilotcerpIDbHpKIVEz2NAcDL63i4ZUxCxnIBlkmE,10149
11
+ pyotp-2.10.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
12
+ pyotp-2.10.0.dist-info/licenses/LICENSE,sha256=eViFEjNBRYFyqtbr-rMbBxzHtAUkkp5pAWYtXbv1fqM,1174
13
+ pyotp-2.10.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ Copyright (C) 2011-2021 Mark Percival <m@mdp.im>,
2
+ Nathan Reynolds <email@nreynolds.co.uk>, Andrey Kislyuk <kislyuk@gmail.com>,
3
+ and PyOTP contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.