PyOTP 2.7.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,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")
pyotp/compat.py ADDED
@@ -0,0 +1,7 @@
1
+ # Use secrets module if available (Python version >= 3.6) per PEP 506
2
+ try:
3
+ from secrets import SystemRandom # type: ignore
4
+ except ImportError:
5
+ from random import SystemRandom
6
+
7
+ random = SystemRandom()
@@ -0,0 +1 @@
1
+ from .steam import Steam # noqa:F401
pyotp/contrib/steam.py ADDED
@@ -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
pyotp/hotp.py ADDED
@@ -0,0 +1,80 @@
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 = hashlib.sha1,
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
+ self.initial_count = initial_count
31
+ super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
32
+
33
+ def at(self, count: int) -> str:
34
+ """
35
+ Generates the OTP for the given count.
36
+
37
+ :param count: the OTP HMAC counter
38
+ :returns: OTP
39
+ """
40
+ return self.generate_otp(self.initial_count + count)
41
+
42
+ def verify(self, otp: str, counter: int) -> bool:
43
+ """
44
+ Verifies the OTP passed in against the current counter OTP.
45
+
46
+ :param otp: the OTP to check against
47
+ :param counter: the OTP HMAC counter
48
+ """
49
+ return utils.strings_equal(str(otp), str(self.at(counter)))
50
+
51
+ def provisioning_uri(
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:
58
+ """
59
+ Returns the provisioning URI for the OTP. This can then be
60
+ encoded in a QR Code and used to provision an OTP app like
61
+ Google Authenticator.
62
+
63
+ See also:
64
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
65
+
66
+ :param name: name of the user account
67
+ :param initial_count: starting HMAC counter value, defaults to 0
68
+ :param issuer_name: the name of the OTP issuer; this will be the
69
+ organization title of the OTP entry in Authenticator
70
+ :returns: provisioning URI
71
+ """
72
+ return utils.build_uri(
73
+ self.secret,
74
+ name=name if name else self.name,
75
+ initial_count=initial_count if initial_count else self.initial_count,
76
+ issuer=issuer_name if issuer_name else self.issuer,
77
+ algorithm=self.digest().name,
78
+ digits=self.digits,
79
+ image=image,
80
+ )
pyotp/otp.py ADDED
@@ -0,0 +1,69 @@
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
+ self.digest = digest
22
+ self.secret = s
23
+ self.name = name or "Secret"
24
+ self.issuer = issuer
25
+
26
+ def generate_otp(self, input: int) -> str:
27
+ """
28
+ :param input: the HMAC counter value to use as the OTP input.
29
+ Usually either the counter, or the computed integer based on the Unix timestamp
30
+ """
31
+ if input < 0:
32
+ raise ValueError("input must be positive integer")
33
+ hasher = hmac.new(self.byte_secret(), self.int_to_bytestring(input), self.digest)
34
+ hmac_hash = bytearray(hasher.digest())
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)
43
+ while len(str_code) < self.digits:
44
+ str_code = "0" + str_code
45
+
46
+ return str_code
47
+
48
+ def byte_secret(self) -> bytes:
49
+ secret = self.secret
50
+ missing_padding = len(secret) % 8
51
+ if missing_padding != 0:
52
+ secret += "=" * (8 - missing_padding)
53
+ return base64.b32decode(secret, casefold=True)
54
+
55
+ @staticmethod
56
+ def int_to_bytestring(i: int, padding: int = 8) -> bytes:
57
+ """
58
+ Turns an integer to the OATH specified
59
+ bytestring, which is fed to the HMAC
60
+ along with the secret
61
+ """
62
+ result = bytearray()
63
+ while i != 0:
64
+ result.append(i & 0xFF)
65
+ i >>= 8
66
+ # It's necessary to convert the final result from bytearray to bytes
67
+ # because the hmac functions in python 2.6 and 3.3 don't work with
68
+ # bytearray
69
+ return bytes(bytearray(reversed(result)).rjust(padding, b"\0"))
pyotp/py.typed ADDED
File without changes
pyotp/totp.py ADDED
@@ -0,0 +1,114 @@
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 = hashlib.sha1,
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 interval: the time interval in seconds for OTP. This defaults to 30.
28
+ :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more.
29
+ :param digest: digest function to use in the HMAC (expected to be sha1)
30
+ :param name: account name
31
+ :param issuer: issuer
32
+ """
33
+ self.interval = interval
34
+ super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer)
35
+
36
+ def at(self, for_time: Union[int, datetime.datetime], counter_offset: int = 0) -> str:
37
+ """
38
+ Accepts either a Unix timestamp integer or a datetime object.
39
+
40
+ To get the time until the next timecode change (seconds until the current OTP expires), use this instead::
41
+
42
+ totp = pyotp.TOTP(...)
43
+ time_remaining = totp.interval - datetime.datetime.now().timestamp() % totp.interval
44
+
45
+ :param for_time: the time to generate an OTP for
46
+ :param counter_offset: the amount of ticks to add to the time counter
47
+ :returns: OTP value
48
+ """
49
+ if not isinstance(for_time, datetime.datetime):
50
+ for_time = datetime.datetime.fromtimestamp(int(for_time))
51
+ return self.generate_otp(self.timecode(for_time) + counter_offset)
52
+
53
+ def now(self) -> str:
54
+ """
55
+ Generate the current time OTP
56
+
57
+ :returns: OTP value
58
+ """
59
+ return self.generate_otp(self.timecode(datetime.datetime.now()))
60
+
61
+ def verify(self, otp: str, for_time: Optional[datetime.datetime] = None, valid_window: int = 0) -> bool:
62
+ """
63
+ Verifies the OTP passed in against the current time OTP.
64
+
65
+ :param otp: the OTP to check against
66
+ :param for_time: Time to check OTP at (defaults to now)
67
+ :param valid_window: extends the validity to this many counter ticks before and after the current one
68
+ :returns: True if verification succeeded, False otherwise
69
+ """
70
+ if for_time is None:
71
+ for_time = datetime.datetime.now()
72
+
73
+ if valid_window:
74
+ for i in range(-valid_window, valid_window + 1):
75
+ if utils.strings_equal(str(otp), str(self.at(for_time, i))):
76
+ return True
77
+ return False
78
+
79
+ return utils.strings_equal(str(otp), str(self.at(for_time)))
80
+
81
+ def provisioning_uri(
82
+ self, name: Optional[str] = None, issuer_name: Optional[str] = None, image: Optional[str] = None
83
+ ) -> str:
84
+
85
+ """
86
+ Returns the provisioning URI for the OTP. This can then be
87
+ encoded in a QR Code and used to provision an OTP app like
88
+ Google Authenticator.
89
+
90
+ See also:
91
+ https://github.com/google/google-authenticator/wiki/Key-Uri-Format
92
+
93
+ """
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
+ )
103
+
104
+ def timecode(self, for_time: datetime.datetime) -> int:
105
+ """
106
+ Accepts either a timezone naive (`for_time.tzinfo is None`) or
107
+ a timezone aware datetime as argument and returns the
108
+ corresponding counter value (timecode).
109
+
110
+ """
111
+ if for_time.tzinfo:
112
+ return int(calendar.timegm(for_time.utctimetuple()) / self.interval)
113
+ else:
114
+ return int(time.mktime(for_time.timetuple()) / self.interval)
pyotp/utils.py ADDED
@@ -0,0 +1,88 @@
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
+ image: Optional[str] = None,
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 image: optional logo image url
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 = {"secret": secret} # type: Dict[str, Union[None, int, str]]
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
+ if image:
68
+ image_uri = urlparse(image)
69
+ if image_uri.scheme != "https" or not image_uri.netloc or not image_uri.path:
70
+ raise ValueError("{} is not a valid url".format(image_uri))
71
+ url_args["image"] = image
72
+
73
+ uri = base_uri.format(otp_type, label, urlencode(url_args).replace("+", "%20"))
74
+ return uri
75
+
76
+
77
+ def strings_equal(s1: str, s2: str) -> bool:
78
+ """
79
+ Timing-attack resistant string comparison.
80
+
81
+ Normal comparison using == will short-circuit on the first mismatching
82
+ character. This avoids that by scanning the whole string, though we
83
+ still reveal to a timing attack whether the strings are the same
84
+ length.
85
+ """
86
+ s1 = unicodedata.normalize("NFKC", s1)
87
+ s2 = unicodedata.normalize("NFKC", s2)
88
+ return compare_digest(s1.encode("utf-8"), s2.encode("utf-8"))
@@ -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.
@@ -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/
@@ -0,0 +1,14 @@
1
+ pyotp/__init__.py,sha256=THa-gEq1SxMZ_kVWKkLrq9xxwLe0djEFh4AL4Xr4lX8,3500
2
+ pyotp/compat.py,sha256=i-pxcRWpShxkMTMucqPJdPJibYUaVtEhL9pyweKQ84k,209
3
+ pyotp/hotp.py,sha256=IcYFQ3DwlX-cXzWj2flY8WAYEBLlh5itX2BG5kdV6xI,2618
4
+ pyotp/otp.py,sha256=w_2XMUBoHqp_ThTMTzVMwtMkX7735LIdvfPNfMBDfTU,2179
5
+ pyotp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pyotp/totp.py,sha256=rzvePHNoPzCzZ9JYqVRNIiEZx32WoFeEJBrBcHT550M,4017
7
+ pyotp/utils.py,sha256=X9967t-OmHQnSsfkbmp5vTt1E8l69Ye-khWlg_mM8Ww,3128
8
+ pyotp/contrib/__init__.py,sha256=2hKOYyF4NnZ09Rw3FmeoYmk1l7l631cgIpj2kjzbKfw,38
9
+ pyotp/contrib/steam.py,sha256=rzXdY7iGtsVedEepm9UyB2bfFE14d9CYVPNNCfPIEyU,1339
10
+ pyotp-2.7.0.dist-info/LICENSE,sha256=eViFEjNBRYFyqtbr-rMbBxzHtAUkkp5pAWYtXbv1fqM,1174
11
+ pyotp-2.7.0.dist-info/METADATA,sha256=Izwa2gOgIwnklVVbBlCyWoH09aeAecrXw_iGeu5GIxk,8674
12
+ pyotp-2.7.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
13
+ pyotp-2.7.0.dist-info/top_level.txt,sha256=rFDgz6Sm4nbkYk6tlSRiMcJPyYdnY6LcZiAaYTxVc5k,6
14
+ pyotp-2.7.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ pyotp