├── .codecov.yml ├── .coveragerc ├── .github └── workflows │ ├── ci.yml │ └── deploy-docs.yml ├── .gitignore ├── .travis.yml ├── COPYING ├── LICENSE ├── MANIFEST.in ├── NOTICE ├── README.rst ├── appveyor.yml ├── authenticatorpy ├── __init__.py ├── __main__.py └── authenticator.py ├── docs ├── index.md ├── installation.md └── module │ ├── authenticator.md │ └── cli.md ├── mkdocs.yml ├── requirements.docs.txt ├── requirements.testing.txt ├── setup.cfg ├── setup.py ├── tests └── test_authenticator.py └── tox.ini /.codecov.yml: -------------------------------------------------------------------------------- 1 | # Documentation: https://docs.codecov.io/docs/codecov-yaml 2 | 3 | codecov: 4 | token: "46cea78f-3b4b-4d9e-8409-1ceaa759a738" 5 | require_ci_to_pass: yes 6 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [paths] 2 | source = authenticatorpy/ 3 | [run] 4 | omit = authenticatorpy/__main__.py 5 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: authenticatorpy ci 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ${{ matrix.operating-system }} 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | python-version: [3.5, 3.6, 3.7, 3.8, 3.9, '3.10'] 13 | operating-system: [ubuntu-latest, windows-latest, macos-latest] 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python ${{ matrix.python-version }} 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install -e . 25 | pip install -r requirements.testing.txt 26 | - name: Lint with flake8 27 | run: | 28 | pip install flake8 29 | # stop the build if there are Python syntax errors or undefined names 30 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 31 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 32 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 33 | - name: Test with pytest 34 | run: | 35 | py.test -s -vv --cov-report xml --cov=authenticatorpy tests/ 36 | codecov 37 | - name: Upload coverage to Codecov 38 | uses: codecov/codecov-action@v1 39 | with: 40 | yml: ./.codecov.yml 41 | file: ./coverage.xml 42 | flags: unittests 43 | fail_ci_if_error: true 44 | -------------------------------------------------------------------------------- /.github/workflows/deploy-docs.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy to Netlify 2 | on: 3 | push: 4 | pull_request: 5 | types: [opened, synchronize] 6 | jobs: 7 | build: 8 | runs-on: ubuntu-18.04 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up Python 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: "3.7" 15 | - name: Install Module 16 | run: pip install -e . 17 | - name: Install Dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | pip install -r requirements.docs.txt 21 | pip install livereload 22 | - name: Build Docs 23 | run: mkdocs build 24 | - name: Deploy to Netlify 25 | uses: nwtgck/actions-netlify@v1.0.3 26 | with: 27 | publish-dir: './site' 28 | production-branch: master 29 | github-token: ${{ secrets.PERSONAL_TOKEN }} 30 | env: 31 | NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} 32 | NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # vscode 104 | .vscode/ 105 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.5" 5 | - "3.6" 6 | - "3.7" 7 | - "3.8" 8 | - "3.9" 9 | 10 | # command to install dependencies 11 | install: 12 | - pip install -r requirements.testing.txt --upgrade 13 | - pip install -e . 14 | 15 | # command to run tests 16 | script: 17 | - py.test -s -vv --cov-report xml --cov=authenticatorpy tests/ 18 | - codecov 19 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Abdullah Selek 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Abdullah Selek 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING 2 | include LICENSE 3 | include NOTICE 4 | include *.rst 5 | prune .DS_Store 6 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | NOTICE 2 | 3 | This code is made available under the MIT License and is copyright Abdullah Selek. 4 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | authenticatorpy 2 | =============== 3 | 4 | .. image:: https://github.com/abdullahselek/authenticatorpy/workflows/authenticatorpy%20ci/badge.svg 5 | :target: https://github.com/abdullahselek/authenticatorpy/actions 6 | 7 | .. image:: https://img.shields.io/pypi/v/authenticatorpy.svg 8 | :target: https://pypi.python.org/pypi/authenticatorpy/ 9 | 10 | .. image:: https://img.shields.io/pypi/pyversions/authenticatorpy.svg 11 | :target: https://pypi.org/project/authenticatorpy 12 | 13 | .. image:: https://codecov.io/gh/abdullahselek/authenticatorpy/branch/master/graph/badge.svg 14 | :target: https://codecov.io/gh/abdullahselek/authenticatorpy 15 | 16 | .. image:: https://pepy.tech/badge/authenticatorpy 17 | :target: https://pepy.tech/project/authenticatorpy 18 | 19 | .. image:: https://img.shields.io/conda/vn/conda-forge/authenticatorpy?logo=conda-forge 20 | :target: https://anaconda.org/conda-forge/authenticatorpy 21 | 22 | .. image:: https://anaconda.org/conda-forge/authenticatorpy/badges/latest_release_date.svg 23 | :target: https://anaconda.org/conda-forge/authenticatorpy 24 | 25 | .. image:: https://anaconda.org/conda-forge/authenticatorpy/badges/license.svg 26 | :target: https://anaconda.org/conda-forge/authenticatorpy 27 | 28 | +----------------------------------------------------------------------------------+------------------------------------------------------------------------------------+ 29 | | Linux | Windows | 30 | +==================================================================================+====================================================================================+ 31 | | .. image:: https://travis-ci.org/abdullahselek/authenticatorpy.svg?branch=master | .. image:: https://ci.appveyor.com/api/projects/status/vbbhr6naecm16ljv?svg=true | 32 | | :target: https://travis-ci.org/abdullahselek/authenticatorpy | :target: https://ci.appveyor.com/project/abdullahselek/authenticatorpy | 33 | +----------------------------------------------------------------------------------+------------------------------------------------------------------------------------+ 34 | 35 | Introduction 36 | ============ 37 | 38 | A pure Python library which provides one time password like Google Authenticator. It works with Python versions Python 3.x. 39 | 40 | Installing 41 | ========== 42 | 43 | You can install authenticatorpy using Python Package Index:: 44 | 45 | $ pip install authenticatorpy 46 | 47 | Install with conda from the Anaconda conda-forge channel:: 48 | 49 | $ conda install -c conda-forge authenticatorpy 50 | 51 | Install from its source repository on GitHub:: 52 | 53 | $ pip install -e git+https://github.com/abdullahselek/authenticatorpy#egg=authenticatorpy 54 | 55 | 56 | Getting the code 57 | ================ 58 | 59 | The code is hosted at https://github.com/abdullahselek/authenticatorpy 60 | 61 | Check out the latest development version anonymously with:: 62 | 63 | $ git clone git://github.com/abdullahselek/authenticatorpy.git 64 | $ cd authenticatorpy 65 | 66 | To install test dependencies, run either:: 67 | 68 | $ pip install -Ur requirements.testing.txt 69 | 70 | Running Tests 71 | ============= 72 | 73 | The test suite can be run against a single Python version which requires ``pip install pytest`` and optionally ``pip install pytest-cov`` (these are included if you have installed dependencies from ``requirements.testing.txt``) 74 | 75 | To run the unit tests with a single Python version:: 76 | 77 | $ py.test -v 78 | 79 | to also run code coverage:: 80 | 81 | $ py.test --cov=authenticatorpy 82 | 83 | To run the unit tests against a set of Python versions:: 84 | 85 | $ tox 86 | 87 | Sample Usage 88 | ============ 89 | 90 | Import Authenticator:: 91 | 92 | from authenticatorpy.authenticator import Authenticator 93 | 94 | Initiation:: 95 | 96 | authenticator = Authenticator('abcd xyzw abcd xyzw abcd xyzw abcd xyzw') 97 | password = authenticator.one_time_password() 98 | 99 | And that's it, you have the unique password. 100 | 101 | Command Line Usage 102 | ================== 103 | 104 | With ``--secret`` parameter default 30 seconds regeneration interval:: 105 | 106 | python -m authenticatorpy --secret 'abcd xyzw abcd xyzw abcd xyzw abcd xyzw' 107 | 108 | or additional ``--time`` parameter:: 109 | 110 | python -m authenticatorpy --secret 'abcd xyzw abcd xyzw abcd xyzw abcd xyzw' --time 15 111 | 112 | Relevant RFCs 113 | ------------- 114 | 115 | | `RFC4226 `_ 116 | | `RFC6238 `_ 117 | 118 | License 119 | ------- 120 | 121 | MIT License 122 | 123 | Copyright (c) 2018 Abdullah Selek 124 | 125 | Permission is hereby granted, free of charge, to any person obtaining a copy 126 | of this software and associated documentation files (the “Software”), to deal 127 | in the Software without restriction, including without limitation the rights 128 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 129 | copies of the Software, and to permit persons to whom the Software is 130 | furnished to do so, subject to the following conditions: 131 | 132 | The above copyright notice and this permission notice shall be included in all 133 | copies or substantial portions of the Software. 134 | 135 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 136 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 137 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 138 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 139 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 140 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 141 | SOFTWARE. 142 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | 3 | matrix: 4 | 5 | - PYTHON: "C:\\Python35" 6 | - PYTHON: "C:\\Python35-x64" 7 | - PYTHON: "C:\\Python36-x64" 8 | - PYTHON: "C:\\Python37" 9 | - PYTHON: "C:\\Python37-x64" 10 | - PYTHON: "C:\\Python38" 11 | - PYTHON: "C:\\Python38-x64" 12 | - PYTHON: "C:\\Python39" 13 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 14 | - PYTHON: "C:\\Python39-x64" 15 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 16 | 17 | install: 18 | # We need wheel installed to build wheels 19 | - "%PYTHON%\\python.exe -m pip install wheel" 20 | - "%PYTHON%\\python.exe -m pip install -r requirements.testing.txt" 21 | - "%PYTHON%\\python.exe -m pip install -e ." 22 | 23 | build: off 24 | 25 | test_script: 26 | - "%PYTHON%\\python.exe -m pytest -s -vv --cov-report xml --cov=authenticatorpy" 27 | 28 | after_test: 29 | # This step builds your wheels. 30 | # Again, you only need build.cmd if you're building C extensions for 31 | # 64-bit Python 3.3/3.4. And you need to use %PYTHON% to get the correct 32 | # interpreter 33 | - "%PYTHON%\\python.exe setup.py bdist_wheel" 34 | 35 | artifacts: 36 | # bdist_wheel puts your built wheel in the dist directory 37 | - path: dist\* 38 | -------------------------------------------------------------------------------- /authenticatorpy/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """A Python library that provide unique keys for 2FA with given secret.""" 4 | 5 | from __future__ import absolute_import 6 | 7 | __author__ = "Abdullah Selek" 8 | __email__ = "abdullahselek.os@gmail.com" 9 | __copyright__ = "Copyright (c) 2018 Abdullah Selek" 10 | __license__ = "MIT License" 11 | __version__ = "0.3.1" 12 | __url__ = "https://github.com/abdullahselek/authenticatorpy" 13 | __download_url__ = "https://pypi.org/pypi/authenticatorpy" 14 | __description__ = "A Python library that provide unique keys for 2FA with given secret." 15 | 16 | 17 | from authenticatorpy import authenticator 18 | -------------------------------------------------------------------------------- /authenticatorpy/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import argparse 5 | import sched 6 | import time 7 | 8 | from authenticatorpy.authenticator import Authenticator 9 | 10 | 11 | def create_one_time_password(scheduler, authenticator, sleep_time): 12 | scheduler.enter( 13 | sleep_time, 0, create_one_time_password, (scheduler, authenticator, sleep_time) 14 | ) 15 | print(authenticator.one_time_password(sleep_time)) 16 | 17 | 18 | if __name__ == "__main__": 19 | 20 | parser = argparse.ArgumentParser(description="Authenticator 2FA token generator") 21 | parser.add_argument("--secret", type=str, help="secret string for user") 22 | parser.add_argument( 23 | "--time", 24 | type=int, 25 | help="optional delay to generate another new token (default 30 seconds)", 26 | ) 27 | args = parser.parse_args() 28 | 29 | if len(sys.argv) < 2: 30 | print("Specify a secret key to use") 31 | sys.exit(1) 32 | 33 | # Optional bash tab completion support 34 | try: 35 | import argcomplete 36 | 37 | argcomplete.autocomplete(parser) 38 | except ImportError: 39 | pass 40 | 41 | secret = sys.argv[2] 42 | authenticator = Authenticator(secret) 43 | 44 | sleep_time = 30 45 | if len(sys.argv) > 4: 46 | sleep_time = float(sys.argv[4]) 47 | 48 | scheduler = sched.scheduler(time.time, time.sleep) 49 | scheduler.enter( 50 | 0, 0, create_one_time_password, (scheduler, authenticator, sleep_time) 51 | ) 52 | scheduler.run() 53 | -------------------------------------------------------------------------------- /authenticatorpy/authenticator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import base64 5 | import time 6 | import hashlib 7 | import binascii 8 | import re 9 | 10 | 11 | class Authenticator(object): 12 | """Authenticator class which generates unique one time use password.""" 13 | 14 | def __init__(self, secret: str): 15 | """Creates a new Authenticator instance. 16 | Args: 17 | secret (str): 18 | User secret which is used in generating one 19 | time password. 20 | Returns: 21 | Authenticator instance. 22 | """ 23 | 24 | self._secret = secret 25 | self.__check_secret(secret) 26 | 27 | def __is_ascii(self, secret: str): 28 | return all(ord(c) < 128 for c in secret) 29 | 30 | def __is_alpha(self, secret: str): 31 | return all(c.isalpha() for c in secret) 32 | 33 | def __check_secret(self, secret: str): 34 | if isinstance(secret, str) == False: 35 | raise TypeError("You must set a str variable as secret!") 36 | if self.__is_ascii(secret) == False: 37 | raise TypeError("You must set an ascii str variable as secret!") 38 | secret_without_spaces = self.remove_spaces(secret) 39 | self._secret = self.to_upper_case(secret_without_spaces) 40 | secret_length = len(self._secret) 41 | if secret_length < 8: 42 | raise ValueError("You must set a secret of minimum 8 characters!") 43 | if secret_length > 8: 44 | index = secret_length % 8 45 | self._secret = self._secret[:-index] 46 | if self.__is_alpha(self._secret) == False: 47 | raise TypeError("All characters in the secret must be alphabetic!") 48 | 49 | def remove_spaces(self, secret: str) -> str: 50 | """Removes empty spaces from given string. 51 | Args: 52 | secret (str): 53 | User secret which is used in generating one 54 | time password. 55 | Returns: 56 | String without empty spaces. 57 | """ 58 | 59 | secret_without_spaces = secret.replace(" ", "") 60 | secret_without_spaces = re.sub(r"\W", "", secret_without_spaces) 61 | return secret_without_spaces 62 | 63 | def to_upper_case(self, secret_without_spaces: str) -> str: 64 | """Updates given string to uppercase without changing. 65 | Args: 66 | secret_without_spaces (str): 67 | User secret which is used in generating one 68 | time password. 69 | Returns: 70 | String in uppercase. 71 | """ 72 | 73 | return secret_without_spaces.upper() 74 | 75 | def decode_with_base32(self, upper_case_secret: str) -> bytes: 76 | """Creates a new Base32 decoded value from given string. 77 | Args: 78 | upper_case_secret (str): 79 | User secret which is used in generating one 80 | time password. 81 | Returns: 82 | Base32 decoded value. 83 | """ 84 | 85 | return base64.b32decode(upper_case_secret) 86 | 87 | def current_timestamp(self) -> time: 88 | """Returns the current UNIX time.""" 89 | 90 | return time.time() 91 | 92 | def create_hmac(self, secret: str, input: float) -> str: 93 | """Creates the hash value which is used in creating one time password. 94 | Args: 95 | secret (str): 96 | User secret which is used in generating one 97 | time password. 98 | input (float): 99 | The value of current UNIX time divided by 30. 100 | Returns: 101 | SHA1 hash value. 102 | """ 103 | 104 | input_str = repr(input).encode("ascii") 105 | input_hash = hashlib.sha1(secret + input_str).hexdigest().encode("ascii") 106 | return hashlib.sha1(secret + input_hash).hexdigest() 107 | 108 | def one_time_password(self, delay_time: float = 30.0) -> str: 109 | """Creates one time password using secret which must be set in constructor. 110 | Args: 111 | delay_time (float): 112 | Optional time interval for token availability. 113 | Returns: 114 | One time password as string. 115 | """ 116 | 117 | secret_without_spaces = self.remove_spaces(self._secret) 118 | upper_case_secret = self.to_upper_case(secret_without_spaces) 119 | secret = self.decode_with_base32(upper_case_secret) 120 | input = self.current_timestamp() / delay_time 121 | hmac = self.create_hmac(secret, input) 122 | offset = ord(hmac[len(hmac) - 1]) & 0x0F 123 | hex_four_characters = binascii.hexlify(hmac[offset : offset + 4].encode()) 124 | password = int(hex_four_characters, 32) % 1000000 125 | return password 126 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # authenticatorpy 2 | 3 | [![Build Status](https://github.com/abdullahselek/authenticatorpy/workflows/authenticatorpy%20ci/badge.svg)](https://github.com/abdullahselek/authenticatorpy/actions) 4 | [![pypi](https://img.shields.io/pypi/v/authenticatorpy.svg)](https://pypi.python.org/pypi/authenticatorpy/) 5 | [![pyversions](https://img.shields.io/pypi/pyversions/authenticatorpy.svg)](https://pypi.org/project/authenticatorpy) 6 | [![codecov](https://codecov.io/gh/abdullahselek/authenticatorpy/branch/master/graph/badge.svg)](https://codecov.io/gh/abdullahselek/authenticatorpy) 7 | 8 | 9 | **Documentation**: https://authenticatorpy.abdullahselek.com 10 | 11 | **Source Code**: https://github.com/abdullahselek/authenticatorpy 12 | 13 | A pure Python library which provides one time password like Google Authenticator. It works with Python versions Python 3.x. It is designed to have a simple interface usage without no dependencies. 14 | 15 | It also has a CLI which you can simulate creating tokens on your terminal. 16 | -------------------------------------------------------------------------------- /docs/installation.md: -------------------------------------------------------------------------------- 1 | # Installation & Testing 2 | 3 | ## Installation 4 | 5 | **From PyPI** 6 | 7 | $ pip install authenticatorpy 8 | 9 | **From source** 10 | 11 | Install dependencies using `pip` 12 | 13 | ```console 14 | $ pip install -r requirements.txt 15 | ``` 16 | 17 | Download the latest `authenticatorpy` library from: https://github.com/abdullahselek/authenticatorpy 18 | 19 | Extract the source distribution and run 20 | 21 | ```console 22 | $ python setup.py build 23 | $ python setup.py install 24 | ``` 25 | 26 | ## Running Tests 27 | 28 | The test suite can be run against a single Python version which requires `pip install pytest` and optionally `pip install pytest-cov` (these are included if you have installed dependencies from `requirements.testing.txt`) 29 | 30 | To run the unit tests with a single Python version 31 | 32 | ```console 33 | $ py.test -v 34 | ``` 35 | 36 | to also run code coverage 37 | 38 | ```console 39 | $ py.test -v --cov-report html --cov=authenticatorpy 40 | ``` 41 | 42 | To run the unit tests against a set of Python versions:: 43 | 44 | ```console 45 | $ tox 46 | ``` 47 | 48 | ## Getting the code 49 | 50 | The code is hosted at [Github](https://github.com/abdullahselek/authenticatorpy). 51 | 52 | Check out the latest development version anonymously with 53 | 54 | ```console 55 | $ git clone https://github.com/abdullahselek/authenticatorpy.git 56 | $ cd authenticatorpy 57 | ``` 58 | -------------------------------------------------------------------------------- /docs/module/authenticator.md: -------------------------------------------------------------------------------- 1 | # Authenticator 2 | 3 | ::: authenticatorpy.authenticator 4 | rendering: 5 | show_source: true 6 | -------------------------------------------------------------------------------- /docs/module/cli.md: -------------------------------------------------------------------------------- 1 | # CLI 2 | 3 | CLI helps you to simulate creating tokens with your secret keys and optional time to live values. 4 | 5 | ## Usage 6 | 7 | First you need to install **authenticatorpy** either from PyPi or source. Then you can use sample 8 | commands below. 9 | 10 | This will create you new tokens with 30 seconds gaps. 11 | 12 | ```console 13 | $ python -m authenticatorpy --secret testsecret 14 | ``` 15 | 16 | With this one you can set your own time gaps, as an example 5 seconds. 17 | 18 | ```console 19 | $ python -m authenticatorpy --secret testsecret --time 5 20 | ``` 21 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: authenticatorpy 2 | site_description: Generate 2FA tokens like Google Authenticator. 3 | site_url: https://authenticatorpy.abdullahselek.com/ 4 | theme: 5 | name: material 6 | palette: 7 | primary: black 8 | accent: amber 9 | favicon: images/favicon.png 10 | language: en 11 | repo_name: abdullahselek/authenticatorpy 12 | repo_url: https://github.com/abdullahselek/authenticatorpy 13 | edit_uri: '' 14 | nav: 15 | - authenticatorpy: index.md 16 | - installation.md 17 | - Module Documentation: 18 | - module/authenticator.md 19 | - module/cli.md 20 | plugins: 21 | - search 22 | - mkdocstrings: 23 | default_handler: python 24 | handlers: 25 | python: 26 | rendering: 27 | show_source: true 28 | watch: 29 | - authenticatorpy 30 | markdown_extensions: 31 | - toc: 32 | permalink: true 33 | - markdown.extensions.codehilite: 34 | guess_lang: false 35 | - markdown_include.include: 36 | base_path: docs 37 | - admonition 38 | - codehilite 39 | - extra 40 | extra: 41 | social: 42 | - icon: fontawesome/brands/github-alt 43 | link: https://github.com/abdullahselek 44 | - icon: fontawesome/brands/linkedin 45 | link: https://www.linkedin.com/in/abdullahselek 46 | - icon: fontawesome/solid/globe 47 | link: https://abdullahselek.com 48 | extra_css: 49 | - css/termynal.css 50 | - css/custom.css 51 | extra_javascript: 52 | - https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js 53 | - js/termynal.js 54 | - js/custom.js 55 | -------------------------------------------------------------------------------- /requirements.docs.txt: -------------------------------------------------------------------------------- 1 | mkdocs == 1.2.3 2 | mkdocstrings == 0.10.3 3 | mkdocs-material == 5.0.2 4 | markdown-include == 0.5.1 5 | -------------------------------------------------------------------------------- /requirements.testing.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | pytest-cov 3 | pytest-runner 4 | codecov 5 | tox 6 | tox-pyenv 7 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test = pytest 3 | 4 | [check-manifest] 5 | ignore = 6 | .travis.yml 7 | violations.flake8.txt 8 | 9 | [flake8] 10 | ignore = E111,E124,E126,E221,E501 11 | 12 | [pep8] 13 | ignore = E111,E124,E126,E221,E501 14 | max-line-length = 100 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import absolute_import, print_function 4 | 5 | import os 6 | import re 7 | import codecs 8 | 9 | from setuptools import setup, find_packages 10 | 11 | cwd = os.path.abspath(os.path.dirname(__file__)) 12 | 13 | def read(filename): 14 | with codecs.open(os.path.join(cwd, filename), 'rb', 'utf-8') as h: 15 | return h.read() 16 | 17 | metadata = read(os.path.join(cwd, 'authenticatorpy', '__init__.py')) 18 | 19 | def extract_metaitem(meta): 20 | meta_match = re.search(r"""^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]""".format(meta=meta), 21 | metadata, re.MULTILINE) 22 | if meta_match: 23 | return meta_match.group(1) 24 | raise RuntimeError('Unable to find __{meta}__ string.'.format(meta=meta)) 25 | 26 | setup( 27 | name='authenticatorpy', 28 | version=extract_metaitem('version'), 29 | license=extract_metaitem('license'), 30 | description=extract_metaitem('description'), 31 | long_description=(read('README.rst')), 32 | author=extract_metaitem('author'), 33 | author_email=extract_metaitem('email'), 34 | maintainer=extract_metaitem('author'), 35 | maintainer_email=extract_metaitem('email'), 36 | url=extract_metaitem('url'), 37 | download_url=extract_metaitem('download_url'), 38 | packages=find_packages(exclude=('tests', 'docs')), 39 | platforms=['Any'], 40 | keywords='authenticator, unique key generator, 2FA tokens', 41 | classifiers=[ 42 | 'Intended Audience :: Developers', 43 | 'License :: OSI Approved :: MIT License', 44 | 'Operating System :: OS Independent', 45 | 'Topic :: Software Development :: Libraries :: Python Modules', 46 | 'Programming Language :: Python', 47 | 'Programming Language :: Python :: 3.5', 48 | 'Programming Language :: Python :: 3.6', 49 | 'Programming Language :: Python :: 3.7', 50 | 'Programming Language :: Python :: 3.8', 51 | 'Programming Language :: Python :: 3.9', 52 | ], 53 | ) 54 | -------------------------------------------------------------------------------- /tests/test_authenticator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import unittest 5 | 6 | from authenticatorpy.authenticator import Authenticator 7 | 8 | 9 | class AuthenticatorTest(unittest.TestCase): 10 | def setUp(self): 11 | self._authenticator = Authenticator("abcd xyzw abcd xyzw abcd xyzw abcd xyzw") 12 | 13 | def test_initiation(self): 14 | self.assertIsInstance(self._authenticator, Authenticator) 15 | 16 | def test_wrong_initiation(self): 17 | with self.assertRaises(Exception) as context: 18 | Authenticator(123456) 19 | 20 | self.assertTrue( 21 | "You must set a str variable as secret!" in str(context.exception) 22 | ) 23 | 24 | with self.assertRaises(Exception) as context: 25 | Authenticator("abcd") 26 | 27 | self.assertTrue( 28 | "You must set a secret of minimum 8 characters!" in str(context.exception) 29 | ) 30 | 31 | with self.assertRaises(Exception) as context: 32 | Authenticator("ĀƯŤĤËŊŦĩÇÁƮŏƦ") 33 | 34 | self.assertTrue( 35 | "You must set an ascii str variable as secret!" in str(context.exception) 36 | ) 37 | 38 | with self.assertRaises(Exception) as context: 39 | Authenticator(lambda: None) 40 | 41 | self.assertTrue( 42 | "You must set a str variable as secret!" in str(context.exception) 43 | ) 44 | 45 | with self.assertRaises(Exception) as context: 46 | Authenticator(123456.789) 47 | 48 | self.assertTrue( 49 | "You must set a str variable as secret!" in str(context.exception) 50 | ) 51 | 52 | with self.assertRaises(Exception) as context: 53 | Authenticator([]) 54 | 55 | self.assertTrue( 56 | "You must set a str variable as secret!" in str(context.exception) 57 | ) 58 | 59 | with self.assertRaises(Exception) as context: 60 | Authenticator(set()) 61 | 62 | self.assertTrue( 63 | "You must set a str variable as secret!" in str(context.exception) 64 | ) 65 | 66 | with self.assertRaises(Exception) as context: 67 | Authenticator(tuple()) 68 | 69 | self.assertTrue( 70 | "You must set a str variable as secret!" in str(context.exception) 71 | ) 72 | 73 | with self.assertRaises(Exception) as context: 74 | Authenticator("abcd efg0") 75 | 76 | self.assertTrue( 77 | "All characters in the secret must be alphabetic!" in str(context.exception) 78 | ) 79 | 80 | def test_remove_spaces(self): 81 | string_without_spaces = self._authenticator.remove_spaces( 82 | "abcd xyzw abcd xyzw abcd xyzw abcd xyzw" 83 | ) 84 | self.assertEqual(string_without_spaces, "abcdxyzwabcdxyzwabcdxyzwabcdxyzw") 85 | string_without_spaces = self._authenticator.remove_spaces( 86 | "abcd \tyzw \nbcd \tyzw" 87 | ) 88 | self.assertEqual(string_without_spaces, "abcdyzwbcdyzw") 89 | 90 | def test_to_upper_case(self): 91 | upper_case_str = self._authenticator.to_upper_case("abcdefgh") 92 | self.assertEqual(upper_case_str, "ABCDEFGH") 93 | upper_case_str = self._authenticator.to_upper_case("aBcDeFgH") 94 | self.assertEqual(upper_case_str, "ABCDEFGH") 95 | 96 | def test_decode_with_base32(self): 97 | decoded_str = self._authenticator.decode_with_base32( 98 | "ABCDXYZWABCDXYZWABCDXYZWABCDXYZW" 99 | ) 100 | self.assertEqual(decoded_str, b"\x00D;\xe36\x00D;\xe36\x00D;\xe36\x00D;\xe36") 101 | 102 | def test_current_timestamp(self): 103 | self.assertIsNotNone(self._authenticator.current_timestamp()) 104 | 105 | def test_create_hmac(self): 106 | decoded_str = self._authenticator.decode_with_base32( 107 | "ABCDXYZWABCDXYZWABCDXYZWABCDXYZW" 108 | ) 109 | input = self._authenticator.current_timestamp() / 30 110 | hmac = self._authenticator.create_hmac(decoded_str, input) 111 | self.assertIsNotNone(hmac) 112 | 113 | def test_one_time_password(self): 114 | password = self._authenticator.one_time_password() 115 | self.assertIsNotNone(password) 116 | self.assertIsNotNone(Authenticator("abcd xyzw a").one_time_password()) 117 | self.assertIsNotNone(Authenticator("abcd xyzw ab").one_time_password()) 118 | self.assertIsNotNone(Authenticator("abcd xyzw abcd").one_time_password()) 119 | 120 | def test_one_time_password_with_empty_spaces(self): 121 | password = Authenticator("\ta\bt\tc\td \te\tf\tg\th").one_time_password() 122 | self.assertIsNotNone(password) 123 | password = Authenticator("\ra\rb\rc\rd \re\rf\rg\rh").one_time_password() 124 | self.assertIsNotNone(password) 125 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = clean,py27,py3,py36,pypy,pypy3 3 | skip_missing_interpreters = True 4 | 5 | [testenv] 6 | deps = -Ur{toxinidir}/requirements.testing.txt 7 | commands = pytest -s -v 8 | whitelist_externals = pyenv install -s 3.6.1 9 | pyenv install -s pypy-5.3.1 10 | pyenv local 3.6.1 pypy-5.3.1 11 | 12 | [testenv:clean] 13 | deps = coverage 14 | commands = coverage erase 15 | 16 | [testenv:report] 17 | commands = py.test --cov-report html --cov=authenticatorpy 18 | 19 | [testenv:coverage] 20 | commands = coverage combine 21 | coverage html 22 | coverage report 23 | codecov 24 | --------------------------------------------------------------------------------