diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md new file mode 100644 index 0000000..8de294e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +Thank you for contributing! Before you submit a pull request, please read the following. + +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html + +If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3baf502..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,64 +10,5 @@ jobs: test: runs-on: ubuntu-latest steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install pylint, Sphinx, pre-commit - run: | - pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Build docs - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/failure-help-text.yml b/.github/workflows/failure-help-text.yml new file mode 100644 index 0000000..0b1194f --- /dev/null +++ b/.github/workflows/failure-help-text.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Failure help text + +on: + workflow_run: + workflows: ["Build CI"] + types: + - completed + +jobs: + post-help: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} + steps: + - name: Post comment to help + uses: adafruit/circuitpython-action-library-ci-failed@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 6d0015a..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,85 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install deps - run: | - source actions-ci/install.sh - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Upload Release Assets - # the 'official' actions version does not yet support dynamically - # supplying asset names to upload. @csexton's version chosen based on - # discussion in the issue below, as its the simplest to implement and - # allows for selecting files with a pattern. - # https://github.com/actions/upload-release-asset/issues/4 - #uses: actions/upload-release-asset@v1.0.1 - uses: csexton/release-asset-action@master - with: - pattern: "bundles/*" - github-token: ${{ secrets.GITHUB_TOKEN }} - - upload-pypi: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - uses: actions/setup-python@v1 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - python setup.py sdist - twine upload dist/* diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..9acec60 --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: GitHub Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run GitHub Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-gh@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + upload-url: ${{ github.event.release.upload_url }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml new file mode 100644 index 0000000..65775b7 --- /dev/null +++ b/.github/workflows/release_pypi.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: PyPI Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run PyPI Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-pypi@main + with: + pypi-username: ${{ secrets.pypi_username }} + pypi-password: ${{ secrets.pypi_password }} diff --git a/.gitignore b/.gitignore index 9647e71..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,48 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT +# Do not include files and directories created by your personal work environment, such as the IDE +# you use, except for those already listed here. Pull requests including changes to this file will +# not be accepted. + +# This .gitignore file contains rules for files generated by working with CircuitPython libraries, +# including building Sphinx, testing with pip, and creating a virual environment, as well as the +# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. + +# If you find that there are files being generated on your machine that should not be included in +# your git commit, you should create a .gitignore_global file on your computer to include the +# files created by your personal setup. To do so, follow the two steps below. + +# First, create a file called .gitignore_global somewhere convenient for you, and add rules for +# the files you want to exclude from git commits. + +# Second, configure Git to use the exclude file for all Git repositories by running the +# following via commandline, replacing "path/to/your/" with the actual path to your newly created +# .gitignore_global file: +# git config --global core.excludesfile path/to/your/.gitignore_global + +# CircuitPython-specific files *.mpy -.idea + +# Python-specific files __pycache__ -_build *.pyc + +# Sphinx build-specific files +_build + +# This file results from running `pip -e install .` in a local repository +*.egg-info + +# Virtual environment-specific files .env -bundles +.venv + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea +.vscode +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 354c761..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,34 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: -- repo: https://github.com/python/black - rev: 20.8b1 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace -- repo: https://github.com/pycqa/pylint - rev: pylint-2.7.1 - hooks: - - id: pylint - name: pylint (library code) - types: [python] - exclude: "^(docs/|examples/|setup.py$)" -- repo: local - hooks: - - id: pylint_examples - name: pylint (examples code) - description: Run pylint rules on "examples/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name $example; done)'] - language: system + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 0238b90..0000000 --- a/.pylintrc +++ /dev/null @@ -1,436 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Naming hint for argument names -argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for attribute names -attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Naming hint for class names -# class-name-hint=[A-Z_][a-zA-Z0-9]+$ -class-name-hint=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Naming hint for constant names -const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming hint for function names -function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Naming hint for method names -method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Naming hint for variable names -variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=Exception diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..88bca9f --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +sphinx: + configuration: docs/conf.py + +build: + os: ubuntu-20.04 + tools: + python: "3" + +python: + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index ffa84c4..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: requirements.txt diff --git a/README.rst b/README.rst index fca96fb..f0604ed 100644 --- a/README.rst +++ b/README.rst @@ -1,11 +1,11 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-rsa/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/rsa/en/latest/ +.. image:: https://readthedocs.org/projects/rsa/badge/?version=latest + :target: https://docs.circuitpython.org/projects/rsa/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord @@ -13,6 +13,10 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_RSA/actions/ :alt: Build Status +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff + RSA implementation based on `Sybren A. Stüvel's python-rsa `_ pure-python RSA implementation. @@ -23,6 +27,8 @@ This driver depends on: * `Adafruit CircuitPython `_ * `Adafruit CircuitPython Logger Module `_ +* `pyasn1 Library `_ (some functionality) +* CPython's ``rsa`` Library (some functionality) Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading @@ -48,8 +54,8 @@ To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip3 install adafruit-circuitpython-rsa Usage Example @@ -57,14 +63,16 @@ Usage Example Examples for this library are avaliable in the examples/ folder. +Documentation +============= + +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out `this guide `_. + Contributing ============ Contributions are welcome! Please read our `Code of Conduct -`_ +`_ before contributing to help this project stay welcoming. - -Documentation -============= - -For information on building library documentation, please check out `this guide `_. diff --git a/adafruit_rsa/__init__.py b/adafruit_rsa/__init__.py index 8c66cbd..ff46b68 100755 --- a/adafruit_rsa/__init__.py +++ b/adafruit_rsa/__init__.py @@ -1,33 +1,34 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""RSA module +""" +RSA module +==================================================== Module for calculating large primes, and RSA encryption, decryption, signing and verification. Includes generating public and private keys. -WARNING: this implementation does not use compression of the cleartext input to +**WARNING:** This implementation does not use compression of the cleartext input to prevent repetitions, or other common security improvements. Use with care. """ -from adafruit_rsa.key import newkeys, PrivateKey, PublicKey +from adafruit_rsa.key import PrivateKey, PublicKey, newkeys from adafruit_rsa.pkcs1 import ( - encrypt, - decrypt, - sign, - verify, DecryptionError, VerificationError, + compute_hash, + decrypt, + encrypt, find_signature_hash, + sign, sign_hash, - compute_hash, + verify, ) __author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly" __date__ = "2018-09-16" # __version__ = '4.0.0' -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 8312ab5..fb8770a 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -1,14 +1,29 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Python compatibility wrappers.""" +""" +`adafruit_rsa._compat` +==================================================== + +Python compatibility wrappers. +""" import sys from struct import pack -__version__ = "0.0.0-auto.0" +try: + from typing import Any, Tuple + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass + + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" MAX_INT = sys.maxsize @@ -31,40 +46,40 @@ INTEGER_TYPES = (int,) -def write_to_stdout(data): +def write_to_stdout(data: bytes) -> None: """Writes bytes to stdout - :type data: bytes + :param bytes data: Data to write """ # On Py3 we must use the buffer interface to write bytes. sys.stdout.buffer.write(data) -def is_bytes(obj): +def is_bytes(obj: Any) -> bool: """ Determines whether the given value is a byte string. :param obj: The value to test. - :returns: - ``True`` if ``value`` is a byte string; ``False`` otherwise. + :return: + ``True`` if ``obj`` is a byte string; ``False`` otherwise. """ return isinstance(obj, bytes) -def is_integer(obj): +def is_integer(obj: Any) -> bool: """ Determines whether the given value is an integer. :param obj: The value to test. - :returns: - ``True`` if ``value`` is an integer; ``False`` otherwise. + :return: + ``True`` if ``obj`` is an integer; ``False`` otherwise. """ return isinstance(obj, INTEGER_TYPES) -def byte(num): +def byte(num: int) -> bytes: """ Converts a number between 0 and 255 (both inclusive) to a base-256 (byte) representation. @@ -72,15 +87,13 @@ def byte(num): Use it as a replacement for ``chr`` where you are expecting a byte because this will work on all current versions of Python:: - :param num: - An unsigned integer between 0 and 255 (both inclusive). - :returns: - A single byte. + :param int num: An unsigned integer between 0 and 255 (both inclusive). + :return: A single byte. """ return pack("B", num) -def xor_bytes(bytes_1, bytes_2): +def xor_bytes(bytes_1: bytes, bytes_2: bytes) -> bytes: """ Returns the bitwise XOR result between two bytes objects, bytes_1 ^ bytes_2. @@ -88,30 +101,31 @@ def xor_bytes(bytes_1, bytes_2): generate different results. If parameters have different length, extra length of the largest one is ignored. - :param bytes_1: - First bytes object. - :param bytes_2: - Second bytes object. - :returns: - Bytes object, result of XOR operation. + :param bytes bytes_1: First bytes object. + :param bytes_2: Second bytes object. + :return: Bytes object, result of XOR operation. """ return bytes(x ^ y for x, y in zip(bytes_1, bytes_2)) -def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE): +def get_word_alignment( + num: int, + force_arch: int = 64, + _machine_word_size: Literal[64, 32] = MACHINE_WORD_SIZE, +) -> Tuple[int, int, int, str]: """ Returns alignment details for the given number based on the platform Python is running on. - :param num: - Unsigned integral number. - :param force_arch: + :param int num: + Unsigned integer number. + :param int force_arch: If you don't want to use 64-bit unsigned chunks, set this to anything other than 64. 32-bit chunks will be preferred then. Default 64 will be used when on a 64-bit machine. - :param _machine_word_size: + :param int _machine_word_size: (Internal) The machine word size used for alignment. - :returns: + :return: 4-tuple:: (word_bits, word_bytes, diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index 7cc6f03..02e9d33 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -1,17 +1,22 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""ASN.1 definitions. +""" +`adafruit_rsa.asn1` +==================================================== + +ASN.1 definitions. Not all ASN.1-handling code use these definitions, but when it does, they should be here. """ -# pylint: disable=no-name-in-module, too-few-public-methods -from pyasn1.type import univ, namedtype, tag +try: + from pyasn1.type import namedtype, tag, univ +except ImportError as err: + raise ImportError("Usage of asn1.py requires pyasn1 library") from err -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" @@ -32,19 +37,21 @@ class OpenSSLPubKey(univ.Sequence): # This little hack (the implicit tag) allows us to get a Bit String as Octet String namedtype.NamedType( "key", - univ.OctetString().subtype( - implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3) - ), + univ.OctetString().subtype(implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3)), ), ) class AsnPubKey(univ.Sequence): - """ASN.1 contents of DER encoded public key: + """ASN1 contents of DER encoded public key: + + .. code-block:: shell + + RSAPublicKey ::= SEQUENCE { + modulus INTEGER, -- n + publicExponent INTEGER, -- e + } - RSAPublicKey ::= SEQUENCE { - modulus INTEGER, -- n - publicExponent INTEGER, -- e """ componentType = namedtype.NamedTypes( diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index 295e92c..4255a94 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -1,19 +1,30 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Common functionality shared by several modules.""" +""" +`adafruit_rsa.common` +==================================================== -# pylint: disable=invalid-name +Common functionality shared by several modules. +""" -__version__ = "0.0.0-auto.0" +try: + from typing import Optional, Sequence, Tuple +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -def bit_length(int_type): +def bit_length(int_type: int) -> int: """Return the number of bits necessary to represent an integer in binary, - excluding the sign and leading zeros""" + excluding the sign and leading zeros + + :param int int_type: The integer to check + """ + length = 0 while int_type: int_type >>= 1 @@ -24,16 +35,14 @@ def bit_length(int_type): class NotRelativePrimeError(ValueError): """Raises if provided a and b not relatively prime.""" - def __init__(self, a, b, d, msg=None): - super().__init__( - msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d) - ) + def __init__(self, a: int, b: int, d: int, msg: Optional[str] = None): + super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d)) self.a = a self.b = b self.d = d -def bit_size(num): +def bit_size(num: int) -> int: """ Number of bits needed to represent a integer excluding any prefix 0 bits. @@ -47,23 +56,21 @@ def bit_size(num): >>> bit_size(1025) 11 - :param num: + :param int num: Integer value. If num is 0, returns 0. Only the absolute value of the number is considered. Therefore, signed integers will be abs(num) before the number's bit length is determined. - :returns: + :return: Returns the number of bits in the integer. """ try: return bit_length(num) except AttributeError as err: - raise TypeError( - "bit_size(num) only supports integers, not %r" % type(num) - ) from err + raise TypeError("bit_size(num) only supports integers, not %r" % type(num)) from err -def byte_size(number): +def byte_size(number: int) -> int: """ Returns the number of bytes required to hold a specific long number. @@ -78,21 +85,19 @@ def byte_size(number): >>> byte_size(1 << 1024) 129 - :param number: - An unsigned integer - :returns: - The number of bytes required to hold a specific long number. + :param int number: An unsigned integer + :return: The number of bytes required to hold a specific long number. """ if number == 0: return 1 return ceil_div(bit_size(number), 8) -def ceil_div(num, div): +def ceil_div(num: int, div: int) -> int: """ - Returns the ceiling function of a division between `num` and `div`. + Returns the ceiling function of a division between ``num`` and ``div``. - Usage:: + Usage: >>> ceil_div(100, 7) 15 @@ -101,9 +106,8 @@ def ceil_div(num, div): >>> ceil_div(1, 4) 1 - :param num: Division's numerator, a number - :param div: Division's divisor, a number - + :param int num: Division's numerator, a number + :param int div: Division's divisor, a number :return: Rounded up result of the division between the parameters. """ quanta, mod = divmod(num, div) @@ -112,7 +116,7 @@ def ceil_div(num, div): return quanta -def extended_gcd(a, b): +def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb""" # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a @@ -136,7 +140,7 @@ def extended_gcd(a, b): return a, lx, ly # Return only positive values -def inverse(x, n): +def inverse(x: int, n: int) -> int: """Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n) >>> inverse(7, 4) @@ -153,14 +157,14 @@ def inverse(x, n): return inv -def crt(a_values, modulo_values): +def crt(a_values: Sequence[int], modulo_values: Sequence[int]) -> int: """Chinese Remainder Theorem. Calculates x such that x = a[i] (mod m[i]) for each i. - :param a_values: the a-values of the above equation - :param modulo_values: the m-values of the above equation - :returns: x such that x = a[i] (mod m[i]) for each i + :param Sequence[int] a_values: the a-values of the above equation + :param Sequence[int] modulo_values: the m-values of the above equation + :return: x such that x = a[i] (mod m[i]) for each i >>> crt([2, 3], [3, 5]) @@ -179,7 +183,7 @@ def crt(a_values, modulo_values): for modulo in modulo_values: m *= modulo - for (m_i, a_i) in zip(modulo_values, a_values): + for m_i, a_i in zip(modulo_values, a_values): M_i = m // m_i inv = inverse(M_i, m_i) diff --git a/adafruit_rsa/core.py b/adafruit_rsa/core.py index 0e5ca85..23b0e99 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -1,23 +1,31 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Core mathematical operations. +""" +`adafruit_rsa.core` +==================================================== + +Core mathematical operations. This is the actual core RSA implementation, which is only defined mathematically on integers. """ -# pylint: disable=invalid-name from adafruit_rsa._compat import is_integer -__version__ = "0.0.0-auto.0" +try: + from typing import Any +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -def fast_pow(x, e, m): +def fast_pow(x: int, e: int, m: int) -> int: """Performs fast modular exponentiation, saves RAM on small CPUs/micros. + :param int x: Base :param int y: Exponent :param int e: Second exponent @@ -35,15 +43,15 @@ def fast_pow(x, e, m): return Y -def assert_int(var, name): +def assert_int(var: Any, name: str) -> None: """Asserts provided variable is an integer.""" if is_integer(var): return - raise TypeError("%s should be an integer, not %s" % (name, var.__class__)) + raise TypeError(f"{name} should be an integer, not {var.__class__}") -def encrypt_int(message, ekey, n): +def encrypt_int(message: int, ekey: int, n: int) -> int: """Encrypts a message using encryption key 'ekey', working modulo n""" assert_int(message, "message") @@ -61,7 +69,7 @@ def encrypt_int(message, ekey, n): return fast_pow(message, ekey, n) -def decrypt_int(cyphertext, dkey, n): +def decrypt_int(cyphertext: int, dkey: int, n: int) -> int: """Decrypts a cypher text using the decryption key 'dkey', working modulo n""" assert_int(cyphertext, "cyphertext") diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index a1ec7c3..f059003 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -1,9 +1,12 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""RSA key generation code. +""" +`adafruit_rsa.key` +==================================================== + +RSA key generation code. Create new keys with the newkeys() function. It will give you a PublicKey and a PrivateKey object. @@ -24,85 +27,84 @@ import adafruit_logging as logging -import adafruit_rsa.prime -import adafruit_rsa.pem import adafruit_rsa.common -import adafruit_rsa.randnum import adafruit_rsa.core +import adafruit_rsa.pem +import adafruit_rsa.prime +import adafruit_rsa.randnum + +try: + from typing import Any, Callable, Dict, Tuple + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -# pylint: disable=invalid-name, useless-object-inheritance, redefined-builtin, no-name-in-module, too-few-public-methods log = logging.getLogger(__name__) +log.addHandler(logging.StreamHandler()) log.setLevel(logging.INFO) DEFAULT_EXPONENT = 65537 -class AbstractKey(object): +class AbstractKey: """Abstract superclass for private and public keys.""" - __slots__ = ("n", "e") - - def __init__(self, n, e): + def __init__(self, n: int, e: int) -> None: self.n = n self.e = e @classmethod - def _load_pkcs1_pem(cls, keyfile): + def _load_pkcs1_pem(cls, keyfile: bytes) -> "AbstractKey": """Loads a key in PKCS#1 PEM format, implement in a subclass. - :param keyfile: contents of a PEM-encoded file that contains + :param bytes keyfile: contents of a PEM-encoded file that contains the public key. - :type keyfile: bytes - :return: the loaded key :rtype: AbstractKey """ @classmethod - def _load_pkcs1_der(cls, keyfile): + def _load_pkcs1_der(cls, keyfile: bytes) -> "AbstractKey": """Loads a key in PKCS#1 PEM format, implement in a subclass. - :param keyfile: contents of a DER-encoded file that contains + :param bytes keyfile: contents of a DER-encoded file that contains the public key. - :type keyfile: bytes - :return: the loaded key :rtype: AbstractKey """ - def _save_pkcs1_pem(self): + def _save_pkcs1_pem(self) -> bytes: """Saves the key in PKCS#1 PEM format, implement in a subclass. - :returns: the PEM-encoded key. + :return: the PEM-encoded key. :rtype: bytes """ - def _save_pkcs1_der(self): + def _save_pkcs1_der(self) -> bytes: """Saves the key in PKCS#1 DER format, implement in a subclass. - :returns: the DER-encoded key. + :return: the DER-encoded key. :rtype: bytes """ @classmethod - def load_pkcs1(cls, keyfile, format="PEM"): + def load_pkcs1(cls, keyfile: bytes, format: Literal["PEM", "DER"] = "PEM") -> "AbstractKey": """Loads a key in PKCS#1 DER or PEM format. - :param keyfile: contents of a DER- or PEM-encoded file that contains - the key. - :type keyfile: bytes - :param format: the format of the file to load; 'PEM' or 'DER' - :type format: str - + :param bytes keyfile: contents of a DER- or PEM-encoded file that + contains the key. + :param str format: the format of the file to load; 'PEM' or 'DER' :return: the loaded key :rtype: AbstractKey """ - raise NotImplementedError( - "Loading PEM Files not supported by this CircuitPython library." - ) + raise NotImplementedError("Loading PEM Files not supported by this CircuitPython library.") # methods = { # 'PEM': cls._load_pkcs1_pem, @@ -113,23 +115,22 @@ def load_pkcs1(cls, keyfile, format="PEM"): # return method(keyfile) @staticmethod - def _assert_format_exists(file_format, methods): + def _assert_format_exists( + file_format: str, methods: Dict[str, Callable] + ) -> Callable[[], bytes]: """Checks whether the given file format exists in 'methods'.""" try: return methods[file_format] except KeyError as err: formats = ", ".join(sorted(methods.keys())) - raise ValueError( - "Unsupported format: %r, try one of %s" % (file_format, formats) - ) from err + raise ValueError(f"Unsupported format: {file_format!r}, try one of {formats}") from err - def save_pkcs1(self, format="PEM"): + def save_pkcs1(self, format: Literal["PEM", "DER"] = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. - :param format: the format to save; 'PEM' or 'DER' - :type format: str - :returns: the DER- or PEM-encoded key. + :param str format: the format to save; 'PEM' or 'DER' + :return: the DER- or PEM-encoded key. :rtype: bytes """ @@ -141,13 +142,11 @@ def save_pkcs1(self, format="PEM"): method = self._assert_format_exists(format, methods) return method() - def blind(self, message, r): + def blind(self, message: int, r: int) -> int: """Performs blinding on the message using random number 'r'. - :param message: the message, as integer, to blind. - :type message: int - :param r: the random number to blind with. - :type r: int + :param int message: the message, as integer, to blind. + :param int r: the random number to blind with. :return: the blinded message. :rtype: int @@ -158,12 +157,13 @@ def blind(self, message, r): return (message * adafruit_rsa.core.fast_pow(r, self.e, self.n)) % self.n - def unblind(self, blinded, r): + def unblind(self, blinded: int, r: int) -> int: """Performs blinding on the message using random number 'r'. - :param blinded: the blinded message, as integer, to unblind. - :param r: the random number to unblind with. + :param int blinded: the blinded message, as integer, to unblind. + :param int r: the random number to unblind with. :return: the original message. + :rtype: int The blinding is such that message = unblind(decrypt(blind(encrypt(message))). @@ -173,7 +173,6 @@ def unblind(self, blinded, r): return (adafruit_rsa.common.inverse(r, self.n) * blinded) % self.n -# pylint: disable=abstract-method class PublicKey(AbstractKey): """Represents a public RSA key. @@ -200,21 +199,21 @@ class PublicKey(AbstractKey): __slots__ = ("n", "e") - def __getitem__(self, key): + def __getitem__(self, key: str) -> Any: return getattr(self, key) - def __repr__(self): + def __repr__(self) -> str: return "PublicKey(%i, %i)" % (self.n, self.e) - def __getstate__(self): + def __getstate__(self) -> Tuple[int, int]: """Returns the key as tuple for pickling.""" return self.n, self.e - def __setstate__(self, state): + def __setstate__(self, state: Tuple[int, int]) -> None: """Sets the key from tuple.""" self.n, self.e = state - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: if other is None: return False @@ -223,18 +222,18 @@ def __eq__(self, other): return self.n == other.n and self.e == other.e - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: return not self == other - def __hash__(self): + def __hash__(self) -> int: return hash((self.n, self.e)) @classmethod - def _load_pkcs1_der(cls, keyfile): + def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey": """Loads a key in PKCS#1 DER format. - :param keyfile: contents of a DER-encoded file that contains the public - key. + :param bytes keyfile: contents of a DER-encoded file that contains the + public key. :return: a PublicKey object First let's construct a DER encoded key: @@ -249,22 +248,32 @@ def _load_pkcs1_der(cls, keyfile): PublicKey(2367317549, 65537) """ - # pylint: disable=import-outside-toplevel - from adafruit_rsa.tools.pyasn1.codec.der import decoder - from adafruit_rsa.asn1 import AsnPubKey + try: + from adafruit_rsa.asn1 import AsnPubKey + from adafruit_rsa.tools.pyasn1.codec.der import decoder + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) return cls(n=int(priv["modulus"]), e=int(priv["publicExponent"])) - def _save_pkcs1_der(self): + def _save_pkcs1_der(self) -> bytes: """Saves the public key in PKCS#1 DER format. - :returns: the DER-encoded public key. + :return: the DER-encoded public key. :rtype: bytes """ - # pylint: disable=import-outside-toplevel - from pyasn1.codec.der import encoder - from rsa.asn1 import AsnPubKey + try: + from pyasn1.codec.der import encoder + except ImportError as err: + raise ImportError("This functionality requires the library") from err + try: + from rsa.asn1 import AsnPubKey + except ImportError as err: + raise ImportError( + "This functionality requres the CPython rsa library, " + "not available in CircuitPython" + ) from err # Create the ASN object asn_key = AsnPubKey() @@ -274,21 +283,21 @@ def _save_pkcs1_der(self): return encoder.encode(asn_key) @classmethod - def _load_pkcs1_pem(cls, keyfile): + def _load_pkcs1_pem(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1 PEM-encoded public key file. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and after the "-----END RSA PUBLIC KEY-----" lines is ignored. - :param keyfile: contents of a PEM-encoded file that contains the public - key. + :param bytes keyfile: contents of a PEM-encoded file that contains the + public key. :return: a PublicKey object """ der = adafruit_rsa.pem.load_pem(keyfile, "RSA PUBLIC KEY") return cls._load_pkcs1_der(der) - def _save_pkcs1_pem(self): + def _save_pkcs1_pem(self) -> bytes: """Saves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key. @@ -299,7 +308,7 @@ def _save_pkcs1_pem(self): return adafruit_rsa.pem.save_pem(der, "RSA PUBLIC KEY") @classmethod - def load_pkcs1_openssl_pem(cls, keyfile): + def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY @@ -308,8 +317,8 @@ def load_pkcs1_openssl_pem(cls, keyfile): The contents of the file before the "-----BEGIN PUBLIC KEY-----" and after the "-----END PUBLIC KEY-----" lines is ignored. - :param keyfile: contents of a PEM-encoded file that contains the public - key, from OpenSSL. + :param bytes keyfile: contents of a PEM-encoded file that contains the + public key, from OpenSSL. :type keyfile: bytes :return: a PublicKey object """ @@ -318,19 +327,20 @@ def load_pkcs1_openssl_pem(cls, keyfile): return cls.load_pkcs1_openssl_der(der) @classmethod - def load_pkcs1_openssl_der(cls, keyfile): + def load_pkcs1_openssl_der(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1 DER-encoded public key file from OpenSSL. - :param keyfile: contents of a DER-encoded file that contains the public - key, from OpenSSL. + :param bytes keyfile: contents of a DER-encoded file that contains the + public key, from OpenSSL. :return: a PublicKey object - :rtype: bytes - """ - # pylint: disable=import-outside-toplevel - from adafruit_rsa.asn1 import OpenSSLPubKey - from pyasn1.codec.der import decoder - from pyasn1.type import univ + try: + from pyasn1.codec.der import decoder + from pyasn1.type import univ + + from adafruit_rsa.asn1 import OpenSSLPubKey + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) @@ -366,8 +376,7 @@ class PrivateKey(AbstractKey): __slots__ = ("n", "e", "d", "p", "q", "exp1", "exp2", "coef") - # pylint: disable=too-many-arguments - def __init__(self, n, e, d, p, q): + def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None: AbstractKey.__init__(self, n, e) self.d = d self.p = p @@ -378,10 +387,10 @@ def __init__(self, n, e, d, p, q): self.exp2 = int(d % (q - 1)) self.coef = adafruit_rsa.common.inverse(q, p) - def __getitem__(self, key): + def __getitem__(self, key: str) -> Any: return getattr(self, key) - def __repr__(self): + def __repr__(self) -> str: return "PrivateKey(%i, %i, %i, %i, %i)" % ( self.n, self.e, @@ -390,15 +399,15 @@ def __repr__(self): self.q, ) - def __getstate__(self): + def __getstate__(self) -> Tuple[int, int, int, int, int, int, int, int]: """Returns the key as tuple for pickling.""" return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef - def __setstate__(self, state): + def __setstate__(self, state: Tuple[int, int, int, int, int, int, int, int]) -> None: """Sets the key from tuple.""" self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: if other is None: return False @@ -416,21 +425,18 @@ def __eq__(self, other): and self.coef == other.coef ) - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: return not self == other - def __hash__(self): - return hash( - (self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef) - ) + def __hash__(self) -> int: + return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) - def blinded_decrypt(self, encrypted): + def blinded_decrypt(self, encrypted: int) -> int: """Decrypts the message using blinding to prevent side-channel attacks. - :param encrypted: the encrypted message - :type encrypted: int + :param int encrypted: the encrypted message - :returns: the decrypted message + :return: the decrypted message :rtype: int """ @@ -440,13 +446,11 @@ def blinded_decrypt(self, encrypted): return self.unblind(decrypted, blind_r) - def blinded_encrypt(self, message): + def blinded_encrypt(self, message: int) -> int: """Encrypts the message using blinding to prevent side-channel attacks. - :param message: the message to encrypt - :type message: int - - :returns: the encrypted message + :param int message: the message to encrypt + :return: the encrypted message :rtype: int """ @@ -456,12 +460,11 @@ def blinded_encrypt(self, message): return self.unblind(encrypted, blind_r) @classmethod - def _load_pkcs1_der(cls, keyfile): + def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey": """Loads a key in PKCS#1 DER format. - :param keyfile: contents of a DER-encoded file that contains the private - key. - :type keyfile: bytes + :param bytes keyfile: contents of a DER-encoded file that contains the + private key. :return: a PrivateKey object First let's construct a DER encoded key: @@ -477,9 +480,12 @@ def _load_pkcs1_der(cls, keyfile): """ - from adafruit_rsa.tools.pyasn1.codec.der import ( # pylint: disable=import-outside-toplevel - decoder, - ) + try: + from adafruit_rsa.tools.pyasn1.codec.der import ( + decoder, + ) + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err (priv, _) = decoder.decode(keyfile) @@ -514,15 +520,17 @@ def _load_pkcs1_der(cls, keyfile): return key - def _save_pkcs1_der(self): + def _save_pkcs1_der(self) -> bytes: """Saves the private key in PKCS#1 DER format. - :returns: the DER-encoded private key. + :return: the DER-encoded private key. :rtype: bytes """ - # pylint: disable=import-outside-toplevel - from pyasn1.type import univ, namedtype - from pyasn1.codec.der import encoder + try: + from pyasn1.codec.der import encoder + from pyasn1.type import namedtype, univ + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err class AsnPrivKey(univ.Sequence): """Creates PKCS#1 DER Formatted AsnPrivKey""" @@ -554,22 +562,21 @@ class AsnPrivKey(univ.Sequence): return encoder.encode(asn_key) @classmethod - def _load_pkcs1_pem(cls, keyfile): + def _load_pkcs1_pem(cls, keyfile: bytes) -> "PrivateKey": """Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. - :param keyfile: contents of a PEM-encoded file that contains the private - key. - :type keyfile: bytes + :param bytes keyfile: contents of a PEM-encoded file that contains the + private key. :return: a PrivateKey object """ der = adafruit_rsa.pem.load_pem(keyfile, b"RSA PRIVATE KEY") return cls._load_pkcs1_der(der) - def _save_pkcs1_pem(self): + def _save_pkcs1_pem(self) -> bytes: """Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. @@ -580,7 +587,11 @@ def _save_pkcs1_pem(self): return adafruit_rsa.pem.save_pem(der, b"RSA PRIVATE KEY") -def find_p_q(nbits, getprime_func=adafruit_rsa.prime.getprime, accurate=True): +def find_p_q( + nbits: int, + getprime_func: Callable[[int], int] = adafruit_rsa.prime.getprime, + accurate: bool = True, +) -> Tuple[int, int]: """Returns a tuple of two different primes of nbits bits each. The resulting p * q has exacty 2 * nbits bits, and the returned p and q @@ -593,7 +604,7 @@ def find_p_q(nbits, getprime_func=adafruit_rsa.prime.getprime, accurate=True): *Introduced in Python-RSA 3.1* :param accurate: whether to enable accurate mode or not. - :returns: (p, q), where p > q + :return: (p, q), where p > q >>> (p, q) = find_p_q(128) >>> from adafruit_rsa.rsa import common @@ -625,7 +636,7 @@ def find_p_q(nbits, getprime_func=adafruit_rsa.prime.getprime, accurate=True): log.debug("find_p_q(%i): Finding q", nbits) q = getprime_func(qbits) - def is_acceptable(p, q): + def is_acceptable(p: int, q: int) -> bool: """Returns True iff p and q are acceptable: - p and q differ @@ -658,17 +669,15 @@ def is_acceptable(p, q): return max(p, q), min(p, q) -def calculate_keys_custom_exponent(p, q, exponent): +def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> Tuple[int, int]: """Calculates an encryption and a decryption key given p, q and an exponent, and returns them as a tuple (e, d) - :param p: the first large prime - :param q: the second large prime - :param exponent: the exponent for the key; only change this if you know - what you're doing, as the exponent influences how difficult your - private key can be cracked. A very common choice for e is 65537. - :type exponent: int - + :param int p: the first large prime + :param int q: the second large prime + :param int exponent: the exponent for the key; only change this if you + know what you're doing, as the exponent influences how difficult + your private key can be cracked. A very common choice for e is 65537. """ phi_n = (p - 1) * (q - 1) @@ -686,19 +695,18 @@ def calculate_keys_custom_exponent(p, q, exponent): if (exponent * d) % phi_n != 1: raise ValueError( - "e (%d) and d (%d) are not mult. inv. modulo " - "phi_n (%d)" % (exponent, d, phi_n) + "e (%d) and d (%d) are not mult. inv. modulo " "phi_n (%d)" % (exponent, d, phi_n) ) return exponent, d -def calculate_keys(p, q): +def calculate_keys(p: int, q: int) -> Tuple[int, int]: """Calculates an encryption and a decryption key given p and q, and returns them as a tuple (e, d) - :param p: the first large prime - :param q: the second large prime + :param int p: the first large prime + :param int q: the second large prime :return: tuple (e, d) with the encryption and decryption exponents. """ @@ -706,19 +714,26 @@ def calculate_keys(p, q): return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT) -def gen_keys(nbits, getprime_func, accurate=True, exponent=DEFAULT_EXPONENT): +def gen_keys( + nbits: int, + getprime_func: Callable[[int], int], + accurate: bool = True, + exponent: int = DEFAULT_EXPONENT, +) -> Tuple[int, int, int, int]: """Generate RSA keys of nbits bits. Returns (p, q, e, d). Note: this can take a long time, depending on the key size. - :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and + :param int nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and ``q`` will use ``nbits/2`` bits. - :param getprime_func: either :py:func:`adafruit_rsa.rsa.prime.getprime` or a function + :param Callable getprime_func: either :py:func:`adafruit_rsa.rsa.prime.getprime` or a function with similar signature. - :param exponent: the exponent for the key; only change this if you know + :param bool accurate: when True, ``n`` will have exactly the number of bits you + asked for. However, this makes key generation much slower. When False, + `n`` may have slightly less bits. + :param int exponent: the exponent for the key; only change this if you know what you're doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537. - :type exponent: int """ # Regenerate p and q values, until calculate_keys doesn't raise a @@ -735,28 +750,31 @@ def gen_keys(nbits, getprime_func, accurate=True, exponent=DEFAULT_EXPONENT): def newkeys( - nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT, log_level="INFO" -): + nbits: int, + accurate: bool = True, + poolsize: int = 1, + exponent: int = DEFAULT_EXPONENT, + log_level: str = "INFO", +) -> Tuple["PublicKey", "PrivateKey"]: """Generates public and private keys, and returns them as (pub, priv). The public key is also known as the 'encryption key', and is a :py:class:`adafruit_rsa.rsa.PublicKey` object. The private key is also known as the 'decryption key' and is a :py:class:`adafruit_rsa.rsa.PrivateKey` object. - :param nbits: the number of bits required to store ``n = p*q``. - :param accurate: when True, ``n`` will have exactly the number of bits you + :param int nbits: the number of bits required to store ``n = p*q``. + :param bool accurate: when True, ``n`` will have exactly the number of bits you asked for. However, this makes key generation much slower. When False, - `n`` may have slightly less bits. - :param poolsize: the number of processes to use to generate the prime + ``n`` may have slightly less bits. + :param int poolsize: the number of processes to use to generate the prime numbers. - :param exponent: the exponent for the key; only change this if you know + :param int exponent: the exponent for the key; only change this if you know what you're doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537. - :type exponent: int - :param log_level: Logger level, setting to DEBUG will log info about when + :param str log_level: Logger level, setting to DEBUG will log info about when p and q are generating. - :returns: a tuple (:py:class:`adafruit_rsa.PublicKey`, :py:class:`adafruit_rsa.PrivateKey`) + :return: a tuple (:py:class:`adafruit_rsa.PublicKey`, :py:class:`adafruit_rsa.PrivateKey`) The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires Python 2.6 or newer. diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index 2dd2239..ac9317c 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -1,13 +1,27 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Detection of 32-bit and 64-bit machines and byte alignment.""" +""" +`adafruit_rsa.machine_size` +==================================================== + +Detection of 32-bit and 64-bit machines and byte alignment. +""" import sys -__version__ = "0.0.0-auto.0" +try: + from typing import Tuple + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" MAX_INT = sys.maxsize @@ -27,12 +41,16 @@ MACHINE_WORD_SIZE = 64 -def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE): +def get_word_alignment( + num: int, + force_arch: int = 64, + _machine_word_size: Literal[64, 32] = MACHINE_WORD_SIZE, +) -> Tuple[int, int, int, str]: """ Returns alignment details for the given number based on the platform Python is running on. - :param num: + :param int num: Unsigned integral number. :param force_arch: If you don't want to use 64-bit unsigned chunks, set this to @@ -40,7 +58,7 @@ def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE) Default 64 will be used when on a 64-bit machine. :param _machine_word_size: (Internal) The machine word size used for alignment. - :returns: + :return: 4-tuple:: (word_bits, word_bytes, diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index daaaa5e..99d9cf7 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -1,19 +1,28 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Functions that load and write PEM-encoded files.""" +""" +`adafruit_rsa.pem` +==================================================== + +Functions that load and write PEM-encoded files. +""" + from adafruit_binascii import a2b_base64, b2a_base64 -# pylint: disable=redefined-builtin from adafruit_rsa._compat import is_bytes -__version__ = "0.0.0-auto.0" +try: + from typing import Tuple, Union +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -def _markers(pem_marker): +def _markers(pem_marker: Union[bytes, str]) -> Tuple[bytes, bytes]: """ Returns the start and end PEM markers, as bytes. """ @@ -27,11 +36,11 @@ def _markers(pem_marker): ) -def load_pem(contents, pem_marker): +def load_pem(contents: Union[bytes, str], pem_marker: Union[bytes, str]) -> bytes: """Loads a PEM file. - :param contents: the contents of the file to interpret - :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' + :param bytes|str contents: the contents of the file to interpret + :param bytes|str pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' when your file has '-----BEGIN RSA PRIVATE KEY-----' and '-----END RSA PRIVATE KEY-----' markers. @@ -93,10 +102,10 @@ def load_pem(contents, pem_marker): return a2b_base64(pem) -def save_pem(contents, pem_marker): +def save_pem(contents: bytes, pem_marker: Union[bytes, str]) -> bytes: """Saves a PEM file. - :param contents: the contents to encode in PEM format + :param bytes contents: the contents to encode in PEM format :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' when your file has '-----BEGIN RSA PRIVATE KEY-----' and '-----END RSA PRIVATE KEY-----' markers. diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index 8b7339e..28db849 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -1,9 +1,12 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Functions for PKCS#1 version 1.5 encryption and signing +""" +`adafruit_rsa.pkcs1` +==================================================== + +Functions for PKCS#1 version 1.5 encryption and signing This module implements certain functionality from PKCS#1 version 1.5. For a very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes @@ -16,11 +19,38 @@ deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION to your users. """ + import os + import adafruit_hashlib as hashlib -from adafruit_rsa import common, transform, core -__version__ = "0.0.0-auto.0" +from adafruit_rsa import common, core, transform + +try: + from typing import Iterator, Optional, Union + + from adafruit_rsa.key import PrivateKey, PublicKey + + try: + from typing import Protocol + except ImportError: + from typing_extensions import Protocol + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal + + class _FileLikeObject(Protocol): + """A file like object that implements the :meth:`read` method""" + + def read(self, blocksize: int) -> Union[bytes, str]: + """A method that reads a given number of bytes or chracters""" + +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" # ASN.1 codes that describe the hash algorithm used. @@ -55,10 +85,13 @@ class VerificationError(CryptoError): """Raised when verification fails.""" -def _pad_for_encryption(message, target_length): +def _pad_for_encryption(message: bytes, target_length: int) -> bytes: r"""Pads the message for encryption, returning the padded message. + :param bytes message: The message + :param int target_length: The length of the padded message :return: 00 02 RANDOM_DATA 00 MESSAGE + :rtype: bytes >>> block = _pad_for_encryption(b'hello', 16) >>> len(block) @@ -100,12 +133,15 @@ def _pad_for_encryption(message, target_length): return b"".join([b"\x00\x02", padding, b"\x00", message]) -def _pad_for_signing(message, target_length): +def _pad_for_signing(message: bytes, target_length: int) -> bytes: r"""Pads the message for signing, returning the padded message. The padding is always a repetition of FF bytes. + :param bytes message: The message to pad + :param int target_length: The length to pad the message :return: 00 01 PADDING 00 MESSAGE + :rtype: bytes >>> block = _pad_for_signing(b'hello', 16) >>> len(block) @@ -133,13 +169,13 @@ def _pad_for_signing(message, target_length): return b"".join([b"\x00\x01", padding_length * b"\xff", b"\x00", message]) -def encrypt(message, pub_key): +def encrypt(message: bytes, pub_key: PublicKey) -> bytes: """Encrypts the given message using PKCS#1 v1.5 - :param message: the message to encrypt. Must be a byte string no longer than + :param bytes message: the message to encrypt. Must be a byte string no longer than ``k-11`` bytes, where ``k`` is the number of bytes needed to encode the ``n`` component of the public key. - :param pub_key: the :py:class:`adafruit_rsaPublicKey` to encrypt with. + :param PublicKey pub_key: the :py:class:`adafruit_rsaPublicKey` to encrypt with. :raise OverflowError: when the message is too large to fit in the padded block. @@ -164,15 +200,15 @@ def encrypt(message, pub_key): return block -def decrypt(crypto, priv_key): +def decrypt(crypto: bytes, priv_key: PrivateKey) -> bytes: """Decrypts the given message using PKCS#1 v1.5 The decryption is considered 'failed' when the resulting cleartext doesn't start with the bytes 00 02, or when the 00 byte between the padding and the message cannot be found. - :param crypto: the crypto text as returned by :py:func:`adafruit_rsaencrypt` - :param priv_key: the :py:class:`adafruit_rsaPrivateKey` to decrypt with. + :param bytes crypto: the crypto text as returned by :py:func:`adafruit_rsaencrypt` + :param PrivateKey priv_key: the :py:class:`adafruit_rsaPrivateKey` to decrypt with. :raise DecryptionError: when the decryption fails. No details are given as to why the code thinks the decryption fails, as this would leak information about the private key. @@ -229,15 +265,19 @@ def decrypt(crypto, priv_key): return cleartext[sep_idx + 1 :] -def sign_hash(hash_value, priv_key, hash_method): +def sign_hash( + hash_value: Optional[bytes], + priv_key: PrivateKey, + hash_method: Literal["MD5", "SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512"], +) -> bytes: """Signs a precomputed hash with the private key. Hashes the message, then signs the hash with the given key. This is known as a "detached signature", because the message itself isn't altered. - :param hash_value: A precomputed hash to sign (ignores message). Should be set to - None if needing to hash and sign message. - :param priv_key: the :py:class:`adafruit_rsaPrivateKey` to sign with + :param bytes hash_value: A precomputed hash to sign (ignores message). Should be + set to ``None`` if needing to hash and sign message. + :param PrivateKey priv_key: the :py:class:`adafruit_rsaPrivateKey` to sign with :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. :return: a message signature block. @@ -263,7 +303,7 @@ def sign_hash(hash_value, priv_key, hash_method): return block -def sign(message, priv_key, hash_method): +def sign(message: Union[bytes, _FileLikeObject], priv_key: PrivateKey, hash_method: str) -> bytes: """Signs the message with the private key. Hashes the message, then signs the hash with the given key. This is known @@ -272,7 +312,8 @@ def sign(message, priv_key, hash_method): :param message: the message to sign. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. - :param priv_key: the :py:class:`adafruit_rsaPrivateKey` to sign with + :param PrivateKey priv_key: the :py:class:`adafruit_rsaPrivateKey` to sign + with :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. :return: a message signature block. @@ -285,7 +326,7 @@ def sign(message, priv_key, hash_method): return sign_hash(msg_hash, priv_key, hash_method) -def verify(message, signature, pub_key): +def verify(message: Union[bytes, _FileLikeObject], signature: bytes, pub_key: PublicKey) -> str: """Verifies that the signature matches the message. The hash method is detected automatically from the signature. @@ -293,10 +334,11 @@ def verify(message, signature, pub_key): :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. - :param signature: the signature block, as created with :py:func:`rsa.sign`. - :param pub_key: the :py:class:`adafruit_rsaPublicKey` of the person signing the message. + :param bytes signature: the signature block, as created with :py:func:`rsa.sign`. + :param PublicKey pub_key: the :py:class:`adafruit_rsaPublicKey` of the person + signing the message. :raise VerificationError: when the signature doesn't match the message. - :returns: the name of the used hash. + :return: the name of the used hash. """ @@ -320,15 +362,17 @@ def verify(message, signature, pub_key): return method_name -def find_signature_hash(signature, pub_key): +def find_signature_hash(signature: bytes, pub_key: PublicKey) -> str: """Returns the hash name detected from the signature. If you also want to verify the message, use :py:func:`adafruit_rsaverify()` instead. It also returns the name of the used hash. - :param signature: the signature block, as created with :py:func:`adafruit_rsasign`. - :param pub_key: the :py:class:`adafruit_rsaPublicKey` of the person signing the message. - :returns: the name of the used hash. + :param bytes signature: the signature block, as created with + :py:func:`adafruit_rsasign`. + :param PublicKey pub_key: the :py:class:`adafruit_rsaPublicKey` + of the person signing the message. + :return: the name of the used hash. """ keylength = common.byte_size(pub_key.n) @@ -339,12 +383,12 @@ def find_signature_hash(signature, pub_key): return _find_method_hash(clearsig) -def yield_fixedblocks(infile, blocksize): +def yield_fixedblocks(infile: _FileLikeObject, blocksize: int) -> Iterator[Union[bytes, str]]: """Generator, yields each block of ``blocksize`` bytes in the input file. - :param infile: file to read and separate in blocks. - :param blocksize: block size in bytes. - :returns: a generator that yields the contents of each block + :param TextIOWrapper infile: file to read and separate in blocks. + :param int blocksize: block size in bytes. + :return: a generator that yields the contents of each block """ while True: @@ -360,7 +404,7 @@ def yield_fixedblocks(infile, blocksize): break -def compute_hash(message, method_name): +def compute_hash(message: Union[bytes, str, _FileLikeObject], method_name: str) -> bytes: """Returns the message digest. :param message: the signed message. Can be an 8-bit string or a file-like @@ -368,7 +412,6 @@ def compute_hash(message, method_name): file-like object. :param method_name: the hash method, must be a key of :py:const:`HASH_METHODS`. - """ if method_name not in HASH_METHODS: @@ -388,15 +431,15 @@ def compute_hash(message, method_name): return hasher.digest() -def _find_method_hash(clearsig): +def _find_method_hash(clearsig: bytes) -> str: """Finds the hash method. - :param clearsig: full padded ASN1 and hash. + :param bytes clearsig: full padded ASN1 and hash. :return: the used hash method. :raise VerificationFailed: when the hash method cannot be found """ - for (hashname, asn1code) in HASH_ASN1.items(): + for hashname, asn1code in HASH_ASN1.items(): if asn1code in clearsig: return hashname diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 003719b..bf8aacf 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -1,24 +1,35 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Numerical functions related to primes. +""" +`adafruit_rsa.prime` +==================================================== + +Numerical functions related to primes. Implementation based on the book Algorithm Design by Michael T. Goodrich and Roberto Tamassia, 2002. """ -# pylint: disable=invalid-name + import adafruit_rsa.common import adafruit_rsa.randnum -__version__ = "0.0.0-auto.0" +try: + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" __all__ = ["getprime", "are_relatively_prime"] -def gcd(p, q): +def gcd(p: int, q: int) -> int: """Returns the greatest common divisor of p and q >>> gcd(48, 180) @@ -30,7 +41,7 @@ def gcd(p, q): return p -def get_primality_testing_rounds(number): +def get_primality_testing_rounds(number: int) -> Literal[3, 4, 7, 10]: """Returns minimum number of rounds for Miller-Rabing primality testing, based on number bitsize. @@ -56,7 +67,7 @@ def get_primality_testing_rounds(number): return 10 -def miller_rabin_primality_testing(n, k): +def miller_rabin_primality_testing(n: int, k: int) -> bool: """Calculates whether n is composite (which is always correct) or prime (which theoretically is incorrect with error probability 4**-k), by applying Miller-Rabin primality testing. @@ -64,10 +75,8 @@ def miller_rabin_primality_testing(n, k): For reference and implementation example, see: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - :param n: Integer to be tested for primality. - :type n: int - :param k: Number of rounds (witnesses) of Miller-Rabin testing. - :type k: int + :param int n: Integer to be tested for primality. + :param int k: Number of rounds (witnesses) of Miller-Rabin testing. :return: False if the number is composite, True if it's probably prime. :rtype: bool """ @@ -92,7 +101,7 @@ def miller_rabin_primality_testing(n, k): x = adafruit_rsa.core.fast_pow(a, d, n) - if x in (1, n - 1): + if x in {1, n - 1}: continue for _ in range(r - 1): @@ -109,7 +118,7 @@ def miller_rabin_primality_testing(n, k): return True -def pow_mod(x, y, z): +def pow_mod(x: int, y: int, z: int) -> int: "Calculate (x ** y) % z efficiently." number = 1 while y: @@ -120,7 +129,7 @@ def pow_mod(x, y, z): return number -def is_prime(number): +def is_prime(number: int) -> bool: """Returns True if the number is prime, and False otherwise. >>> is_prime(2) @@ -146,7 +155,7 @@ def is_prime(number): return miller_rabin_primality_testing(number, k + 1) -def getprime(nbits): +def getprime(nbits: int) -> int: """Returns a prime number that can be stored in 'nbits' bits. >>> p = getprime(128) @@ -174,7 +183,7 @@ def getprime(nbits): # Retry if not prime -def are_relatively_prime(a, b): +def are_relatively_prime(a: int, b: int) -> bool: """Returns True if a and b are relatively prime, and False if they are not. diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index 6fddb4b..3614c98 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -1,9 +1,13 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Functions for generating random numbers.""" +""" +`adafruit_rsa.randnum` +==================================================== + +Functions for generating random numbers. +""" # Source inspired by code by Yesudeep Mangalapilly @@ -12,11 +16,11 @@ from adafruit_rsa import common, transform from adafruit_rsa._compat import byte -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -def read_random_bits(nbits): +def read_random_bits(nbits: int) -> bytes: """Reads 'nbits' random bits. If nbits isn't a whole number of bytes, an extra byte will be appended with @@ -37,7 +41,7 @@ def read_random_bits(nbits): return randomdata -def read_random_int(nbits): +def read_random_int(nbits: int) -> int: """Reads a random integer of approximately nbits bits.""" randomdata = read_random_bits(nbits) @@ -50,7 +54,7 @@ def read_random_int(nbits): return value -def read_random_odd_int(nbits): +def read_random_odd_int(nbits: int) -> int: """Reads a random odd integer of approximately nbits bits. >>> read_random_odd_int(512) & 1 @@ -63,7 +67,7 @@ def read_random_odd_int(nbits): return value | 1 -def randint(maxvalue): +def randint(maxvalue: int) -> int: """Returns a random integer x with 1 <= x <= maxvalue May take a very long time in specific situations. If maxvalue needs N bits diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index a94828c..c655607 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -1,9 +1,12 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 -"""Data transformation functions. +""" +`adafruit_rsa.transform` +==================================================== + +Data transformation functions. From bytes to a number, number to bytes, etc. """ @@ -11,16 +14,22 @@ # from __future__ import absolute_import from struct import pack + import adafruit_binascii as binascii -from adafruit_rsa._compat import byte, is_integer from adafruit_rsa import common, machine_size +from adafruit_rsa._compat import byte, is_integer -__version__ = "0.0.0-auto.0" +try: + from typing import Optional +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -def bytes2int(raw_bytes): +def bytes2int(raw_bytes: bytes) -> int: """Converts a list of bytes or an 8-bit string to an integer. When using unicode strings, encode it to some encoding like UTF8 first. @@ -35,7 +44,7 @@ def bytes2int(raw_bytes): return int(binascii.hexlify(raw_bytes), 16) -def _int2bytes(number, block_size=None): +def _int2bytes(number: int, block_size: Optional[int] = None) -> bytes: """Converts a number to a string of bytes. Usage:: @@ -66,9 +75,7 @@ def _int2bytes(number, block_size=None): # Type checking if not is_integer(number): - raise TypeError( - "You must pass an integer for 'number', not %s" % number.__class__ - ) + raise TypeError("You must pass an integer for 'number', not %s" % number.__class__) if number < 0: raise ValueError("Negative numbers cannot be used: %i" % number) @@ -85,8 +92,7 @@ def _int2bytes(number, block_size=None): if block_size and block_size > 0: if needed_bytes > block_size: raise OverflowError( - "Needed %i bytes for number, but block size " - "is %i" % (needed_bytes, block_size) + "Needed %i bytes for number, but block size " "is %i" % (needed_bytes, block_size) ) # Convert the number to bytes. @@ -103,17 +109,17 @@ def _int2bytes(number, block_size=None): return padding + b"".join(raw_bytes) -def bytes_leading(raw_bytes, needle=b"\x00"): +def bytes_leading(raw_bytes: bytes, needle: bytes = b"\x00") -> int: """ Finds the number of prefixed byte occurrences in the haystack. Useful when you want to deal with padding. - :param raw_bytes: + :param bytes raw_bytes: Raw bytes. - :param needle: + :param bytes needle: The byte to count. Default \x00. - :returns: + :return: The number of leading needle bytes. """ @@ -128,15 +134,23 @@ def bytes_leading(raw_bytes, needle=b"\x00"): return leading -def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): +def int2bytes( + number: int, + fill_size: Optional[int] = None, + chunk_size: Optional[int] = None, + overflow: bool = False, +) -> bytes: """ Convert an unsigned integer to bytes (base-256 representation):: Does not preserve leading zeros if you don't specify a chunk size or fill size. + .. NOTE: + You must not specify both fill_size and chunk_size. Only one of them is allowed. - :param number: + + :param int number: Integer value :param fill_size: If the optional fill size is given the length of the resulting @@ -151,7 +165,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): will be raised when the fill_size is shorter than the length of the generated byte sequence. Instead the byte sequence will be returned as is. - :returns: + :return: Raw bytes (base-256 representation). :raises: ``OverflowError`` when fill_size is given and the number takes up more @@ -196,5 +210,5 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): remainder = length % chunk_size if remainder: padding_size = chunk_size - remainder - raw_bytes = "% {}s".format(length + padding_size).encode() % raw_bytes + raw_bytes = f"% {length + padding_size}s".encode() % raw_bytes return raw_bytes diff --git a/docs/api.rst b/docs/api.rst index 5c3e39f..b6f0821 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,9 +1,46 @@ -Adafruit CircuitPython RSA API -=============================== .. If you created a package, create one automodule per module in the package. .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" +API Reference +############# + .. automodule:: adafruit_rsa :members: + +.. automodule:: adafruit_rsa._compat + :members: + +.. automodule:: adafruit_rsa.asn1 + + .. autoclass:: PubKeyHeader + .. autoclass:: OpenSSLPubKey + .. autoclass:: AsnPubKey + +.. automodule:: adafruit_rsa.common + :members: + +.. automodule:: adafruit_rsa.core + :members: + +.. automodule:: adafruit_rsa.key + :members: + +.. automodule:: adafruit_rsa.machine_size + :members: + +.. automodule:: adafruit_rsa.pem + :members: + +.. automodule:: adafruit_rsa.pkcs1 + :members: + +.. automodule:: adafruit_rsa.prime + :members: + +.. automodule:: adafruit_rsa.randnum + :members: + +.. automodule:: adafruit_rsa.transform + :members: diff --git a/docs/conf.py b/docs/conf.py index 0ae8873..bf106cc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,9 +1,8 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys @@ -16,6 +15,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -29,8 +29,8 @@ intersphinx_mapping = { - "python": ("https://docs.python.org/3.4", None), - "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), + "python": ("https://docs.python.org/3", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), } # Add any paths that contain templates here, relative to this directory. @@ -43,7 +43,12 @@ # General information about the project. project = "Adafruit RSA Library" -copyright = "2019 Brent Rubell" +creation_year = "2019" +current_year = str(datetime.datetime.now().year) +year_duration = ( + current_year if current_year == creation_year else creation_year + " - " + current_year +) +copyright = year_duration + " Brent Rubell" author = "Brent Rubell" # The version info for the project you're documenting, acts as replacement for @@ -60,7 +65,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -92,19 +97,9 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -if not on_rtd: # only import and set the theme if we're building docs locally - try: - import sphinx_rtd_theme - - html_theme = "sphinx_rtd_theme" - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] - except: - html_theme = "default" - html_theme_path = ["."] -else: - html_theme_path = ["."] +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, diff --git a/docs/index.rst b/docs/index.rst index 2c1731a..18bda77 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,8 +31,9 @@ Table of Contents .. toctree:: :caption: Other Links - Download - CircuitPython Reference Documentation + Download from GitHub + Download Library Bundle + CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat Adafruit Learning System diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..979f568 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/keys/example512key.json b/examples/keys/example512key.json new file mode 100644 index 0000000..37325ac --- /dev/null +++ b/examples/keys/example512key.json @@ -0,0 +1 @@ +{"private_key_arguments": [10802924268999465233003672463737659932191279041133968058923436754367015686828567560383989892160402220695228233889545658683964318629332408693761505895756447, 65537, 6603041646208715356266858592129685239844946455128316714288951729655521528037145487273616012885516521612688207348765184497451491506274914199323595424930097, 112900874195215049358818352411672948770646187545424444301451131703364915854523, 95685036506628869041897601422905615595924763394819122702857010830658994689389]} diff --git a/examples/keys/example512key.json.license b/examples/keys/example512key.json.license new file mode 100644 index 0000000..936829b --- /dev/null +++ b/examples/keys/example512key.json.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks +# SPDX-License-Identifier: MIT diff --git a/examples/keys/example512key_pub.json b/examples/keys/example512key_pub.json new file mode 100644 index 0000000..ed0316f --- /dev/null +++ b/examples/keys/example512key_pub.json @@ -0,0 +1 @@ +{"public_key_arguments": [10802924268999465233003672463737659932191279041133968058923436754367015686828567560383989892160402220695228233889545658683964318629332408693761505895756447, 65537]} diff --git a/examples/keys/example512key_pub.json.license b/examples/keys/example512key_pub.json.license new file mode 100644 index 0000000..936829b --- /dev/null +++ b/examples/keys/example512key_pub.json.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks +# SPDX-License-Identifier: MIT diff --git a/examples/rsa_generate_json_keys.py b/examples/rsa_generate_json_keys.py new file mode 100644 index 0000000..0f2c898 --- /dev/null +++ b/examples/rsa_generate_json_keys.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks +# SPDX-License-Identifier: MIT +""" +This script can be used to generate a new key pair and output them as JSON. +You can copy the JSON from serial console and paste it into a new file +on the device and then use it with the rsa_json_keys.py example. +""" + +import json + +import adafruit_rsa + +# Create a keypair +print("Generating keypair...") +(public_key, private_key) = adafruit_rsa.newkeys(512) + + +print("public json:") +print("-------------------------------") +public_obj = {"public_key_arguments": [public_key.n, public_key.e]} +print(json.dumps(public_obj)) +print("-------------------------------") + + +print("private json:") +print("-------------------------------") +private_obj = { + "private_key_arguments": [ + private_key.n, + private_key.e, + private_key.d, + private_key.p, + private_key.q, + ] +} +print(json.dumps(private_obj)) +print("-------------------------------") diff --git a/examples/rsa_json_keys.py b/examples/rsa_json_keys.py new file mode 100644 index 0000000..6c2adf8 --- /dev/null +++ b/examples/rsa_json_keys.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks +# SPDX-License-Identifier: MIT +import binascii +import json + +import adafruit_rsa +from adafruit_rsa import PrivateKey, PublicKey + +""" +CircuitPython microcontrollers cannot load PEM key files generated by OpenSSL +because the pyasn1 module is not supported. This example illustrates a way +of loading keys from JSON files instead. +""" + +# load a keypair from JSON files + +with open("keys/example512key.json") as f: + priv_key_obj = json.loads(f.read()) + + +with open("keys/example512key_pub.json") as f: + pub_key_obj = json.loads(f.read()) + + +# initialize the Key objects from data that was loaded from the JSON files +public_key = PublicKey(*pub_key_obj["public_key_arguments"]) +private_key = PrivateKey(*priv_key_obj["private_key_arguments"]) + +# Message to send +message = "hello blinka" + +# Encode the string as bytes (Adafruit_RSA only operates on bytes!) +message = message.encode("utf-8") + +# Encrypt the message using the public key +print("Encrypting message...") +encrypted_message = adafruit_rsa.encrypt(message, public_key) + +print("encrypted b64: ") +print(binascii.b2a_base64(encrypted_message, False).decode()) + +# Decrypt the encrypted message using a private key +print("Decrypting message...") +decrypted_message = adafruit_rsa.decrypt(encrypted_message, private_key) + +# Print out the decrypted message +print("Decrypted Message: ", decrypted_message.decode("utf-8")) diff --git a/examples/rsa_sign_verify.py b/examples/rsa_sign_verify.py index b08a493..d9a57a6 100755 --- a/examples/rsa_sign_verify.py +++ b/examples/rsa_sign_verify.py @@ -21,6 +21,4 @@ # Verify Message Signature if adafruit_rsa.verify(message, signature, public_key) != hash_method: - raise ValueError( - "Verification failed - signature does not match secret message sent!" - ) + raise ValueError("Verification failed - signature does not match secret message sent!") diff --git a/examples/rsa_tests.py b/examples/rsa_tests.py index c789caf..7863c8c 100755 --- a/examples/rsa_tests.py +++ b/examples/rsa_tests.py @@ -1,16 +1,17 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -"""Adafruit RSA Tests -""" +"""Adafruit RSA Tests""" + import time + import adafruit_rsa def test_encrypt_decrypt(): # Generate general purpose keys (pub, priv) = adafruit_rsa.newkeys(256, log_level="DEBUG") - msg = "blinka".encode("utf-8") + msg = b"blinka" msg_enc = adafruit_rsa.encrypt(msg, pub) msg_dec = adafruit_rsa.decrypt(msg_enc, priv) assert msg == msg_dec, "Decrypted message does not match original message" @@ -20,22 +21,21 @@ def test_mod_msg(): """Modifies an enecrypted message, asserts failure""" # Generate general purpose keys (pub, priv) = adafruit_rsa.newkeys(256, log_level="DEBUG") - msg = "blinka".encode("utf-8") + msg = b"blinka" msg_enc = adafruit_rsa.encrypt(msg, pub) msg_enc = msg_enc[:-1] + b"X" # change the last byte try: - adafruit_rsa.decrypt(msg_enc, priv) - raise "ERROR: Decrypted message matches original" + msg_dec = adafruit_rsa.decrypt(msg_enc, priv) + assert msg_dec != msg, "ERROR: Decrypted message matches original" except adafruit_rsa.pkcs1.DecryptionError: pass -# pylint: disable=unused-variable def test_randomness(): """Encrypt msg 2x yields diff. encrypted values.""" # Generate general purpose keys (pub, priv) = adafruit_rsa.newkeys(256, log_level="DEBUG") - msg = "blinka".encode("utf-8") + msg = b"blinka" msg_enc_1 = adafruit_rsa.encrypt(msg, pub) msg_enc_2 = adafruit_rsa.encrypt(msg, pub) assert msg_enc_1 != msg_enc_2, "Messages should yield different values." @@ -93,12 +93,9 @@ def test_sign_verify_fail(): # Run adafruit_rsa tests start_time = time.monotonic() -# pylint: disable=consider-using-enumerate -for test_num, test_name in enumerate(all_tests, start=0): +for test_name in all_tests: # for i in range(0, len(all_tests)): - print("Testing: {}".format(test_name)) - all_tests[test_num]() + print(f"Testing: {test_name}") + test_name() print("OK!") -print( - "Ran {} tests in {} seconds".format(len(all_tests), time.monotonic() - start_time) -) +print(f"Ran {len(all_tests)} tests in {time.monotonic() - start_time} seconds") diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..d4e27c4 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..4e9b32b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-rsa" +description = "RSA implementation based on python-rsa" +version = "0.0.0+auto.0" +readme = "README.rst" +authors = [ + {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} +] +urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_RSA"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "rsa", + "rsa,", + "encryption,", + "cryptography", +] +license = {text = "MIT"} +classifiers = [ + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Embedded Systems", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", +] +dynamic = ["dependencies", "optional-dependencies"] + +[tool.setuptools] +packages = ["adafruit_rsa"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index 17a850d..6ac8bc8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,8 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # # SPDX-License-Identifier: Unlicense -Adafruit-Blinka +Adafruit-Blinka>=7.0.0 +pyasn1 +adafruit-circuitpython-logging>=4.0.0 +adafruit-circuitpython-hashlib diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..a9c2ec9 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions + "PLR6301", # could-be-static no-self-use + "PLC0415", # import outside toplevel + "PLC2701", # private import + "PLW2901", # loop var overwrite + "F841", # var assigned not used + "E722", # bare except +] + +[format] +line-ending = "lf" diff --git a/setup.py b/setup.py deleted file mode 100644 index 13a0dca..0000000 --- a/setup.py +++ /dev/null @@ -1,57 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -"""A setuptools based setup module. - -See: -https://packaging.python.org/en/latest/distributing.html -https://github.com/pypa/sampleproject -""" - -from setuptools import setup, find_packages - -# To use a consistent encoding -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, "README.rst"), encoding="utf-8") as f: - long_description = f.read() - -setup( - name="adafruit-circuitpython-rsa", - use_scm_version=True, - setup_requires=["setuptools_scm"], - description="RSA implementation based on python-rsa", - long_description=long_description, - long_description_content_type="text/x-rst", - # The project's main homepage. - url="https://github.com/adafruit/Adafruit_CircuitPython_RSA", - # Author details - author="Adafruit Industries", - author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka"], - # Choose your license - license="MIT", - # See https://pypi.python.org/pypi?%3Aaction=list_classifiers - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries", - "Topic :: System :: Hardware", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - ], - # What does your project relate to? - keywords="adafruit blinka circuitpython micropython rsa rsa, encryption, cryptography", - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, - # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=["adafruit_rsa"], -) diff --git a/util/decode_priv_key.py b/util/decode_priv_key.py index c756ba2..423d186 100644 --- a/util/decode_priv_key.py +++ b/util/decode_priv_key.py @@ -8,7 +8,7 @@ =================================================================== Generates RSA keys and decodes them using python-rsa -for use with a CircuitPython secrets file. +for use with a CircuitPython settings.toml file. This script is designed to run on a computer, NOT a CircuitPython device. @@ -17,24 +17,26 @@ * Author(s): Google Inc., Brent Rubell """ + import subprocess + import rsa # Generate private and public RSA keys -proc = subprocess.Popen(["openssl", "genrsa", "-out", "rsa_private.pem", "2048"]) -proc.wait() -proc = subprocess.Popen( +with subprocess.Popen(["openssl", "genrsa", "-out", "rsa_private.pem", "2048"]) as proc: + proc.wait() +with subprocess.Popen( ["openssl", "rsa", "-in", "rsa_private.pem", "-pubout", "-out", "rsa_public.pem"] -) -proc.wait() +) as proc: + proc.wait() # Open generated private key file try: with open("rsa_private.pem", "rb") as file: private_key = file.read() -except: # pylint: disable=bare-except +except: print("No file named rsa_private.pem found in directory.") pk = rsa.PrivateKey.load_pkcs1(private_key) -print("Copy and paste this into your secrets.py file:\n") -print('"private_key": ' + str(pk)[10:] + ",") +print("Copy and paste this into your settings.toml file:\n") +print(f'private_key="{str(pk)[10:]}"')