From a7d82cc0b1ae24ef636096c014ada6ad5bc46ab0 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 19 May 2021 13:32:42 -0400 Subject: [PATCH 01/81] Added pull request template Signed-off-by: dherrada --- .../adafruit_circuitpython_pr.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md 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..71ef8f8 --- /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://circuitpython.readthedocs.io/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. From 290904bf810f77c5d0e71189869d8b543f9b7a2e Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 19 May 2021 13:35:18 -0400 Subject: [PATCH 02/81] Added help text and problem matcher Signed-off-by: dherrada --- .github/workflows/build.yml | 2 ++ .github/workflows/failure-help-text.yml | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 .github/workflows/failure-help-text.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3baf502..0ab7182 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -71,3 +71,5 @@ jobs: python setup.py sdist python setup.py bdist_wheel --universal twine check dist/* + - name: Setup problem matchers + uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 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 From 6f473f8e973b237987fa6fd13a566c73667d0e4b Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 24 May 2021 09:54:31 -0400 Subject: [PATCH 03/81] Moved CI to Python 3.7 Signed-off-by: dherrada --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0ab7182..c4c975d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,10 +22,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.6 + - name: Set up Python 3.7 uses: actions/setup-python@v1 with: - python-version: 3.6 + python-version: 3.7 - name: Versions run: | python3 --version From 8c19e58931bc4f3b258b300dee761c3ea33828da Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 2 Jun 2021 14:15:55 -0400 Subject: [PATCH 04/81] Moved default branch to main --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index fca96fb..d9c01ec 100644 --- a/README.rst +++ b/README.rst @@ -61,7 +61,7 @@ Contributing ============ Contributions are welcome! Please read our `Code of Conduct -`_ +`_ before contributing to help this project stay welcoming. Documentation From 952ee5f672046c83a45a9300e9f45a3f1182bdd2 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 23 Sep 2021 17:52:55 -0400 Subject: [PATCH 05/81] Globally disabled consider-using-f-string pylint check Signed-off-by: dherrada --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 354c761..8810708 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,5 +30,5 @@ repos: 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)'] + args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name,consider-using-f-string $example; done)'] language: system From 0f52518d19a1fbce13ab5dc8d7cc1fb9bd3ce7da Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 25 Oct 2021 11:30:35 -0500 Subject: [PATCH 06/81] add docs link to readme --- README.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.rst b/README.rst index d9c01ec..50a8e76 100644 --- a/README.rst +++ b/README.rst @@ -57,6 +57,11 @@ 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 `_. + Contributing ============ From f2ed7c0299f0de9826b5a85634e8b8705d35fcb8 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 3 Nov 2021 14:40:16 -0400 Subject: [PATCH 07/81] PATCH Pylint and readthedocs patch test Signed-off-by: dherrada --- .github/workflows/build.yml | 4 ++-- .pre-commit-config.yaml | 26 +++++++++++++++++--------- .pylintrc | 2 +- .readthedocs.yml | 2 +- docs/requirements.txt | 5 +++++ 5 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 docs/requirements.txt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c4c975d..ca35544 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,9 +42,9 @@ jobs: # (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 + - name: Pip install Sphinx, pre-commit run: | - pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit + pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - name: Library version run: git describe --dirty --always --tags - name: Pre-commit hooks diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8810708..1b9fadc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,17 +18,25 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: pylint-2.7.1 + rev: v2.11.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) + args: + - --disable=consider-using-f-string + exclude: "^(docs/|examples/|tests/|setup.py$)" + - id: pylint + name: pylint (example 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,consider-using-f-string $example; done)'] - language: system + types: [python] + files: "^examples/" + args: + - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code + - id: pylint + name: pylint (test code) + description: Run pylint rules on "tests/*.py" files + types: [python] + files: "^tests/" + args: + - --disable=missing-docstring,consider-using-f-string,duplicate-code diff --git a/.pylintrc b/.pylintrc index 0238b90..e78bad2 100644 --- a/.pylintrc +++ b/.pylintrc @@ -252,7 +252,7 @@ ignore-docstrings=yes ignore-imports=yes # Minimum lines number of a similarity. -min-similarity-lines=12 +min-similarity-lines=4 [BASIC] diff --git a/.readthedocs.yml b/.readthedocs.yml index ffa84c4..49dcab3 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -4,4 +4,4 @@ python: version: 3 -requirements_file: requirements.txt +requirements_file: docs/requirements.txt diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..88e6733 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx>=4.0.0 From efbaa434918affce3c4c13cfa7ae093753099b6a Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 5 Nov 2021 14:49:30 -0400 Subject: [PATCH 08/81] Disabled unspecified-encoding pylint check Signed-off-by: dherrada --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index e78bad2..cfd1c41 100644 --- a/.pylintrc +++ b/.pylintrc @@ -55,7 +55,7 @@ confidence= # 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 +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,unspecified-encoding # 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 From 0c425c9c9be096e1cb821036654f3f5ae0f141f8 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 8 Nov 2021 13:15:17 -0500 Subject: [PATCH 09/81] Linted --- .pre-commit-config.yaml | 2 +- examples/rsa_tests.py | 4 ++-- util/decode_priv_key.py | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1b9fadc..43d1385 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: name: pylint (library code) types: [python] args: - - --disable=consider-using-f-string + - --disable=consider-using-f-string,duplicate-code exclude: "^(docs/|examples/|tests/|setup.py$)" - id: pylint name: pylint (example code) diff --git a/examples/rsa_tests.py b/examples/rsa_tests.py index c789caf..177b7e9 100755 --- a/examples/rsa_tests.py +++ b/examples/rsa_tests.py @@ -24,8 +24,8 @@ def test_mod_msg(): 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 diff --git a/util/decode_priv_key.py b/util/decode_priv_key.py index c756ba2..c673c42 100644 --- a/util/decode_priv_key.py +++ b/util/decode_priv_key.py @@ -21,12 +21,12 @@ 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: From ca2a2788ed97afb3e2e77856161b92db8be1f9b8 Mon Sep 17 00:00:00 2001 From: dherrada Date: Tue, 9 Nov 2021 13:31:14 -0500 Subject: [PATCH 10/81] Updated readthedocs file Signed-off-by: dherrada --- .readthedocs.yaml | 15 +++++++++++++++ .readthedocs.yml | 7 ------- 2 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 .readthedocs.yaml delete mode 100644 .readthedocs.yml diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..95ec218 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,15 @@ +# 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 + +python: + version: "3.6" + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 49dcab3..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: docs/requirements.txt From b0f29dfc9ecd2db9516b7a22eca13a2499d4d838 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 23 Nov 2021 13:16:20 -0600 Subject: [PATCH 11/81] update rtd py version --- .readthedocs.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 95ec218..1335112 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -9,7 +9,7 @@ version: 2 python: - version: "3.6" + version: "3.7" install: - requirements: docs/requirements.txt - requirements: requirements.txt From e516c78effe1d8bf9208b1b85c69b2f1e049b522 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 13 Jan 2022 16:27:30 -0500 Subject: [PATCH 12/81] First part of patch Signed-off-by: dherrada --- .../PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md | 2 +- .github/workflows/build.yml | 6 +++--- .github/workflows/release.yml | 8 ++++---- .readthedocs.yaml | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md index 71ef8f8..8de294e 100644 --- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -4,7 +4,7 @@ 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://circuitpython.readthedocs.io/en/latest/docs/design_guide.html +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 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ca35544..474520d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,10 +22,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.7 - uses: actions/setup-python@v1 + - name: Set up Python 3.x + uses: actions/setup-python@v2 with: - python-version: 3.7 + python-version: "3.x" - name: Versions run: | python3 --version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d0015a..a65e5de 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,10 +24,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 + - name: Set up Python 3.x + uses: actions/setup-python@v2 with: - python-version: 3.6 + python-version: "3.x" - name: Versions run: | python3 --version @@ -67,7 +67,7 @@ jobs: 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 + uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 1335112..f8b2891 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -9,7 +9,7 @@ version: 2 python: - version: "3.7" + version: "3.x" install: - requirements: docs/requirements.txt - requirements: requirements.txt From 3c44cd12999f9529293c36753f369f9e6eb1dce6 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 24 Jan 2022 16:46:17 -0500 Subject: [PATCH 13/81] Updated docs link, updated python docs link, updated setup.py --- README.rst | 4 ++-- docs/conf.py | 4 ++-- docs/index.rst | 2 +- setup.py | 2 -- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/README.rst b/README.rst index 50a8e76..5f1f8aa 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-circuitpython-rsa/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/rsa/en/latest/ + :target: https://docs.circuitpython.org/projects/rsa/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg @@ -60,7 +60,7 @@ Examples for this library are avaliable in the examples/ folder. Documentation ============= -API documentation for this library can be found on `Read the Docs `_. +API documentation for this library can be found on `Read the Docs `_. Contributing ============ diff --git a/docs/conf.py b/docs/conf.py index 0ae8873..68ec99d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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. diff --git a/docs/index.rst b/docs/index.rst index 2c1731a..7e3f7e9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -32,7 +32,7 @@ Table of Contents :caption: Other Links Download - CircuitPython Reference Documentation + CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat Adafruit Learning System diff --git a/setup.py b/setup.py index 13a0dca..c61bd6e 100644 --- a/setup.py +++ b/setup.py @@ -44,8 +44,6 @@ "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", From 7193248bfb51fc07d5a6358a9b48be8c51a8ded0 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Thu, 10 Feb 2022 10:16:22 -0500 Subject: [PATCH 14/81] Consolidate Documentation sections of README --- README.rst | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 5f1f8aa..3f99dbe 100644 --- a/README.rst +++ b/README.rst @@ -62,14 +62,11 @@ 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 `_. From c033c8b5a6ae5d794840c8e007b80d698bd8f567 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 14 Feb 2022 15:35:02 -0500 Subject: [PATCH 15/81] Fixed readthedocs build Signed-off-by: dherrada --- .readthedocs.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index f8b2891..33c2a61 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,8 +8,12 @@ # Required version: 2 +build: + os: ubuntu-20.04 + tools: + python: "3" + python: - version: "3.x" install: - requirements: docs/requirements.txt - requirements: requirements.txt From 56e5bad31e51ca93c631bdbf3ad567aaefbd91ea Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Mon, 28 Mar 2022 15:52:04 -0400 Subject: [PATCH 16/81] Update Black to latest. Signed-off-by: Kattni Rembor --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 43d1385..29230db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ repos: - repo: https://github.com/python/black - rev: 20.8b1 + rev: 22.3.0 hooks: - id: black - repo: https://github.com/fsfe/reuse-tool From e71b4380cbcf4f9fa6560f1a7f510472cb70aa30 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 5 Apr 2022 13:07:57 -0400 Subject: [PATCH 17/81] Add try/except guards for pyasn1 imports --- adafruit_rsa/asn1.py | 5 ++++- adafruit_rsa/key.py | 37 ++++++++++++++++++++++++++----------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index 7cc6f03..8b6579e 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -9,7 +9,10 @@ """ # pylint: disable=no-name-in-module, too-few-public-methods -from pyasn1.type import univ, namedtype, tag +try: + from pyasn1.type import univ, namedtype, tag +except ImportError as err: + raise ImportError("Usage of asn1.py requires pyasn1 library") from err __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index a1ec7c3..813f317 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -250,8 +250,11 @@ def _load_pkcs1_der(cls, keyfile): """ # pylint: disable=import-outside-toplevel - from adafruit_rsa.tools.pyasn1.codec.der import decoder - from adafruit_rsa.asn1 import AsnPubKey + try: + from adafruit_rsa.tools.pyasn1.codec.der import decoder + from adafruit_rsa.asn1 import AsnPubKey + 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"])) @@ -263,7 +266,10 @@ def _save_pkcs1_der(self): :rtype: bytes """ # pylint: disable=import-outside-toplevel - from pyasn1.codec.der import encoder + try: + from pyasn1.codec.der import encoder + except ImportError as err: + raise ImportError("This functionality requires the library") from err from rsa.asn1 import AsnPubKey # Create the ASN object @@ -328,9 +334,12 @@ def load_pkcs1_openssl_der(cls, keyfile): """ # pylint: disable=import-outside-toplevel - from adafruit_rsa.asn1 import OpenSSLPubKey - from pyasn1.codec.der import decoder - from pyasn1.type import univ + try: + from adafruit_rsa.asn1 import OpenSSLPubKey + from pyasn1.codec.der import decoder + from pyasn1.type import univ + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) @@ -477,9 +486,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 ( # pylint: disable=import-outside-toplevel + decoder, + ) + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err (priv, _) = decoder.decode(keyfile) @@ -521,8 +533,11 @@ def _save_pkcs1_der(self): :rtype: bytes """ # pylint: disable=import-outside-toplevel - from pyasn1.type import univ, namedtype - from pyasn1.codec.der import encoder + try: + from pyasn1.type import univ, namedtype + from pyasn1.codec.der import encoder + except ImportError as err: + raise ImportError("This functionality requires the pyasn1 library") from err class AsnPrivKey(univ.Sequence): """Creates PKCS#1 DER Formatted AsnPrivKey""" From fb08c8a941197e9653e309841fc1b3f120756231 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 5 Apr 2022 13:10:43 -0400 Subject: [PATCH 18/81] Add try/except guard for import of CPython rsa library --- adafruit_rsa/key.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 813f317..cd1b7ee 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -270,7 +270,13 @@ def _save_pkcs1_der(self): from pyasn1.codec.der import encoder except ImportError as err: raise ImportError("This functionality requires the library") from err - from rsa.asn1 import AsnPubKey + 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() From 1cb1abff58a00d0faa69a2324c332dc4294e758c Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 5 Apr 2022 13:14:43 -0400 Subject: [PATCH 19/81] Update dependencies block in README --- README.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.rst b/README.rst index 3f99dbe..db5390d 100644 --- a/README.rst +++ b/README.rst @@ -23,6 +23,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 From de3de7cd16bd9c0e3336f2b529d5871384b2efb7 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 11:48:02 -0400 Subject: [PATCH 20/81] Add type annotations to _compat.py --- adafruit_rsa/_compat.py | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 8312ab5..bcb31f5 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -8,6 +8,11 @@ import sys from struct import pack +try: + from typing import Any, Literal, Tuple +except ImportError: + pass + __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" @@ -31,40 +36,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. + ``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. + ``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,7 +77,7 @@ 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: + :param int num: An unsigned integer between 0 and 255 (both inclusive). :returns: A single byte. @@ -80,7 +85,7 @@ def byte(num): 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,7 +93,7 @@ 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: + :param bytes bytes_1: First bytes object. :param bytes_2: Second bytes object. @@ -98,18 +103,22 @@ def xor_bytes(bytes_1, bytes_2): 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: 4-tuple:: From 9277ffd6ae5078f47083d9ea7fe6ca58f08c5163 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 11:59:58 -0400 Subject: [PATCH 21/81] Add type annotations to common.py --- adafruit_rsa/common.py | 44 ++++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index 295e92c..fb00903 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -7,13 +7,22 @@ # pylint: disable=invalid-name +try: + from typing import Optional, Tuple, Sequence +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,7 +33,7 @@ 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): + 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) ) @@ -33,7 +42,7 @@ def __init__(self, a, b, d, msg=None): 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,7 +56,7 @@ 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. @@ -63,7 +72,7 @@ def bit_size(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,17 +87,15 @@ 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`. @@ -101,9 +108,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 +118,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 +142,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,13 +159,13 @@ 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 + :param Sequence[int] a_values: the a-values of the above equation + :param Sequence[int] modulo_values: the m-values of the above equation :returns: x such that x = a[i] (mod m[i]) for each i From e2799b6c3cbc66a03d466ead42a21f1c227f1d66 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 12:04:19 -0400 Subject: [PATCH 22/81] Add type annotations to core.py --- adafruit_rsa/core.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/adafruit_rsa/core.py b/adafruit_rsa/core.py index 0e5ca85..497bcb1 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -12,12 +12,18 @@ # pylint: disable=invalid-name from adafruit_rsa._compat import is_integer +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,7 +41,7 @@ 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 @@ -43,7 +49,7 @@ def assert_int(var, name): raise TypeError("%s should be an integer, not %s" % (name, 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 +67,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") From b77b97de8813b8fa5a8d2f27255efae36a8cabc4 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 12:42:07 -0400 Subject: [PATCH 23/81] Add tpe annotations for key.py --- adafruit_rsa/key.py | 211 +++++++++++++++++++++++--------------------- 1 file changed, 108 insertions(+), 103 deletions(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index a1ec7c3..72646ee 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -30,6 +30,11 @@ import adafruit_rsa.randnum import adafruit_rsa.core +try: + from typing import Any, Tuple, Dict, Callable +except ImportError: + pass + __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" @@ -45,42 +50,38 @@ class AbstractKey(object): __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. :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. @@ -88,15 +89,12 @@ def _save_pkcs1_der(self): """ @classmethod - def load_pkcs1(cls, keyfile, format="PEM"): + def load_pkcs1(cls, keyfile: bytes, format: str = "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 """ @@ -113,7 +111,9 @@ 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: @@ -124,11 +124,10 @@ def _assert_format_exists(file_format, methods): "Unsupported format: %r, try one of %s" % (file_format, formats) ) from err - def save_pkcs1(self, format="PEM"): + def save_pkcs1(self, format: str = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. - :param format: the format to save; 'PEM' or 'DER' - :type format: str + :param str format: the format to save; 'PEM' or 'DER' :returns: the DER- or PEM-encoded key. :rtype: bytes """ @@ -141,13 +140,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 +155,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))). @@ -200,21 +198,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 +221,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: @@ -256,7 +254,7 @@ def _load_pkcs1_der(cls, keyfile): (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. @@ -274,21 +272,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 +297,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 +306,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,14 +316,12 @@ 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 @@ -367,7 +363,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 +374,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 +386,17 @@ 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,19 +414,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): + 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 :rtype: int @@ -440,12 +437,10 @@ 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 - + :param int message: the message to encrypt :returns: the encrypted message :rtype: int """ @@ -456,12 +451,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: @@ -514,7 +508,7 @@ 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. @@ -554,22 +548,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 +573,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 @@ -625,7 +622,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 +655,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) @@ -693,12 +688,12 @@ def calculate_keys_custom_exponent(p, q, exponent): 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 +701,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,7 +737,11 @@ 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", ): """Generates public and private keys, and returns them as (pub, priv). @@ -743,17 +749,16 @@ def newkeys( :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 + :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`) From a50c91604ce621de57450d95c294187d141bde61 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 12:43:57 -0400 Subject: [PATCH 24/81] Add type annotations to machine_size.py --- adafruit_rsa/machine_size.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index 2dd2239..cfc60e0 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -7,6 +7,11 @@ import sys +try: + from typing import Literal, Tuple +except ImportError: + pass + __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" @@ -27,12 +32,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 From aec783bc961aa83e32d32d7a019b5cd4f21eeca6 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 12:56:02 -0400 Subject: [PATCH 25/81] Add type annotations to pem.py --- adafruit_rsa/pem.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index daaaa5e..0b4daef 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -9,11 +9,16 @@ # pylint: disable=redefined-builtin from adafruit_rsa._compat import is_bytes +try: + from typing import Union, Tuple +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 +32,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 +98,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. From 0994307fe48f8eaaf9415547fb414e8e90def5f3 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 13:36:09 -0400 Subject: [PATCH 26/81] Add type annotations to pkcs1.py --- adafruit_rsa/pkcs1.py | 93 ++++++++++++++++++++++++++++++------------- 1 file changed, 66 insertions(+), 27 deletions(-) diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index 8b7339e..c1aa5ec 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -20,6 +20,26 @@ import adafruit_hashlib as hashlib from adafruit_rsa import common, transform, core +try: + from typing import Optional, Iterator, Union + from adafruit_rsa.key import PublicKey, PrivateKey + + try: + from typing import Protocol + except ImportError: + from typing_extensions import Protocol + + 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" @@ -55,10 +75,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 +123,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 +159,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 +190,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 +255,17 @@ 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: str +) -> 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 +291,9 @@ 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 +302,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 +316,9 @@ 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,8 +326,9 @@ 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. @@ -320,14 +354,16 @@ 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. + :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. :returns: the name of the used hash. """ @@ -339,11 +375,13 @@ 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. + :param TextIOWrapper infile: file to read and separate in blocks. + :param int blocksize: block size in bytes. :returns: a generator that yields the contents of each block """ @@ -360,7 +398,9 @@ 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 +408,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,10 +427,10 @@ 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 """ From e76b5267ee9df17f29b62931879e37390a59c627 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 13:39:30 -0400 Subject: [PATCH 27/81] Add type annotations for prime.py --- adafruit_rsa/prime.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 003719b..790bef3 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -12,13 +12,18 @@ import adafruit_rsa.common import adafruit_rsa.randnum +try: + from typing 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 +35,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 +61,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 +69,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 """ @@ -109,7 +112,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 +123,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 +149,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 +177,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. From b72afb8d5ed8d9ffbb7ef4613e240f591d22a3ba Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 13:41:07 -0400 Subject: [PATCH 28/81] Add type annotations to randnum.py --- adafruit_rsa/randnum.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index 6fddb4b..3ec6d3a 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -16,7 +16,7 @@ __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 +37,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 +50,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 +63,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 From 12f6f80761e4b6c2347766038d3b04e7a9a90528 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 13:45:18 -0400 Subject: [PATCH 29/81] Add type annotations to transform.py --- adafruit_rsa/transform.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index a94828c..6cf0da7 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -16,11 +16,16 @@ from adafruit_rsa._compat import byte, is_integer from adafruit_rsa import common, machine_size +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 +40,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:: @@ -103,15 +108,15 @@ 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: The number of leading needle bytes. @@ -128,7 +133,12 @@ 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 @@ -136,7 +146,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): .. 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 From 55c306290f0edf564fc2bedef6b52e78e883174a Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Fri, 25 Mar 2022 15:24:32 -0400 Subject: [PATCH 30/81] Require Blinka >= 7.0.0 for Protocol --- requirements.txt | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index 17a850d..2b832d9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,4 +2,4 @@ # # SPDX-License-Identifier: Unlicense -Adafruit-Blinka +Adafruit-Blinka>=7.0.0 diff --git a/setup.py b/setup.py index c61bd6e..21d4265 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ # Author details author="Adafruit Industries", author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka"], + install_requires=["Adafruit-Blinka>=7.0.0"], # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers From 24016d85448876deb2357b3bfea7061e679f464d Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 30 Mar 2022 13:15:46 -0400 Subject: [PATCH 31/81] Update module docstrings --- adafruit_rsa/__init__.py | 6 ++++-- adafruit_rsa/_compat.py | 7 ++++++- adafruit_rsa/asn1.py | 6 +++++- adafruit_rsa/common.py | 7 ++++++- adafruit_rsa/core.py | 6 +++++- adafruit_rsa/key.py | 6 +++++- adafruit_rsa/machine_size.py | 7 ++++++- adafruit_rsa/pem.py | 8 +++++++- adafruit_rsa/pkcs1.py | 7 ++++++- adafruit_rsa/prime.py | 6 +++++- adafruit_rsa/randnum.py | 7 ++++++- adafruit_rsa/transform.py | 6 +++++- 12 files changed, 66 insertions(+), 13 deletions(-) diff --git a/adafruit_rsa/__init__.py b/adafruit_rsa/__init__.py index 8c66cbd..5a73010 100755 --- a/adafruit_rsa/__init__.py +++ b/adafruit_rsa/__init__.py @@ -3,12 +3,14 @@ # # 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. """ diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index bcb31f5..0647b84 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -3,7 +3,12 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Python compatibility wrappers.""" +""" +`adafruit_rsa._compat` +==================================================== + +Python compatibility wrappers. +""" import sys from struct import pack diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index 7cc6f03..bf0f1b7 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -3,7 +3,11 @@ # # 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. """ diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index fb00903..aa621e8 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -3,7 +3,12 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Common functionality shared by several modules.""" +""" +`adafruit_rsa.common` +==================================================== + +Common functionality shared by several modules. +""" # pylint: disable=invalid-name diff --git a/adafruit_rsa/core.py b/adafruit_rsa/core.py index 497bcb1..b933a8d 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -3,7 +3,11 @@ # # 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. diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 72646ee..e3e6f4d 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -3,7 +3,11 @@ # # 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. diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index cfc60e0..4e91f18 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -3,7 +3,12 @@ # # 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 diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index 0b4daef..0ee7952 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -3,7 +3,13 @@ # # 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 diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index c1aa5ec..0d4c310 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -3,7 +3,11 @@ # # 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,6 +20,7 @@ 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 diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 790bef3..62aabeb 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -3,7 +3,11 @@ # # 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. diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index 3ec6d3a..75c49bd 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -3,7 +3,12 @@ # # 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 diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index 6cf0da7..e7641b9 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -3,7 +3,11 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Data transformation functions. +""" +`adafruit_rsa.transform` +==================================================== + +Data transformation functions. From bytes to a number, number to bytes, etc. """ From 915bc8b46f2db81eb80266d65019452bed9d3bed Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 30 Mar 2022 13:16:17 -0400 Subject: [PATCH 32/81] Update method and class docstrings --- adafruit_rsa/_compat.py | 17 ++++++----------- adafruit_rsa/common.py | 4 ++-- adafruit_rsa/key.py | 2 +- adafruit_rsa/transform.py | 3 +++ 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 0647b84..662328c 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -82,10 +82,8 @@ def byte(num: int) -> bytes: Use it as a replacement for ``chr`` where you are expecting a byte because this will work on all current versions of Python:: - :param int 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). + :returns: A single byte. """ return pack("B", num) @@ -98,12 +96,9 @@ def xor_bytes(bytes_1: bytes, bytes_2: bytes) -> bytes: generate different results. If parameters have different length, extra length of the largest one is ignored. - :param bytes 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)) @@ -125,7 +120,7 @@ def get_word_alignment( Default 64 will be used when on a 64-bit machine. :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/common.py b/adafruit_rsa/common.py index aa621e8..c306c00 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -102,9 +102,9 @@ def byte_size(number: int) -> int: 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 diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index e3e6f4d..46cc2cf 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -756,7 +756,7 @@ def newkeys( :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. + ``n`` may have slightly less bits. :param int poolsize: the number of processes to use to generate the prime numbers. :param int exponent: the exponent for the key; only change this if you know diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index e7641b9..3024319 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -147,9 +147,12 @@ def int2bytes( 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 int number: Integer value :param fill_size: From 821f1b6eec7e827d5cbec54ce7b00696fbabb233 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 30 Mar 2022 13:16:53 -0400 Subject: [PATCH 33/81] Add missing modules from api.rst --- docs/api.rst | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/api.rst b/docs/api.rst index 5c3e39f..e78aade 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -7,3 +7,36 @@ Adafruit CircuitPython RSA API .. automodule:: adafruit_rsa :members: + +.. automodule:: adafruit_rsa._compat + :members: + +.. automodule:: adafruit_rsa.asn1 + :members: + +.. 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: From 0730cc3ff7844e680fd89beab65f69e2ad319a0b Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 30 Mar 2022 13:17:49 -0400 Subject: [PATCH 34/81] Change :returns: to :return: --- adafruit_rsa/_compat.py | 6 +++--- adafruit_rsa/common.py | 4 ++-- adafruit_rsa/key.py | 18 +++++++++--------- adafruit_rsa/machine_size.py | 2 +- adafruit_rsa/pkcs1.py | 6 +++--- adafruit_rsa/transform.py | 4 ++-- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 662328c..09eec3f 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -56,7 +56,7 @@ def is_bytes(obj: Any) -> bool: :param obj: The value to test. - :returns: + :return: ``True`` if ``obj`` is a byte string; ``False`` otherwise. """ return isinstance(obj, bytes) @@ -68,7 +68,7 @@ def is_integer(obj: Any) -> bool: :param obj: The value to test. - :returns: + :return: ``True`` if ``obj`` is an integer; ``False`` otherwise. """ return isinstance(obj, INTEGER_TYPES) @@ -83,7 +83,7 @@ def byte(num: int) -> bytes: because this will work on all current versions of Python:: :param int num: An unsigned integer between 0 and 255 (both inclusive). - :returns: A single byte. + :return: A single byte. """ return pack("B", num) diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index c306c00..cd4edec 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -65,7 +65,7 @@ def bit_size(num: int) -> int: 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. """ @@ -171,7 +171,7 @@ def crt(a_values: Sequence[int], modulo_values: Sequence[int]) -> int: :param Sequence[int] a_values: the a-values of the above equation :param Sequence[int] modulo_values: the m-values of the above equation - :returns: x such that x = a[i] (mod m[i]) for each i + :return: x such that x = a[i] (mod m[i]) for each i >>> crt([2, 3], [3, 5]) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 46cc2cf..fa4d960 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -81,14 +81,14 @@ def _load_pkcs1_der(cls, keyfile: bytes) -> "AbstractKey": 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) -> 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 """ @@ -132,7 +132,7 @@ def save_pkcs1(self, format: str = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. :param str format: the format to save; 'PEM' or 'DER' - :returns: the DER- or PEM-encoded key. + :return: the DER- or PEM-encoded key. :rtype: bytes """ @@ -261,7 +261,7 @@ def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey": 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 @@ -431,7 +431,7 @@ def blinded_decrypt(self, encrypted: int) -> int: :param int encrypted: the encrypted message - :returns: the decrypted message + :return: the decrypted message :rtype: int """ @@ -445,7 +445,7 @@ def blinded_encrypt(self, message: int) -> int: """Encrypts the message using blinding to prevent side-channel attacks. :param int message: the message to encrypt - :returns: the encrypted message + :return: the encrypted message :rtype: int """ @@ -515,7 +515,7 @@ def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey": 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 @@ -594,7 +594,7 @@ def find_p_q( *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 @@ -765,7 +765,7 @@ def newkeys( :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 4e91f18..e12dda6 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -54,7 +54,7 @@ def get_word_alignment( 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/pkcs1.py b/adafruit_rsa/pkcs1.py index 0d4c310..6c5bae2 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -335,7 +335,7 @@ def verify( :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. """ @@ -369,7 +369,7 @@ def find_signature_hash(signature: bytes, pub_key: PublicKey) -> str: :py:func:`adafruit_rsasign`. :param PublicKey pub_key: the :py:class:`adafruit_rsaPublicKey` of the person signing the message. - :returns: the name of the used hash. + :return: the name of the used hash. """ keylength = common.byte_size(pub_key.n) @@ -387,7 +387,7 @@ def yield_fixedblocks( :param TextIOWrapper infile: file to read and separate in blocks. :param int blocksize: block size in bytes. - :returns: a generator that yields the contents of each block + :return: a generator that yields the contents of each block """ while True: diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index 3024319..c56641d 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -122,7 +122,7 @@ def bytes_leading(raw_bytes: bytes, needle: bytes = b"\x00") -> int: Raw bytes. :param bytes needle: The byte to count. Default \x00. - :returns: + :return: The number of leading needle bytes. """ @@ -168,7 +168,7 @@ def int2bytes( 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 From d2a68244fcb2beffb464d7bf39aaff55690b612a Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 30 Mar 2022 13:21:40 -0400 Subject: [PATCH 35/81] Ran new version of black via pre-commit --- adafruit_rsa/pkcs1.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index 6c5bae2..efd2752 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -41,7 +41,6 @@ def read(self, blocksize: int) -> Union[bytes, str]: """A method that reads a given number of bytes or chracters""" ... - except ImportError: pass From 204256c58488596de798139477499b0682ee26c6 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Thu, 7 Apr 2022 14:19:58 -0400 Subject: [PATCH 36/81] Add pyasn1 to requirements.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 2b832d9..76279f0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ # SPDX-License-Identifier: Unlicense Adafruit-Blinka>=7.0.0 +pyasn1 From 73756b929f16b344020ddf913a38aba9192987c3 Mon Sep 17 00:00:00 2001 From: Kattni Date: Fri, 8 Apr 2022 13:08:36 -0400 Subject: [PATCH 37/81] Update badge URL to reflect project name. --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 3f99dbe..671f39d 100644 --- a/README.rst +++ b/README.rst @@ -1,7 +1,7 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-rsa/badge/?version=latest +.. image:: https://readthedocs.org/projects/rsa/badge/?version=latest :target: https://docs.circuitpython.org/projects/rsa/en/latest/ :alt: Documentation Status From d35d90e42cf411ec9f0390fbe26b1c7385066ce4 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 18 Apr 2022 19:00:58 -0400 Subject: [PATCH 38/81] Use Literal in load_pkcs1() --- adafruit_rsa/key.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index fa4d960..0f10b1e 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -35,7 +35,7 @@ import adafruit_rsa.core try: - from typing import Any, Tuple, Dict, Callable + from typing import Any, Tuple, Dict, Callable, Literal except ImportError: pass @@ -93,7 +93,9 @@ def _save_pkcs1_der(self) -> bytes: """ @classmethod - def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> "AbstractKey": + def load_pkcs1( + cls, keyfile: bytes, format: Literal["PEM", "DER"] = "PEM" + ) -> "AbstractKey": """Loads a key in PKCS#1 DER or PEM format. :param bytes keyfile: contents of a DER- or PEM-encoded file that From b8a9681f09ce028f24e4e5a1f85b378d9bc2de8a Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 18 Apr 2022 19:05:17 -0400 Subject: [PATCH 39/81] Use Literal in save_pkcs1() --- adafruit_rsa/key.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 0f10b1e..a8a256a 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -130,7 +130,7 @@ def _assert_format_exists( "Unsupported format: %r, try one of %s" % (file_format, formats) ) from err - def save_pkcs1(self, format: str = "PEM") -> bytes: + def save_pkcs1(self, format: Literal["PEM", "DER"] = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. :param str format: the format to save; 'PEM' or 'DER' From 21c85d33278dcbaa393150c22740691223c238b1 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 18 Apr 2022 19:05:45 -0400 Subject: [PATCH 40/81] Add return type for newkeys() --- adafruit_rsa/key.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index a8a256a..22cc4eb 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -748,7 +748,7 @@ def newkeys( 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 From d1cdbf2be4af05a7afbb6ac21c0ee64dff2cc9d5 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 18 Apr 2022 19:09:12 -0400 Subject: [PATCH 41/81] Change hash_method to Literal type in sign_hash() --- adafruit_rsa/pkcs1.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index efd2752..28041ee 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -26,7 +26,7 @@ from adafruit_rsa import common, transform, core try: - from typing import Optional, Iterator, Union + from typing import Optional, Iterator, Union, Literal from adafruit_rsa.key import PublicKey, PrivateKey try: @@ -260,7 +260,9 @@ def decrypt(crypto: bytes, priv_key: PrivateKey) -> bytes: def sign_hash( - hash_value: Optional[bytes], priv_key: PrivateKey, hash_method: str + 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. From 606926055946700e4fb158819f6d444191424d27 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Thu, 21 Apr 2022 15:00:27 -0400 Subject: [PATCH 42/81] Updated gitignore Signed-off-by: evaherrada --- .gitignore | 48 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 9647e71..544ec4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,47 @@ -# 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 + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea +.vscode +*~ From 6af9bcde2fc82b065ccb85dd801687d50d11e72c Mon Sep 17 00:00:00 2001 From: evaherrada Date: Fri, 22 Apr 2022 15:59:14 -0400 Subject: [PATCH 43/81] Patch: Replaced discord badge image --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 13ab05a..605ec13 100644 --- a/README.rst +++ b/README.rst @@ -5,7 +5,7 @@ Introduction :target: https://docs.circuitpython.org/projects/rsa/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bundle/blob/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord From ee476e8c440eeba196406bb64a33fdddcfea58af Mon Sep 17 00:00:00 2001 From: foamyguy Date: Sun, 24 Apr 2022 14:06:07 -0500 Subject: [PATCH 44/81] change discord badge --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 605ec13..a6d44d2 100644 --- a/README.rst +++ b/README.rst @@ -5,7 +5,7 @@ Introduction :target: https://docs.circuitpython.org/projects/rsa/en/latest/ :alt: Documentation Status -.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bundle/blob/main/badges/adafruit_discord.svg +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord From 7f9aec992b860ca794403a000f0f404f36b380c2 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 15 May 2022 12:50:26 -0400 Subject: [PATCH 45/81] Patch .pre-commit-config.yaml --- .pre-commit-config.yaml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 29230db..0a91a11 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,40 +3,40 @@ # SPDX-License-Identifier: Unlicense repos: -- repo: https://github.com/python/black + - repo: https://github.com/python/black rev: 22.3.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - id: black + - repo: https://github.com/fsfe/reuse-tool + rev: v0.14.0 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: reuse + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.2.0 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace -- repo: https://github.com/pycqa/pylint + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/pycqa/pylint rev: v2.11.1 hooks: - - id: pylint + - id: pylint name: pylint (library code) types: [python] args: - --disable=consider-using-f-string,duplicate-code exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint + - id: pylint name: pylint (example code) description: Run pylint rules on "examples/*.py" files types: [python] files: "^examples/" args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint + - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code + - id: pylint name: pylint (test code) description: Run pylint rules on "tests/*.py" files types: [python] files: "^tests/" args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - --disable=missing-docstring,consider-using-f-string,duplicate-code From 284ce967fba9e307804d89cfa2b6c10802767728 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Thu, 19 May 2022 19:19:15 -0500 Subject: [PATCH 46/81] typing Literal fallback --- adafruit_rsa/_compat.py | 8 +++++++- adafruit_rsa/key.py | 7 ++++++- adafruit_rsa/machine_size.py | 7 ++++++- adafruit_rsa/pkcs1.py | 7 ++++++- adafruit_rsa/prime.py | 5 ++++- 5 files changed, 29 insertions(+), 5 deletions(-) diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 09eec3f..b0e613a 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -14,10 +14,16 @@ from struct import pack try: - from typing import Any, Literal, Tuple + 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" diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 6770f59..8cb3bc1 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -35,7 +35,12 @@ import adafruit_rsa.core try: - from typing import Any, Tuple, Dict, Callable, Literal + from typing import Any, Tuple, Dict, Callable + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal except ImportError: pass diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index e12dda6..caad2cc 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -13,7 +13,12 @@ import sys try: - from typing import Literal, Tuple + from typing import Tuple + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal except ImportError: pass diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index 28041ee..db0bb21 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -26,7 +26,7 @@ from adafruit_rsa import common, transform, core try: - from typing import Optional, Iterator, Union, Literal + from typing import Optional, Iterator, Union from adafruit_rsa.key import PublicKey, PrivateKey try: @@ -34,6 +34,11 @@ 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""" diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 62aabeb..7ce171f 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -17,7 +17,10 @@ import adafruit_rsa.randnum try: - from typing import Literal + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal except ImportError: pass From 19245d6702ca43add3d281636c43a4bad6225df2 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 22 May 2022 00:18:55 -0400 Subject: [PATCH 47/81] Increase min lines similarity Signed-off-by: Alec Delaney --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index cfd1c41..f006a4a 100644 --- a/.pylintrc +++ b/.pylintrc @@ -252,7 +252,7 @@ ignore-docstrings=yes ignore-imports=yes # Minimum lines number of a similarity. -min-similarity-lines=4 +min-similarity-lines=12 [BASIC] From ec814c8c0d92aa8cef5aa2e5472aa9f54ce5e522 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 22 May 2022 00:18:23 -0400 Subject: [PATCH 48/81] Switch to inclusive terminology Signed-off-by: Alec Delaney --- .pylintrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pylintrc b/.pylintrc index f006a4a..f772971 100644 --- a/.pylintrc +++ b/.pylintrc @@ -9,11 +9,11 @@ # run arbitrary code extension-pkg-whitelist= -# Add files or directories to the blacklist. They should be base names, not +# Add files or directories to the ignore-list. They should be base names, not # paths. ignore=CVS -# Add files or directories matching the regex patterns to the blacklist. The +# Add files or directories matching the regex patterns to the ignore-list. The # regex matches against base names, not paths. ignore-patterns= From 15337fb03495240ae12df71faeb04c34e8f6058b Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 30 May 2022 14:25:04 -0400 Subject: [PATCH 49/81] Set language to "en" for documentation Signed-off-by: Alec Delaney --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 68ec99d..62d74a0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -60,7 +60,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. From dc2b76b0802d8978f769f990f2ae4a3a2d98536a Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 30 May 2022 21:54:59 -0400 Subject: [PATCH 50/81] Fix docstring for AsnPubKey --- adafruit_rsa/asn1.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index 58efd66..f926417 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -47,11 +47,15 @@ class OpenSSLPubKey(univ.Sequence): 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( From ba968c12cf8f090a7442a50410fbadf5064323f9 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 30 May 2022 21:55:20 -0400 Subject: [PATCH 51/81] Tidy up how asn1.py is auto-documented --- docs/api.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/api.rst b/docs/api.rst index e78aade..280d2f1 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -12,7 +12,10 @@ Adafruit CircuitPython RSA API :members: .. automodule:: adafruit_rsa.asn1 - :members: + + .. autoclass:: PubKeyHeader + .. autoclass:: OpenSSLPubKey + .. autoclass:: AsnPubKey .. automodule:: adafruit_rsa.common :members: From d1127d78f84995bbc31824b293dd3069fd2c6be6 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 6 Jun 2022 22:24:29 -0400 Subject: [PATCH 52/81] Add and pin dependencies --- requirements.txt | 1 + setup.py | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 76279f0..cc14ecf 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,5 @@ # SPDX-License-Identifier: Unlicense Adafruit-Blinka>=7.0.0 +adafruit-circuitpython-logging>=4.0.0 pyasn1 diff --git a/setup.py b/setup.py index 21d4265..4619ecd 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,11 @@ # Author details author="Adafruit Industries", author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka>=7.0.0"], + install_requires=[ + "Adafruit-Blinka>=7.0.0", + "adafruit-circuitpython-logging>=4.0.0", + "pyasn1", + ], # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers From abcd99e7193096ee1909f909a60b2d409a9cabb6 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 6 Jun 2022 22:26:02 -0400 Subject: [PATCH 53/81] Add StreamHandler to log --- adafruit_rsa/key.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 8cb3bc1..ce33269 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -49,6 +49,7 @@ # 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 From 118b28384d32808768b25ce22fb385af5a1c5823 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Tue, 7 Jun 2022 15:34:54 -0400 Subject: [PATCH 54/81] Added cp.org link to index.rst --- docs/index.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 7e3f7e9..18bda77 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,7 +31,8 @@ Table of Contents .. toctree:: :caption: Other Links - Download + Download from GitHub + Download Library Bundle CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat From 667c432417d89ba2ee2f305f7baed13c94e02a68 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Thu, 23 Jun 2022 23:07:41 -0400 Subject: [PATCH 55/81] Fix setup.py to use "packages" --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 4619ecd..36c6275 100644 --- a/setup.py +++ b/setup.py @@ -55,5 +55,5 @@ # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=["adafruit_rsa"], + packages=["adafruit_rsa"], ) From 451fdd5eb006abc1db6e5df6f3e9a7aadb77a3c5 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Fri, 22 Jul 2022 13:59:15 -0400 Subject: [PATCH 56/81] Changed .env to .venv in README.rst --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index a6d44d2..6ef7b6a 100644 --- a/README.rst +++ b/README.rst @@ -50,8 +50,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 From 9e66837e28ab8fc3b670f258995a6068ef482e26 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Tue, 2 Aug 2022 17:01:01 -0400 Subject: [PATCH 57/81] Added Black formatting badge --- README.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.rst b/README.rst index 6ef7b6a..7925cf9 100644 --- a/README.rst +++ b/README.rst @@ -13,6 +13,10 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_RSA/actions/ :alt: Build Status +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black + :alt: Code Style: Black + RSA implementation based on `Sybren A. Stüvel's python-rsa `_ pure-python RSA implementation. From 0f6038fcee0c37fbac5e4fecd1087a6ef55a9573 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 8 Aug 2022 22:05:55 -0400 Subject: [PATCH 58/81] Switched to pyproject.toml --- .github/workflows/build.yml | 18 ++++++----- .github/workflows/release.yml | 17 +++++----- optional_requirements.txt | 3 ++ pyproject.toml | 46 +++++++++++++++++++++++++++ requirements.txt | 4 +-- setup.py | 59 ----------------------------------- 6 files changed, 71 insertions(+), 76 deletions(-) create mode 100644 optional_requirements.txt create mode 100644 pyproject.toml delete mode 100644 setup.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 474520d..22f6582 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,6 +47,8 @@ jobs: pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - name: Library version run: git describe --dirty --always --tags + - name: Setup problem matchers + uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - name: Pre-commit hooks run: | pre-commit run --all-files @@ -60,16 +62,16 @@ jobs: - name: Build docs working-directory: docs run: sphinx-build -E -W -b html . _build/html - - name: Check For setup.py + - name: Check For pyproject.toml id: need-pypi run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) + echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal + pip install --upgrade build twine + for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do + sed -i -e "s/0.0.0-auto.0/1.2.3/" $file; + done; + python -m build twine check dist/* - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a65e5de..d1b4f8d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,25 +61,28 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - name: Check For setup.py + - name: Check For pyproject.toml id: need-pypi run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) + echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') run: | python -m pip install --upgrade pip - pip install setuptools wheel twine + pip install --upgrade build twine - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') env: TWINE_USERNAME: ${{ secrets.pypi_username }} TWINE_PASSWORD: ${{ secrets.pypi_password }} run: | - python setup.py sdist + for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do + sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; + done; + python -m build twine upload dist/* 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..e1999ff --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", +] + +[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 cc14ecf..5571b16 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # # SPDX-License-Identifier: Unlicense Adafruit-Blinka>=7.0.0 -adafruit-circuitpython-logging>=4.0.0 pyasn1 +adafruit-circuitpython-logging>=4.0.0 diff --git a/setup.py b/setup.py deleted file mode 100644 index 36c6275..0000000 --- a/setup.py +++ /dev/null @@ -1,59 +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>=7.0.0", - "adafruit-circuitpython-logging>=4.0.0", - "pyasn1", - ], - # 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", - ], - # 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=['...']` - packages=["adafruit_rsa"], -) From 19051a4ab4cad386bf11c88fe9ac8de74cf5790d Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 9 Aug 2022 12:03:54 -0400 Subject: [PATCH 59/81] Add setuptools-scm to build system requirements Signed-off-by: Alec Delaney --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index e1999ff..e3d8dc7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,6 +6,7 @@ requires = [ "setuptools", "wheel", + "setuptools-scm", ] [project] From 78176c7eb4ed96918b1b2302befc42fc1c3afd8b Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 16 Aug 2022 18:09:16 -0400 Subject: [PATCH 60/81] Update version string --- adafruit_rsa/__init__.py | 2 +- adafruit_rsa/_compat.py | 2 +- adafruit_rsa/asn1.py | 2 +- adafruit_rsa/common.py | 2 +- adafruit_rsa/core.py | 2 +- adafruit_rsa/key.py | 2 +- adafruit_rsa/machine_size.py | 2 +- adafruit_rsa/pem.py | 2 +- adafruit_rsa/pkcs1.py | 2 +- adafruit_rsa/prime.py | 2 +- adafruit_rsa/randnum.py | 2 +- adafruit_rsa/transform.py | 2 +- pyproject.toml | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/adafruit_rsa/__init__.py b/adafruit_rsa/__init__.py index 5a73010..ddd8bf7 100755 --- a/adafruit_rsa/__init__.py +++ b/adafruit_rsa/__init__.py @@ -31,5 +31,5 @@ __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 b0e613a..4652e38 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -24,7 +24,7 @@ pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" MAX_INT = sys.maxsize diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index f926417..5dd8e65 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -18,7 +18,7 @@ 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" diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index cd4edec..a46863e 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -17,7 +17,7 @@ except ImportError: pass -__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/core.py b/adafruit_rsa/core.py index b933a8d..4336b05 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -21,7 +21,7 @@ except ImportError: pass -__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/key.py b/adafruit_rsa/key.py index ce33269..82cca4e 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -44,7 +44,7 @@ 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 diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index caad2cc..cfbfc32 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -22,7 +22,7 @@ except ImportError: pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" MAX_INT = sys.maxsize diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index 0ee7952..f32c6cb 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -20,7 +20,7 @@ except ImportError: pass -__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/pkcs1.py b/adafruit_rsa/pkcs1.py index db0bb21..cede691 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -49,7 +49,7 @@ def read(self, blocksize: int) -> Union[bytes, str]: except ImportError: pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" # ASN.1 codes that describe the hash algorithm used. diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 7ce171f..26a9696 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -24,7 +24,7 @@ except ImportError: pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" __all__ = ["getprime", "are_relatively_prime"] diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index 75c49bd..4d5beb3 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -17,7 +17,7 @@ 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" diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index c56641d..5bede8f 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -25,7 +25,7 @@ except ImportError: pass -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" diff --git a/pyproject.toml b/pyproject.toml index e3d8dc7..4e9b32b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ requires = [ [project] name = "adafruit-circuitpython-rsa" description = "RSA implementation based on python-rsa" -version = "0.0.0-auto.0" +version = "0.0.0+auto.0" readme = "README.rst" authors = [ {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} From 593f8aff37641b8e2b57a9d46e9ba143bae35681 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 16 Aug 2022 21:09:16 -0400 Subject: [PATCH 61/81] Fix version strings in workflow files --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 22f6582..cb2f60e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -71,7 +71,7 @@ jobs: run: | pip install --upgrade build twine for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0-auto.0/1.2.3/" $file; + sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; done; python -m build twine check dist/* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1b4f8d..f3a0325 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,7 +82,7 @@ jobs: TWINE_PASSWORD: ${{ secrets.pypi_password }} run: | for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; + sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; done; python -m build twine upload dist/* From eea020e1c15baf6ed51dfa4c876c3122c436664c Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 22 Aug 2022 21:36:33 -0400 Subject: [PATCH 62/81] Keep copyright up to date in documentation --- docs/conf.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 62d74a0..a23a8b4 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -6,6 +6,7 @@ import os import sys +import datetime sys.path.insert(0, os.path.abspath("..")) @@ -43,7 +44,8 @@ # General information about the project. project = "Adafruit RSA Library" -copyright = "2019 Brent Rubell" +current_year = str(datetime.datetime.now().year) +copyright = current_year + " Brent Rubell" author = "Brent Rubell" # The version info for the project you're documenting, acts as replacement for From a180e904d7f61b2d7e4f06fe4649f1eeb9ad0acf Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 23 Aug 2022 17:26:23 -0400 Subject: [PATCH 63/81] Use year duration range for copyright attribution --- docs/conf.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index a23a8b4..b2e7884 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -44,8 +44,14 @@ # General information about the project. project = "Adafruit RSA Library" +creation_year = "2019" current_year = str(datetime.datetime.now().year) -copyright = current_year + " Brent Rubell" +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 From de118fe21b256510b5230b362471788318c492d9 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 00:02:50 -0400 Subject: [PATCH 64/81] Switching to composite actions --- .github/workflows/build.yml | 67 +---------------------- .github/workflows/release.yml | 88 ------------------------------ .github/workflows/release_gh.yml | 14 +++++ .github/workflows/release_pypi.yml | 14 +++++ 4 files changed, 30 insertions(+), 153 deletions(-) delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/release_gh.yml create mode 100644 .github/workflows/release_pypi.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cb2f60e..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,68 +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.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - 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 Sphinx, pre-commit - run: | - pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - - 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 pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - pip install --upgrade build twine - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; - done; - python -m build - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index f3a0325..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,88 +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.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - 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 pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - python -m pip install --upgrade pip - pip install --upgrade build twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; - done; - python -m build - twine upload dist/* diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..041a337 --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml new file mode 100644 index 0000000..041a337 --- /dev/null +++ b/.github/workflows/release_pypi.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main From aaf6815970fde5e775a3db67c466e91ce6af17a4 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 00:47:01 -0400 Subject: [PATCH 65/81] Updated pylint version to 2.13.0 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0a91a11..e6ddf7c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.11.1 + rev: v2.13.0 hooks: - id: pylint name: pylint (library code) From f0d5a4c597624f08bbe02d915bc703e7f2f3ef7a Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 08:15:21 -0400 Subject: [PATCH 66/81] Update pylint to 2.15.5 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e6ddf7c..6996f9c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.13.0 + rev: v2.15.5 hooks: - id: pylint name: pylint (library code) From e33403cbf801ff5cee2a1252cff25d7cb934ffca Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 09:12:46 -0400 Subject: [PATCH 67/81] Fix release CI files --- .github/workflows/release_gh.yml | 14 +++++++++----- .github/workflows/release_pypi.yml | 15 ++++++++++----- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml index 041a337..b8aa8d6 100644 --- a/.github/workflows/release_gh.yml +++ b/.github/workflows/release_gh.yml @@ -2,13 +2,17 @@ # # SPDX-License-Identifier: MIT -name: Build CI +name: GitHub Release Actions -on: [pull_request, push] +on: + release: + types: [published] jobs: - test: + upload-release-assets: runs-on: ubuntu-latest steps: - - name: Run Build CI workflow - uses: adafruit/workflows-circuitpython-libs/build@main + - name: Run GitHub Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-gh@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml index 041a337..65775b7 100644 --- a/.github/workflows/release_pypi.yml +++ b/.github/workflows/release_pypi.yml @@ -2,13 +2,18 @@ # # SPDX-License-Identifier: MIT -name: Build CI +name: PyPI Release Actions -on: [pull_request, push] +on: + release: + types: [published] jobs: - test: + upload-release-assets: runs-on: ubuntu-latest steps: - - name: Run Build CI workflow - uses: adafruit/workflows-circuitpython-libs/build@main + - 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 }} From d5474d30b664f214733eca226a65fee61a0b4335 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 18:34:33 -0400 Subject: [PATCH 68/81] Update .pylintrc for v2.15.5 --- .pylintrc | 45 ++++----------------------------------------- 1 file changed, 4 insertions(+), 41 deletions(-) diff --git a/.pylintrc b/.pylintrc index f772971..40208c3 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense @@ -26,7 +26,7 @@ jobs=1 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. -load-plugins= +load-plugins=pylint.extensions.no_self_use # Pickle collected data for later comparisons. persistent=yes @@ -54,8 +54,8 @@ confidence= # --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,unspecified-encoding +# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call +disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding # 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 @@ -225,12 +225,6 @@ 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 @@ -257,38 +251,22 @@ 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_]*)|(__.*__))$ @@ -296,9 +274,6 @@ const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # 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_]*))$ @@ -309,21 +284,12 @@ 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]+))$ @@ -339,9 +305,6 @@ no-docstring-rgx=^_ # 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_]*))$ From 0b641386f5d2b4fb1191210176534e2a7ab20c44 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Mon, 7 Nov 2022 21:21:14 -0500 Subject: [PATCH 69/81] Fix pylint errors --- adafruit_rsa/key.py | 2 -- adafruit_rsa/pkcs1.py | 1 - examples/rsa_tests.py | 5 ++--- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 82cca4e..3cc96aa 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -58,8 +58,6 @@ class AbstractKey(object): """Abstract superclass for private and public keys.""" - __slots__ = ("n", "e") - def __init__(self, n: int, e: int) -> None: self.n = n self.e = e diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index cede691..508bd25 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -44,7 +44,6 @@ class _FileLikeObject(Protocol): def read(self, blocksize: int) -> Union[bytes, str]: """A method that reads a given number of bytes or chracters""" - ... except ImportError: pass diff --git a/examples/rsa_tests.py b/examples/rsa_tests.py index 177b7e9..49345af 100755 --- a/examples/rsa_tests.py +++ b/examples/rsa_tests.py @@ -93,11 +93,10 @@ 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]() + test_name() print("OK!") print( "Ran {} tests in {} seconds".format(len(all_tests), time.monotonic() - start_time) From d060d1bed05323571335eec8463ee2e61a6b0b6f Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Thu, 1 Sep 2022 20:16:31 -0400 Subject: [PATCH 70/81] Add .venv to .gitignore Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com> --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 544ec4a..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ _build # Virtual environment-specific files .env +.venv # MacOS-specific files *.DS_Store From 1a6f1e2ec6020bebd67ba50dffecb6eccba8a73e Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Thu, 19 Jan 2023 23:39:55 -0500 Subject: [PATCH 71/81] Add upload url to release action Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com> --- .github/workflows/release_gh.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml index b8aa8d6..9acec60 100644 --- a/.github/workflows/release_gh.yml +++ b/.github/workflows/release_gh.yml @@ -16,3 +16,4 @@ jobs: uses: adafruit/workflows-circuitpython-libs/release-gh@main with: github-token: ${{ secrets.GITHUB_TOKEN }} + upload-url: ${{ github.event.release.upload_url }} From ea0fb7d90ad596d594361413c2ef203bc2103ed1 Mon Sep 17 00:00:00 2001 From: Tekktrik Date: Sun, 14 May 2023 13:00:32 -0400 Subject: [PATCH 72/81] Update .pylintrc, fix jQuery for docs Signed-off-by: Tekktrik --- .pylintrc | 2 +- docs/conf.py | 1 + docs/requirements.txt | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 40208c3..f945e92 100644 --- a/.pylintrc +++ b/.pylintrc @@ -396,4 +396,4 @@ min-public-methods=1 # Exceptions that will emit a warning when being caught. Defaults to # "Exception" -overgeneral-exceptions=Exception +overgeneral-exceptions=builtins.Exception diff --git a/docs/conf.py b/docs/conf.py index b2e7884..9b8a0d9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,6 +17,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", diff --git a/docs/requirements.txt b/docs/requirements.txt index 88e6733..797aa04 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -3,3 +3,4 @@ # SPDX-License-Identifier: Unlicense sphinx>=4.0.0 +sphinxcontrib-jquery From 7dbbb3061a4eee119a62a7869ef06ef8f31a6c34 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 18 Sep 2023 16:19:52 -0500 Subject: [PATCH 73/81] "fix rtd theme " --- docs/conf.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 9b8a0d9..05df6e3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -101,19 +101,10 @@ # 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" +html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] # 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, From ed7964384b01a086da0be6cacefd96c5958367c9 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 16 Oct 2023 14:30:31 -0500 Subject: [PATCH 74/81] unpin sphinx and add sphinx-rtd-theme to docs reqs Signed-off-by: foamyguy --- docs/requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index 797aa04..979f568 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,5 +2,6 @@ # # SPDX-License-Identifier: Unlicense -sphinx>=4.0.0 +sphinx sphinxcontrib-jquery +sphinx-rtd-theme From 13ef6e6887d77d2bea971b21d947d0ace8651fad Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 11 Mar 2024 17:07:54 -0500 Subject: [PATCH 75/81] add hashlib requirement --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 5571b16..6ac8bc8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ Adafruit-Blinka>=7.0.0 pyasn1 adafruit-circuitpython-logging>=4.0.0 +adafruit-circuitpython-hashlib From b3ca77723b79a9c1bff1caebbc23c3125e85203c Mon Sep 17 00:00:00 2001 From: foamyguy Date: Thu, 21 Mar 2024 20:50:16 -0500 Subject: [PATCH 76/81] json key file example --- examples/keys/example512key.json | 1 + examples/keys/example512key.json.license | 2 + examples/keys/example512key_pub.json | 1 + examples/keys/example512key_pub.json.license | 2 + examples/rsa_json_keys.py | 46 ++++++++++++++++++++ 5 files changed, 52 insertions(+) create mode 100644 examples/keys/example512key.json create mode 100644 examples/keys/example512key.json.license create mode 100644 examples/keys/example512key_pub.json create mode 100644 examples/keys/example512key_pub.json.license create mode 100644 examples/rsa_json_keys.py 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_json_keys.py b/examples/rsa_json_keys.py new file mode 100644 index 0000000..02e843d --- /dev/null +++ b/examples/rsa_json_keys.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks +# SPDX-License-Identifier: MIT +import binascii +import json +import adafruit_rsa +from adafruit_rsa import PublicKey, PrivateKey + +""" +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", "r") as f: + priv_key_obj = json.loads(f.read()) + + +with open("keys/example512key_pub.json", "r") 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")) From 1f75c328ac8e5d840a338d3b1c118dd50b283f0f Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 22 Mar 2024 10:21:06 -0500 Subject: [PATCH 77/81] generate json keys example --- examples/rsa_generate_json_keys.py | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 examples/rsa_generate_json_keys.py diff --git a/examples/rsa_generate_json_keys.py b/examples/rsa_generate_json_keys.py new file mode 100644 index 0000000..588fbe7 --- /dev/null +++ b/examples/rsa_generate_json_keys.py @@ -0,0 +1,36 @@ +# 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("-------------------------------") From d84a535d9a195de984de2c7647cb21d3a649add8 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 7 Oct 2024 09:24:05 -0500 Subject: [PATCH 78/81] remove deprecated get_html_theme_path() call Signed-off-by: foamyguy --- docs/conf.py | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 05df6e3..547070d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -104,7 +104,6 @@ import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" -html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] # 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, From 49ee9b1762bc46b233bb76a541a30cdd8fdabe6d Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 14 Jan 2025 11:32:34 -0600 Subject: [PATCH 79/81] add sphinx configuration to rtd.yaml Signed-off-by: foamyguy --- .readthedocs.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 33c2a61..88bca9f 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,6 +8,9 @@ # Required version: 2 +sphinx: + configuration: docs/conf.py + build: os: ubuntu-20.04 tools: From 9aa4c6e12018d56e83a5fbdc7816b3f79edb2aa2 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Thu, 27 Feb 2025 15:43:18 -0800 Subject: [PATCH 80/81] Remove secrets usage --- util/decode_priv_key.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/util/decode_priv_key.py b/util/decode_priv_key.py index c673c42..12f2f99 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. @@ -36,5 +36,5 @@ 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:]}"') From d4360fd523073fd435d274d3ce7e99ff3e9eddc5 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 16 May 2025 19:04:52 +0000 Subject: [PATCH 81/81] change to ruff --- .gitattributes | 11 + .pre-commit-config.yaml | 43 +--- .pylintrc | 399 ----------------------------- README.rst | 6 +- adafruit_rsa/__init__.py | 13 +- adafruit_rsa/_compat.py | 1 - adafruit_rsa/asn1.py | 8 +- adafruit_rsa/common.py | 15 +- adafruit_rsa/core.py | 4 +- adafruit_rsa/key.py | 50 ++-- adafruit_rsa/machine_size.py | 1 - adafruit_rsa/pem.py | 4 +- adafruit_rsa/pkcs1.py | 28 +- adafruit_rsa/prime.py | 5 +- adafruit_rsa/randnum.py | 1 - adafruit_rsa/transform.py | 13 +- docs/api.rst | 5 +- docs/conf.py | 8 +- examples/rsa_generate_json_keys.py | 3 +- examples/rsa_json_keys.py | 7 +- examples/rsa_sign_verify.py | 4 +- examples/rsa_tests.py | 18 +- ruff.toml | 111 ++++++++ util/decode_priv_key.py | 4 +- 24 files changed, 207 insertions(+), 555 deletions(-) create mode 100644 .gitattributes delete mode 100644 .pylintrc create mode 100644 ruff.toml 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/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6996f9c..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +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: 22.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v0.14.0 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string,duplicate-code - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written 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 ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. 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=pylint.extensions.no_self_use - -# 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,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# 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 - -# 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] - -# Regular expression matching correct argument names -argument-rgx=(([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 - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-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 - -# 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 - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-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 - -# 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=builtins.Exception diff --git a/README.rst b/README.rst index 7925cf9..f0604ed 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_RSA/actions/ :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. 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. diff --git a/adafruit_rsa/__init__.py b/adafruit_rsa/__init__.py index ddd8bf7..ff46b68 100755 --- a/adafruit_rsa/__init__.py +++ b/adafruit_rsa/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -15,17 +14,17 @@ """ -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" diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index 4652e38..fb8770a 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index 5dd8e65..02e9d33 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -12,9 +11,8 @@ 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 try: - from pyasn1.type import univ, namedtype, tag + from pyasn1.type import namedtype, tag, univ except ImportError as err: raise ImportError("Usage of asn1.py requires pyasn1 library") from err @@ -39,9 +37,7 @@ 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)), ), ) diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index a46863e..4255a94 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -10,10 +9,8 @@ Common functionality shared by several modules. """ -# pylint: disable=invalid-name - try: - from typing import Optional, Tuple, Sequence + from typing import Optional, Sequence, Tuple except ImportError: pass @@ -39,9 +36,7 @@ class NotRelativePrimeError(ValueError): """Raises if provided a and b not relatively prime.""" 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) - ) + 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 @@ -72,9 +67,7 @@ def bit_size(num: int) -> int: 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: int) -> int: @@ -190,7 +183,7 @@ def crt(a_values: Sequence[int], modulo_values: Sequence[int]) -> int: 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 4336b05..23b0e99 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -13,7 +12,6 @@ mathematically on integers. """ -# pylint: disable=invalid-name from adafruit_rsa._compat import is_integer try: @@ -50,7 +48,7 @@ def assert_int(var: Any, name: str) -> None: 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: int, ekey: int, n: int) -> int: diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index 3cc96aa..f059003 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -28,14 +27,14 @@ 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, Tuple, Dict, Callable + from typing import Any, Callable, Dict, Tuple try: from typing import Literal @@ -47,7 +46,6 @@ __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) @@ -55,7 +53,7 @@ DEFAULT_EXPONENT = 65537 -class AbstractKey(object): +class AbstractKey: """Abstract superclass for private and public keys.""" def __init__(self, n: int, e: int) -> None: @@ -97,9 +95,7 @@ def _save_pkcs1_der(self) -> bytes: """ @classmethod - def load_pkcs1( - cls, keyfile: bytes, format: Literal["PEM", "DER"] = "PEM" - ) -> "AbstractKey": + def load_pkcs1(cls, keyfile: bytes, format: Literal["PEM", "DER"] = "PEM") -> "AbstractKey": """Loads a key in PKCS#1 DER or PEM format. :param bytes keyfile: contents of a DER- or PEM-encoded file that @@ -108,9 +104,7 @@ def load_pkcs1( :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, @@ -130,9 +124,7 @@ def _assert_format_exists( 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: Literal["PEM", "DER"] = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. @@ -181,7 +173,6 @@ def unblind(self, blinded: int, r: int) -> int: return (adafruit_rsa.common.inverse(r, self.n) * blinded) % self.n -# pylint: disable=abstract-method class PublicKey(AbstractKey): """Represents a public RSA key. @@ -257,10 +248,9 @@ def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey": PublicKey(2367317549, 65537) """ - # pylint: disable=import-outside-toplevel try: - from adafruit_rsa.tools.pyasn1.codec.der import decoder 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 @@ -273,7 +263,6 @@ def _save_pkcs1_der(self) -> bytes: :return: the DER-encoded public key. :rtype: bytes """ - # pylint: disable=import-outside-toplevel try: from pyasn1.codec.der import encoder except ImportError as err: @@ -345,11 +334,11 @@ def load_pkcs1_openssl_der(cls, keyfile: bytes) -> "PublicKey": public key, from OpenSSL. :return: a PublicKey object """ - # pylint: disable=import-outside-toplevel try: - from adafruit_rsa.asn1 import OpenSSLPubKey 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 @@ -387,7 +376,6 @@ class PrivateKey(AbstractKey): __slots__ = ("n", "e", "d", "p", "q", "exp1", "exp2", "coef") - # pylint: disable=too-many-arguments def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None: AbstractKey.__init__(self, n, e) self.d = d @@ -415,9 +403,7 @@ 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: Tuple[int, int, int, int, int, int, int, int] - ) -> None: + 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 @@ -443,9 +429,7 @@ def __ne__(self, other: Any) -> bool: return not self == other def __hash__(self) -> int: - return hash( - (self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef) - ) + return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) def blinded_decrypt(self, encrypted: int) -> int: """Decrypts the message using blinding to prevent side-channel attacks. @@ -497,7 +481,7 @@ def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey": """ try: - from adafruit_rsa.tools.pyasn1.codec.der import ( # pylint: disable=import-outside-toplevel + from adafruit_rsa.tools.pyasn1.codec.der import ( decoder, ) except ImportError as err: @@ -542,10 +526,9 @@ def _save_pkcs1_der(self) -> bytes: :return: the DER-encoded private key. :rtype: bytes """ - # pylint: disable=import-outside-toplevel try: - from pyasn1.type import univ, namedtype 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 @@ -712,8 +695,7 @@ def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> Tuple[int, 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 diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index cfbfc32..ac9317c 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index f32c6cb..99d9cf7 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -12,11 +11,10 @@ from adafruit_binascii import a2b_base64, b2a_base64 -# pylint: disable=redefined-builtin from adafruit_rsa._compat import is_bytes try: - from typing import Union, Tuple + from typing import Tuple, Union except ImportError: pass diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index 508bd25..28db849 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -22,12 +21,15 @@ """ import os + import adafruit_hashlib as hashlib -from adafruit_rsa import common, transform, core + +from adafruit_rsa import common, core, transform try: - from typing import Optional, Iterator, Union - from adafruit_rsa.key import PublicKey, PrivateKey + from typing import Iterator, Optional, Union + + from adafruit_rsa.key import PrivateKey, PublicKey try: from typing import Protocol @@ -301,9 +303,7 @@ def sign_hash( return block -def sign( - message: Union[bytes, _FileLikeObject], priv_key: PrivateKey, hash_method: str -) -> bytes: +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 @@ -326,9 +326,7 @@ def sign( return sign_hash(msg_hash, priv_key, hash_method) -def verify( - message: Union[bytes, _FileLikeObject], signature: bytes, pub_key: PublicKey -) -> str: +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. @@ -385,9 +383,7 @@ def find_signature_hash(signature: bytes, pub_key: PublicKey) -> str: return _find_method_hash(clearsig) -def yield_fixedblocks( - infile: _FileLikeObject, blocksize: int -) -> Iterator[Union[bytes, str]]: +def yield_fixedblocks(infile: _FileLikeObject, blocksize: int) -> Iterator[Union[bytes, str]]: """Generator, yields each block of ``blocksize`` bytes in the input file. :param TextIOWrapper infile: file to read and separate in blocks. @@ -408,9 +404,7 @@ def yield_fixedblocks( break -def compute_hash( - message: Union[bytes, str, _FileLikeObject], method_name: str -) -> bytes: +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 @@ -445,7 +439,7 @@ def _find_method_hash(clearsig: bytes) -> str: :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 26a9696..bf8aacf 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -12,7 +11,7 @@ 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 @@ -102,7 +101,7 @@ def miller_rabin_primality_testing(n: int, k: int) -> bool: 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): diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index 4d5beb3..3614c98 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index 5bede8f..c655607 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # SPDX-FileCopyrightText: 2011 Sybren A. Stüvel # # SPDX-License-Identifier: Apache-2.0 @@ -15,10 +14,11 @@ # 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 try: from typing import Optional @@ -75,9 +75,7 @@ def _int2bytes(number: int, block_size: Optional[int] = None) -> bytes: # 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) @@ -94,8 +92,7 @@ def _int2bytes(number: int, block_size: Optional[int] = None) -> bytes: 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. @@ -213,5 +210,5 @@ def int2bytes( 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 280d2f1..b6f0821 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,10 +1,11 @@ -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: diff --git a/docs/conf.py b/docs/conf.py index 547070d..bf106cc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) @@ -48,9 +46,7 @@ creation_year = "2019" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Brent Rubell" author = "Brent Rubell" diff --git a/examples/rsa_generate_json_keys.py b/examples/rsa_generate_json_keys.py index 588fbe7..0f2c898 100644 --- a/examples/rsa_generate_json_keys.py +++ b/examples/rsa_generate_json_keys.py @@ -5,9 +5,10 @@ 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 +import adafruit_rsa # Create a keypair print("Generating keypair...") diff --git a/examples/rsa_json_keys.py b/examples/rsa_json_keys.py index 02e843d..6c2adf8 100644 --- a/examples/rsa_json_keys.py +++ b/examples/rsa_json_keys.py @@ -2,8 +2,9 @@ # SPDX-License-Identifier: MIT import binascii import json + import adafruit_rsa -from adafruit_rsa import PublicKey, PrivateKey +from adafruit_rsa import PrivateKey, PublicKey """ CircuitPython microcontrollers cannot load PEM key files generated by OpenSSL @@ -13,11 +14,11 @@ # load a keypair from JSON files -with open("keys/example512key.json", "r") as f: +with open("keys/example512key.json") as f: priv_key_obj = json.loads(f.read()) -with open("keys/example512key_pub.json", "r") as f: +with open("keys/example512key_pub.json") as f: pub_key_obj = json.loads(f.read()) 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 49345af..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,7 +21,7 @@ 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: @@ -30,12 +31,11 @@ def test_mod_msg(): 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." @@ -95,9 +95,7 @@ def test_sign_verify_fail(): start_time = time.monotonic() for test_name in all_tests: # for i in range(0, len(all_tests)): - print("Testing: {}".format(test_name)) + 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/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/util/decode_priv_key.py b/util/decode_priv_key.py index 12f2f99..423d186 100644 --- a/util/decode_priv_key.py +++ b/util/decode_priv_key.py @@ -17,7 +17,9 @@ * Author(s): Google Inc., Brent Rubell """ + import subprocess + import rsa # Generate private and public RSA keys @@ -32,7 +34,7 @@ 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)