├── adafruit_atecc ├── __init__.py ├── adafruit_atecc_cert_util.py ├── adafruit_atecc_asn1.py └── adafruit_atecc.py ├── docs ├── _static │ ├── favicon.ico │ ├── favicon.ico.license │ └── custom.css ├── api.rst.license ├── examples.rst.license ├── index.rst.license ├── requirements.txt ├── examples.rst ├── api.rst ├── index.rst └── conf.py ├── README.rst.license ├── optional_requirements.txt ├── requirements.txt ├── .gitattributes ├── .github ├── workflows │ ├── build.yml │ ├── release_pypi.yml │ ├── release_gh.yml │ └── failure-help-text.yml └── PULL_REQUEST_TEMPLATE │ └── adafruit_circuitpython_pr.md ├── .readthedocs.yaml ├── .pre-commit-config.yaml ├── LICENSES ├── MIT.txt ├── Unlicense.txt └── CC-BY-4.0.txt ├── examples ├── atecc_simpletest.py └── atecc_csr.py ├── pyproject.toml ├── .gitignore ├── LICENSE ├── README.rst ├── ruff.toml └── CODE_OF_CONDUCT.md /adafruit_atecc/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_ATECC/HEAD/docs/_static/favicon.ico -------------------------------------------------------------------------------- /docs/api.rst.license: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /docs/examples.rst.license: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /docs/index.rst.license: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /README.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /optional_requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | -------------------------------------------------------------------------------- /docs/_static/favicon.ico.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries 2 | 3 | SPDX-License-Identifier: CC-BY-4.0 4 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | sphinx 6 | sphinxcontrib-jquery 7 | sphinx-rtd-theme 8 | -------------------------------------------------------------------------------- /docs/examples.rst: -------------------------------------------------------------------------------- 1 | Simple test 2 | ------------ 3 | 4 | Ensure your device works with this simple test. 5 | 6 | .. literalinclude:: ../examples/atecc_simpletest.py 7 | :caption: examples/atecc_simpletest.py 8 | :linenos: 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | Adafruit-Blinka 6 | adafruit-circuitpython-binascii 7 | adafruit-circuitpython-busdevice 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | .py text eol=lf 6 | .rst text eol=lf 7 | .txt text eol=lf 8 | .yaml text eol=lf 9 | .toml text eol=lf 10 | .license text eol=lf 11 | .md text eol=lf 12 | -------------------------------------------------------------------------------- /docs/_static/custom.css: -------------------------------------------------------------------------------- 1 | /* SPDX-FileCopyrightText: 2025 Sam Blenny 2 | * SPDX-License-Identifier: MIT 3 | */ 4 | 5 | /* Monkey patch the rtd theme to prevent horizontal stacking of short items 6 | * see https://github.com/readthedocs/sphinx_rtd_theme/issues/1301 7 | */ 8 | .py.property{display: block !important;} 9 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Build CI 6 | 7 | on: [pull_request, push] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Run Build CI workflow 14 | uses: adafruit/workflows-circuitpython-libs/build@main 15 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | # Read the Docs configuration file 6 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 7 | 8 | # Required 9 | version: 2 10 | 11 | sphinx: 12 | configuration: docs/conf.py 13 | 14 | build: 15 | os: ubuntu-lts-latest 16 | tools: 17 | python: "3" 18 | 19 | python: 20 | install: 21 | - requirements: docs/requirements.txt 22 | - requirements: requirements.txt 23 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ############# 3 | .. If you created a package, create one automodule per module in the package. 4 | 5 | .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) 6 | .. use this format as the module name: "adafruit_foo.foo" 7 | 8 | .. automodule:: adafruit_atecc 9 | :members: 10 | 11 | .. automodule:: adafruit_atecc.adafruit_atecc 12 | :members: 13 | 14 | .. automodule:: adafruit_atecc.adafruit_atecc_asn1 15 | :members: 16 | 17 | .. automodule:: adafruit_atecc.adafruit_atecc_cert_util 18 | :members: 19 | -------------------------------------------------------------------------------- /.github/workflows/release_pypi.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: PyPI Release Actions 6 | 7 | on: 8 | release: 9 | types: [published] 10 | 11 | jobs: 12 | upload-release-assets: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Run PyPI Release CI workflow 16 | uses: adafruit/workflows-circuitpython-libs/release-pypi@main 17 | with: 18 | pypi-username: ${{ secrets.pypi_username }} 19 | pypi-password: ${{ secrets.pypi_password }} 20 | -------------------------------------------------------------------------------- /.github/workflows/release_gh.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: GitHub Release Actions 6 | 7 | on: 8 | release: 9 | types: [published] 10 | 11 | jobs: 12 | upload-release-assets: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Run GitHub Release CI workflow 16 | uses: adafruit/workflows-circuitpython-libs/release-gh@main 17 | with: 18 | github-token: ${{ secrets.GITHUB_TOKEN }} 19 | upload-url: ${{ github.event.release.upload_url }} 20 | -------------------------------------------------------------------------------- /.github/workflows/failure-help-text.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Failure help text 6 | 7 | on: 8 | workflow_run: 9 | workflows: ["Build CI"] 10 | types: 11 | - completed 12 | 13 | jobs: 14 | post-help: 15 | runs-on: ubuntu-latest 16 | if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} 17 | steps: 18 | - name: Post comment to help 19 | uses: adafruit/circuitpython-action-library-ci-failed@v1 20 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | repos: 6 | - repo: https://github.com/pre-commit/pre-commit-hooks 7 | rev: v4.5.0 8 | hooks: 9 | - id: check-yaml 10 | - id: end-of-file-fixer 11 | - id: trailing-whitespace 12 | - repo: https://github.com/astral-sh/ruff-pre-commit 13 | rev: v0.3.4 14 | hooks: 15 | - id: ruff-format 16 | - id: ruff 17 | args: ["--fix"] 18 | - repo: https://github.com/fsfe/reuse-tool 19 | rev: v3.0.1 20 | hooks: 21 | - id: reuse 22 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | Thank you for contributing! Before you submit a pull request, please read the following. 6 | 7 | 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 8 | 9 | If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs 10 | 11 | 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 12 | 13 | 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. 14 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice (including the next 11 | paragraph) shall be included in all copies or substantial portions of the 12 | Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 18 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF 19 | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | 3 | Table of Contents 4 | ================= 5 | 6 | .. toctree:: 7 | :maxdepth: 4 8 | :hidden: 9 | 10 | self 11 | 12 | .. toctree:: 13 | :caption: Examples 14 | 15 | examples 16 | 17 | .. toctree:: 18 | :caption: API Reference 19 | :maxdepth: 3 20 | 21 | api 22 | 23 | .. toctree:: 24 | :caption: Tutorials 25 | 26 | 27 | .. toctree:: 28 | :caption: Related Products 29 | 30 | 31 | .. toctree:: 32 | :caption: Other Links 33 | 34 | Download from GitHub 35 | Download Library Bundle 36 | CircuitPython Reference Documentation 37 | CircuitPython Support Forum 38 | Discord Chat 39 | Adafruit Learning System 40 | Adafruit Blog 41 | Adafruit Store 42 | 43 | Indices and tables 44 | ================== 45 | 46 | * :ref:`genindex` 47 | * :ref:`modindex` 48 | * :ref:`search` 49 | -------------------------------------------------------------------------------- /examples/atecc_simpletest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # SPDX-License-Identifier: MIT 3 | 4 | import board 5 | import busio 6 | 7 | from adafruit_atecc.adafruit_atecc import ATECC 8 | 9 | # Use 100kHz frequency for wake condition 10 | WAKE_CLK_FREQ = 100000 11 | 12 | # Initialize the i2c bus 13 | i2c = busio.I2C(board.SCL, board.SDA, frequency=WAKE_CLK_FREQ) 14 | 15 | # Initialize a new atecc object 16 | atecc = ATECC(i2c) 17 | 18 | print("ATECC Serial: ", atecc.serial_number) 19 | 20 | # Generate a random number with a maximum value of 1024 21 | print("Random Value: ", atecc.random(rnd_max=1024)) 22 | 23 | # Print out the value from one of the ATECC's counters 24 | # You should see this counter increase on every time the code.py runs. 25 | print("ATECC Counter #1 Value: ", atecc.counter(1, increment_counter=True)) 26 | 27 | # Initialize the SHA256 calculation engine 28 | atecc.sha_start() 29 | 30 | # Append bytes to the SHA digest 31 | print("Appending to the digest...") 32 | atecc.sha_update(b"Nobody inspects") 33 | print("Appending to the digest...") 34 | atecc.sha_update(b" the spammish repetition") 35 | 36 | # Return the digest of the data passed to sha_update 37 | message = atecc.sha_digest() 38 | print("SHA Digest: ", message) 39 | -------------------------------------------------------------------------------- /LICENSES/Unlicense.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute 4 | this software, either in source code form or as a compiled binary, for any 5 | purpose, commercial or non-commercial, and by any means. 6 | 7 | In jurisdictions that recognize copyright laws, the author or authors of this 8 | software dedicate any and all copyright interest in the software to the public 9 | domain. We make this dedication for the benefit of the public at large and 10 | to the detriment of our heirs and successors. We intend this dedication to 11 | be an overt act of relinquishment in perpetuity of all present and future 12 | rights to this software under copyright law. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 18 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 19 | THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, 20 | please refer to 21 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | [build-system] 6 | requires = [ 7 | "setuptools", 8 | "wheel", 9 | "setuptools-scm", 10 | ] 11 | 12 | [project] 13 | name = "adafruit-circuitpython-atecc" 14 | description = "Driver for Microchip's ATECCx08 cryptographic co-processors with secure hardware-based key storage" 15 | version = "0.0.0+auto.0" 16 | readme = "README.rst" 17 | authors = [ 18 | {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} 19 | ] 20 | urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_ATECC"} 21 | keywords = [ 22 | "adafruit", 23 | "blinka", 24 | "circuitpython", 25 | "micropython", 26 | "atecc", 27 | "atecc,", 28 | "microchip,", 29 | "secure,", 30 | "element,", 31 | "key,", 32 | "co-processor", 33 | ] 34 | license = {text = "MIT"} 35 | classifiers = [ 36 | "Intended Audience :: Developers", 37 | "Topic :: Software Development :: Libraries", 38 | "Topic :: Software Development :: Embedded Systems", 39 | "Topic :: System :: Hardware", 40 | "License :: OSI Approved :: MIT License", 41 | "Programming Language :: Python :: 3", 42 | ] 43 | dynamic = ["dependencies", "optional-dependencies"] 44 | 45 | [tool.setuptools] 46 | packages = ["adafruit_atecc"] 47 | 48 | [tool.setuptools.dynamic] 49 | dependencies = {file = ["requirements.txt"]} 50 | optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | # Do not include files and directories created by your personal work environment, such as the IDE 6 | # you use, except for those already listed here. Pull requests including changes to this file will 7 | # not be accepted. 8 | 9 | # This .gitignore file contains rules for files generated by working with CircuitPython libraries, 10 | # including building Sphinx, testing with pip, and creating a virual environment, as well as the 11 | # MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. 12 | 13 | # If you find that there are files being generated on your machine that should not be included in 14 | # your git commit, you should create a .gitignore_global file on your computer to include the 15 | # files created by your personal setup. To do so, follow the two steps below. 16 | 17 | # First, create a file called .gitignore_global somewhere convenient for you, and add rules for 18 | # the files you want to exclude from git commits. 19 | 20 | # Second, configure Git to use the exclude file for all Git repositories by running the 21 | # following via commandline, replacing "path/to/your/" with the actual path to your newly created 22 | # .gitignore_global file: 23 | # git config --global core.excludesfile path/to/your/.gitignore_global 24 | 25 | # CircuitPython-specific files 26 | *.mpy 27 | 28 | # Python-specific files 29 | __pycache__ 30 | *.pyc 31 | 32 | # Sphinx build-specific files 33 | _build 34 | 35 | # This file results from running `pip -e install .` in a local repository 36 | *.egg-info 37 | 38 | # Virtual environment-specific files 39 | .env 40 | .venv 41 | 42 | # MacOS-specific files 43 | *.DS_Store 44 | 45 | # IDE-specific files 46 | .idea 47 | .vscode 48 | *~ 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Arduino SA. All rights reserved. 2 | 3 | This library is free software; you can redistribute it and/or 4 | modify it under the terms of the GNU Lesser General Public 5 | License as published by the Free Software Foundation; either 6 | version 2.1 of the License, or (at your option) any later version. 7 | 8 | This library is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | Lesser General Public License for more details. 12 | 13 | You should have received a copy of the GNU Lesser General Public 14 | License along with this library; if not, write to the Free Software 15 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 16 | 17 | The MIT License (MIT) 18 | 19 | Copyright (c) 2019 Brent Rubell for Adafruit Industries 20 | 21 | Permission is hereby granted, free of charge, to any person obtaining a copy 22 | of this software and associated documentation files (the "Software"), to deal 23 | in the Software without restriction, including without limitation the rights 24 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 25 | copies of the Software, and to permit persons to whom the Software is 26 | furnished to do so, subject to the following conditions: 27 | 28 | The above copyright notice and this permission notice shall be included in all 29 | copies or substantial portions of the Software. 30 | 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 32 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 33 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 34 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 35 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 36 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 37 | SOFTWARE. 38 | -------------------------------------------------------------------------------- /examples/atecc_csr.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # SPDX-License-Identifier: MIT 3 | 4 | import board 5 | import busio 6 | 7 | import adafruit_atecc.adafruit_atecc_cert_util as cert_utils 8 | from adafruit_atecc.adafruit_atecc import ATECC, CFG_TLS 9 | 10 | # Use 100kHz frequency for wake condition 11 | WAKE_CLK_FREQ = 100000 12 | 13 | # -- Enter your configuration below -- # 14 | 15 | # Lock the ATECC module when the code is run? 16 | LOCK_ATECC = False 17 | # 2-letter country code 18 | MY_COUNTRY = "US" 19 | # State or Province Name 20 | MY_STATE = "New York" 21 | # City Name 22 | MY_CITY = "New York" 23 | # Organization Name 24 | MY_ORG = "Adafruit" 25 | # Organizational Unit Name 26 | MY_SECTION = "Crypto" 27 | # Which ATECC slot (0-4) to use 28 | ATECC_SLOT = 0 29 | # Generate new private key, or use existing key 30 | GENERATE_PRIVATE_KEY = True 31 | 32 | # -- END Configuration, code below -- # 33 | 34 | # Initialize the i2c bus 35 | i2c = busio.I2C(board.SCL, board.SDA, frequency=WAKE_CLK_FREQ) 36 | 37 | # Initialize a new atecc object 38 | atecc = ATECC(i2c) 39 | 40 | print("ATECC Serial Number: ", atecc.serial_number) 41 | 42 | if not atecc.locked: 43 | if not LOCK_ATECC: 44 | raise RuntimeError("The ATECC is not locked, set LOCK_ATECC to True in code.py.") 45 | print("Writing default configuration to the device...") 46 | atecc.write_config(CFG_TLS) 47 | print("Wrote configuration, locking ATECC module...") 48 | # Lock ATECC config, data, and otp zones 49 | atecc.lock_all_zones() 50 | print("ATECC locked!") 51 | 52 | print("Generating Certificate Signing Request...") 53 | # Initialize a certificate signing request with provided info 54 | csr = cert_utils.CSR( 55 | atecc, 56 | ATECC_SLOT, 57 | GENERATE_PRIVATE_KEY, 58 | MY_COUNTRY, 59 | MY_STATE, 60 | MY_CITY, 61 | MY_ORG, 62 | MY_SECTION, 63 | ) 64 | # Generate CSR 65 | my_csr = csr.generate_csr() 66 | print("-----BEGIN CERTIFICATE REQUEST-----\n") 67 | print(my_csr.decode("utf-8")) 68 | print("-----END CERTIFICATE REQUEST-----") 69 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | .. image:: https://readthedocs.org/projects/adafruit-circuitpython-atecc/badge/?version=latest 5 | :target: https://docs.circuitpython.org/projects/atecc/en/latest/ 6 | :alt: Documentation Status 7 | 8 | .. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg 9 | :target: https://adafru.it/discord 10 | :alt: Discord 11 | 12 | .. image:: https://github.com/adafruit/Adafruit_CircuitPython_ATECC/workflows/Build%20CI/badge.svg 13 | :target: https://github.com/adafruit/Adafruit_CircuitPython_ATECC/actions 14 | :alt: Build Status 15 | 16 | .. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json 17 | :target: https://github.com/astral-sh/ruff 18 | :alt: Code Style: Ruff 19 | 20 | 21 | Driver for `Microchip's ATECCx08 cryptographic co-processors with secure hardware-based key storage `_. 22 | 23 | Note: This library was developed and tested with an ATECC608A, but should work for ATECC508 modules as well. 24 | 25 | 26 | Dependencies 27 | ============= 28 | This driver depends on: 29 | 30 | * `Adafruit CircuitPython `_ 31 | * `Bus Device `_ 32 | 33 | Please ensure all dependencies are available on the CircuitPython filesystem. 34 | This is easily achieved by downloading 35 | `the Adafruit library and driver bundle `_. 36 | 37 | Installing from PyPI 38 | ===================== 39 | .. note:: This library is not available on PyPI yet. Install documentation is included 40 | as a standard element. Stay tuned for PyPI availability! 41 | 42 | On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from 43 | PyPI `_. To install for current user: 44 | 45 | .. code-block:: shell 46 | 47 | pip3 install adafruit-circuitpython-atecc 48 | 49 | To install system-wide (this may be required in some cases): 50 | 51 | .. code-block:: shell 52 | 53 | sudo pip3 install adafruit-circuitpython-atecc 54 | 55 | To install in a virtual environment in your current project: 56 | 57 | .. code-block:: shell 58 | 59 | mkdir project-name && cd project-name 60 | python3 -m venv .venv 61 | source .venv/bin/activate 62 | pip3 install adafruit-circuitpython-atecc 63 | 64 | Usage Example 65 | ============= 66 | 67 | Examples of using this module are in examples folder. 68 | 69 | Documentation 70 | ============= 71 | 72 | API documentation for this library can be found on `Read the Docs `_. 73 | 74 | For information on building library documentation, please check out `this guide `_. 75 | 76 | Contributing 77 | ============ 78 | 79 | Contributions are welcome! Please read our `Code of Conduct 80 | `_ 81 | before contributing to help this project stay welcoming. 82 | -------------------------------------------------------------------------------- /ruff.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | target-version = "py38" 6 | line-length = 100 7 | 8 | [lint] 9 | preview = true 10 | select = ["I", "PL", "UP"] 11 | 12 | extend-select = [ 13 | "D419", # empty-docstring 14 | "E501", # line-too-long 15 | "W291", # trailing-whitespace 16 | "PLC0414", # useless-import-alias 17 | "PLC2401", # non-ascii-name 18 | "PLC2801", # unnecessary-dunder-call 19 | "PLC3002", # unnecessary-direct-lambda-call 20 | "PLE0101", # return-in-init 21 | "F706", # return-outside-function 22 | "F704", # yield-outside-function 23 | "PLE0116", # continue-in-finally 24 | "PLE0117", # nonlocal-without-binding 25 | "PLE0241", # duplicate-bases 26 | "PLE0302", # unexpected-special-method-signature 27 | "PLE0604", # invalid-all-object 28 | "PLE0605", # invalid-all-format 29 | "PLE0643", # potential-index-error 30 | "PLE0704", # misplaced-bare-raise 31 | "PLE1141", # dict-iter-missing-items 32 | "PLE1142", # await-outside-async 33 | "PLE1205", # logging-too-many-args 34 | "PLE1206", # logging-too-few-args 35 | "PLE1307", # bad-string-format-type 36 | "PLE1310", # bad-str-strip-call 37 | "PLE1507", # invalid-envvar-value 38 | "PLE2502", # bidirectional-unicode 39 | "PLE2510", # invalid-character-backspace 40 | "PLE2512", # invalid-character-sub 41 | "PLE2513", # invalid-character-esc 42 | "PLE2514", # invalid-character-nul 43 | "PLE2515", # invalid-character-zero-width-space 44 | "PLR0124", # comparison-with-itself 45 | "PLR0202", # no-classmethod-decorator 46 | "PLR0203", # no-staticmethod-decorator 47 | "UP004", # useless-object-inheritance 48 | "PLR0206", # property-with-parameters 49 | "PLR0904", # too-many-public-methods 50 | "PLR0911", # too-many-return-statements 51 | "PLR0912", # too-many-branches 52 | "PLR0913", # too-many-arguments 53 | "PLR0914", # too-many-locals 54 | "PLR0915", # too-many-statements 55 | "PLR0916", # too-many-boolean-expressions 56 | "PLR1702", # too-many-nested-blocks 57 | "PLR1704", # redefined-argument-from-local 58 | "PLR1711", # useless-return 59 | "C416", # unnecessary-comprehension 60 | "PLR1733", # unnecessary-dict-index-lookup 61 | "PLR1736", # unnecessary-list-index-lookup 62 | 63 | # ruff reports this rule is unstable 64 | #"PLR6301", # no-self-use 65 | 66 | "PLW0108", # unnecessary-lambda 67 | "PLW0120", # useless-else-on-loop 68 | "PLW0127", # self-assigning-variable 69 | "PLW0129", # assert-on-string-literal 70 | "B033", # duplicate-value 71 | "PLW0131", # named-expr-without-context 72 | "PLW0245", # super-without-brackets 73 | "PLW0406", # import-self 74 | "PLW0602", # global-variable-not-assigned 75 | "PLW0603", # global-statement 76 | "PLW0604", # global-at-module-level 77 | 78 | # fails on the try: import typing used by libraries 79 | #"F401", # unused-import 80 | 81 | "F841", # unused-variable 82 | "E722", # bare-except 83 | "PLW0711", # binary-op-exception 84 | "PLW1501", # bad-open-mode 85 | "PLW1508", # invalid-envvar-default 86 | "PLW1509", # subprocess-popen-preexec-fn 87 | "PLW2101", # useless-with-lock 88 | "PLW3301", # nested-min-max 89 | ] 90 | 91 | ignore = [ 92 | "PLR2004", # magic-value-comparison 93 | "UP030", # format literals 94 | "PLW1514", # unspecified-encoding 95 | "PLR0913", # too-many-arguments 96 | "PLR0915", # too-many-statements 97 | "PLR0917", # too-many-positional-arguments 98 | "PLR0904", # too-many-public-methods 99 | "PLR0912", # too-many-branches 100 | "PLR0916", # too-many-boolean-expressions 101 | ] 102 | 103 | [lint.per-file-ignores] 104 | "adafruit_atecc/adafruit_atecc.py" = ["E501"] 105 | 106 | [format] 107 | line-ending = "lf" 108 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | import datetime 6 | import os 7 | import sys 8 | 9 | sys.path.insert(0, os.path.abspath("..")) 10 | 11 | # -- General configuration ------------------------------------------------ 12 | 13 | # Add any Sphinx extension module names here, as strings. They can be 14 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 15 | # ones. 16 | extensions = [ 17 | "sphinx.ext.autodoc", 18 | "sphinxcontrib.jquery", 19 | "sphinx.ext.intersphinx", 20 | "sphinx.ext.napoleon", 21 | "sphinx.ext.todo", 22 | ] 23 | 24 | # Uncomment the below if you use native CircuitPython modules such as 25 | # digitalio, micropython and busio. List the modules you use. Without it, the 26 | # autodoc module docs will fail to generate with a warning. 27 | autodoc_mock_imports = ["micropython", "adafruit-bus-device", "adafruit-binascii"] 28 | 29 | intersphinx_mapping = { 30 | "python": ("https://docs.python.org/3", None), 31 | "BusDevice": ( 32 | "https://docs.circuitpython.org/projects/busdevice/en/latest/", 33 | None, 34 | ), 35 | "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), 36 | } 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ["_templates"] 40 | 41 | source_suffix = ".rst" 42 | 43 | # The master toctree document. 44 | master_doc = "index" 45 | 46 | # General information about the project. 47 | project = "Adafruit ATECC Library" 48 | creation_year = "2019" 49 | current_year = str(datetime.datetime.now().year) 50 | year_duration = ( 51 | current_year if current_year == creation_year else creation_year + " - " + current_year 52 | ) 53 | copyright = year_duration + " Brent Rubell" 54 | author = "Brent Rubell" 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | # The short X.Y version. 61 | version = "1.0" 62 | # The full version, including alpha/beta/rc tags. 63 | release = "1.0" 64 | 65 | # The language for content autogenerated by Sphinx. Refer to documentation 66 | # for a list of supported languages. 67 | # 68 | # This is also used if you do content translation via gettext catalogs. 69 | # Usually you set "language" from the command line for these cases. 70 | language = "en" 71 | 72 | # List of patterns, relative to source directory, that match files and 73 | # directories to ignore when looking for source files. 74 | # This patterns also effect to html_static_path and html_extra_path 75 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] 76 | 77 | # The reST default role (used for this markup: `text`) to use for all 78 | # documents. 79 | # 80 | default_role = "any" 81 | 82 | # If true, '()' will be appended to :func: etc. cross-reference text. 83 | # 84 | add_function_parentheses = True 85 | 86 | # The name of the Pygments (syntax highlighting) style to use. 87 | pygments_style = "sphinx" 88 | 89 | # If true, `todo` and `todoList` produce output, else they produce nothing. 90 | todo_include_todos = False 91 | 92 | # If this is True, todo emits a warning for each TODO entries. The default is False. 93 | todo_emit_warnings = True 94 | 95 | napoleon_numpy_docstring = False 96 | 97 | # -- Options for HTML output ---------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | # 102 | import sphinx_rtd_theme 103 | 104 | html_theme = "sphinx_rtd_theme" 105 | 106 | # Add any paths that contain custom static files (such as style sheets) here, 107 | # relative to this directory. They are copied after the builtin static files, 108 | # so a file named "default.css" will overwrite the builtin "default.css". 109 | html_static_path = ["_static"] 110 | 111 | # Include extra css to work around rtd theme glitches 112 | html_css_files = ["custom.css"] 113 | 114 | # The name of an image file (relative to this directory) to use as a favicon of 115 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 116 | # pixels large. 117 | # 118 | html_favicon = "_static/favicon.ico" 119 | 120 | # Output file base name for HTML help builder. 121 | htmlhelp_basename = "AdafruitAteccLibrarydoc" 122 | 123 | # -- Options for LaTeX output --------------------------------------------- 124 | 125 | latex_elements = { 126 | # The paper size ('letterpaper' or 'a4paper'). 127 | # 128 | # 'papersize': 'letterpaper', 129 | # The font size ('10pt', '11pt' or '12pt'). 130 | # 131 | # 'pointsize': '10pt', 132 | # Additional stuff for the LaTeX preamble. 133 | # 134 | # 'preamble': '', 135 | # Latex figure (float) alignment 136 | # 137 | # 'figure_align': 'htbp', 138 | } 139 | 140 | # Grouping the document tree into LaTeX files. List of tuples 141 | # (source start file, target name, title, 142 | # author, documentclass [howto, manual, or own class]). 143 | latex_documents = [ 144 | ( 145 | master_doc, 146 | "AdafruitATECCLibrary.tex", 147 | "AdafruitATECC Library Documentation", 148 | author, 149 | "manual", 150 | ), 151 | ] 152 | 153 | # -- Options for manual page output --------------------------------------- 154 | 155 | # One entry per manual page. List of tuples 156 | # (source start file, name, description, authors, manual section). 157 | man_pages = [ 158 | ( 159 | master_doc, 160 | "AdafruitATECClibrary", 161 | "Adafruit ATECC Library Documentation", 162 | [author], 163 | 1, 164 | ) 165 | ] 166 | 167 | # -- Options for Texinfo output ------------------------------------------- 168 | 169 | # Grouping the document tree into Texinfo files. List of tuples 170 | # (source start file, target name, title, author, 171 | # dir menu entry, description, category) 172 | texinfo_documents = [ 173 | ( 174 | master_doc, 175 | "AdafruitATECCLibrary", 176 | "Adafruit ATECC Library Documentation", 177 | author, 178 | "AdafruitATECCLibrary", 179 | "One line description of project.", 180 | "Miscellaneous", 181 | ), 182 | ] 183 | -------------------------------------------------------------------------------- /adafruit_atecc/adafruit_atecc_cert_util.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2018 Arduino SA. All rights reserved. 2 | # SPDX-FileCopyrightText: 2019 Brent Rubell for Adafruit Industries 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | # Copyright (c) 2018 Arduino SA. All rights reserved. 7 | # 8 | # This library is free software; you can redistribute it and/or 9 | # modify it under the terms of the GNU Lesser General Public 10 | # License as published by the Free Software Foundation; either 11 | # version 2.1 of the License, or (at your option) any later version. 12 | # 13 | # This library is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | # Lesser General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Lesser General Public 19 | # License along with this library; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 21 | # 22 | # The MIT License (MIT) 23 | """ 24 | `adafruit_atecc_cert_util` 25 | ================================================================================ 26 | 27 | Certification Generation and Helper Utilities for the Adafruit_ATECC Module. 28 | 29 | * Author(s): Brent Rubell 30 | 31 | Implementation Notes 32 | -------------------- 33 | 34 | **Software and Dependencies:** 35 | 36 | * Adafruit CircuitPython firmware for the supported boards: 37 | https://github.com/adafruit/circuitpython/releases 38 | """ 39 | 40 | from adafruit_binascii import b2a_base64 41 | 42 | import adafruit_atecc.adafruit_atecc_asn1 as asn1 43 | from adafruit_atecc.adafruit_atecc import ATECC 44 | 45 | 46 | class CSR: 47 | """Certificate Signing Request Builder. 48 | 49 | :param adafruit_atecc atecc: ATECC module. 50 | :param slot_num: ATECC module slot (from 0 to 4). 51 | :param bool private_key: Generate a new private 52 | key in selected slot? 53 | :param str country: 2-letter country code. 54 | :param str state_prov: State or Province name, 55 | :param str city: City name. 56 | :param str org: Organization name. 57 | :param str org_unit: Organizational unit name. 58 | 59 | """ 60 | 61 | def __init__( 62 | self, 63 | atecc: ATECC, 64 | slot_num: int, 65 | private_key: bool, 66 | country: str, 67 | state_prov: str, 68 | city: str, 69 | org: str, 70 | org_unit: str, 71 | ): 72 | self._atecc = atecc 73 | self.private_key = private_key 74 | self._slot = slot_num 75 | self._country = country 76 | self._state_province = state_prov 77 | self._locality = city 78 | self._org = org 79 | self._org_unit = org_unit 80 | self._common = self._atecc.serial_number 81 | self._version_len = 3 82 | self._cert = None 83 | self._key = None 84 | 85 | def generate_csr(self) -> bytearray: 86 | """Generates and returns a certificate signing request.""" 87 | self._csr_begin() 88 | csr = self._csr_end() 89 | return csr 90 | 91 | def _csr_begin(self) -> None: 92 | """Initializes CSR generation.""" 93 | assert 0 <= self._slot <= 4, "Provided slot must be between 0 and 4." 94 | # Create a new key 95 | self._key = bytearray(64) 96 | if self.private_key: 97 | self._atecc.gen_key(self._key, self._slot, self.private_key) 98 | return 99 | self._atecc.gen_key(self._key, self._slot, self.private_key) 100 | 101 | def _csr_end(self) -> bytearray: 102 | """Generates and returns 103 | a certificate signing request as a base64 string.""" 104 | len_issuer_subject = asn1.issuer_or_subject_length( 105 | self._country, 106 | self._state_province, 107 | self._locality, 108 | self._org, 109 | self._org_unit, 110 | self._common, 111 | ) 112 | len_sub_header = asn1.get_sequence_header_length(len_issuer_subject) 113 | 114 | len_csr_info = self._version_len + len_issuer_subject 115 | len_csr_info += len_sub_header + 91 + 2 116 | len_csr_info_header = asn1.get_sequence_header_length(len_csr_info) 117 | 118 | # CSR Info Packet 119 | csr_info = bytearray() 120 | 121 | # Append CSR Info --> [0:2] 122 | asn1.get_sequence_header(len_csr_info, csr_info) 123 | 124 | # Append Version --> [3:5] 125 | asn1.get_version(csr_info) 126 | 127 | # Append Subject --> [6:7] 128 | asn1.get_sequence_header(len_issuer_subject, csr_info) 129 | 130 | # Append Issuer or Subject 131 | asn1.get_issuer_or_subject( 132 | csr_info, 133 | self._country, 134 | self._state_province, 135 | self._locality, 136 | self._org, 137 | self._org_unit, 138 | self._common, 139 | ) 140 | 141 | # Append Public Key 142 | asn1.get_public_key(csr_info, self._key) 143 | 144 | # Terminator 145 | csr_info += b"\xa0\x00" 146 | 147 | # Init. SHA-256 Calculation 148 | csr_info_sha_256 = bytearray(64) 149 | self._atecc.sha_start() 150 | 151 | for i in range(0, len_csr_info + len_csr_info_header, 64): 152 | chunk_len = (len_csr_info_header + len_csr_info) - i 153 | 154 | chunk_len = min(chunk_len, 64) 155 | if chunk_len == 64: 156 | self._atecc.sha_update(csr_info[i : i + 64]) 157 | else: 158 | csr_info_sha_256 = self._atecc.sha_digest(csr_info[i:]) 159 | 160 | # Sign the SHA256 Digest 161 | signature = bytearray(64) 162 | signature = self._atecc.ecdsa_sign(self._slot, csr_info_sha_256) 163 | 164 | # Calculations for signature and csr length 165 | len_signature = asn1.get_signature_length(signature) 166 | len_csr = len_csr_info_header + len_csr_info + len_signature 167 | asn1.get_sequence_header_length(len_csr) 168 | 169 | # append signature to csr 170 | csr = bytearray() 171 | asn1.get_sequence_header(len_csr, csr) 172 | # append csr_info 173 | csr += csr_info 174 | asn1.get_signature(signature, csr) 175 | # encode and return 176 | csr = b2a_base64(csr) 177 | return csr 178 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # Adafruit Community Code of Conduct 8 | 9 | ## Our Pledge 10 | 11 | In the interest of fostering an open and welcoming environment, we as 12 | contributors and leaders pledge to making participation in our project and 13 | our community a harassment-free experience for everyone, regardless of age, body 14 | size, disability, ethnicity, gender identity and expression, level or type of 15 | experience, education, socio-economic status, nationality, personal appearance, 16 | race, religion, or sexual identity and orientation. 17 | 18 | ## Our Standards 19 | 20 | We are committed to providing a friendly, safe and welcoming environment for 21 | all. 22 | 23 | Examples of behavior that contributes to creating a positive environment 24 | include: 25 | 26 | * Be kind and courteous to others 27 | * Using welcoming and inclusive language 28 | * Being respectful of differing viewpoints and experiences 29 | * Collaborating with other community members 30 | * Gracefully accepting constructive criticism 31 | * Focusing on what is best for the community 32 | * Showing empathy towards other community members 33 | 34 | Examples of unacceptable behavior by participants include: 35 | 36 | * The use of sexualized language or imagery and sexual attention or advances 37 | * The use of inappropriate images, including in a community member's avatar 38 | * The use of inappropriate language, including in a community member's nickname 39 | * Any spamming, flaming, baiting or other attention-stealing behavior 40 | * Excessive or unwelcome helping; answering outside the scope of the question 41 | asked 42 | * Trolling, insulting/derogatory comments, and personal or political attacks 43 | * Promoting or spreading disinformation, lies, or conspiracy theories against 44 | a person, group, organisation, project, or community 45 | * Public or private harassment 46 | * Publishing others' private information, such as a physical or electronic 47 | address, without explicit permission 48 | * Other conduct which could reasonably be considered inappropriate 49 | 50 | The goal of the standards and moderation guidelines outlined here is to build 51 | and maintain a respectful community. We ask that you don’t just aim to be 52 | "technically unimpeachable", but rather try to be your best self. 53 | 54 | We value many things beyond technical expertise, including collaboration and 55 | supporting others within our community. Providing a positive experience for 56 | other community members can have a much more significant impact than simply 57 | providing the correct answer. 58 | 59 | ## Our Responsibilities 60 | 61 | Project leaders are responsible for clarifying the standards of acceptable 62 | behavior and are expected to take appropriate and fair corrective action in 63 | response to any instances of unacceptable behavior. 64 | 65 | Project leaders have the right and responsibility to remove, edit, or 66 | reject messages, comments, commits, code, issues, and other contributions 67 | that are not aligned to this Code of Conduct, or to ban temporarily or 68 | permanently any community member for other behaviors that they deem 69 | inappropriate, threatening, offensive, or harmful. 70 | 71 | ## Moderation 72 | 73 | Instances of behaviors that violate the Adafruit Community Code of Conduct 74 | may be reported by any member of the community. Community members are 75 | encouraged to report these situations, including situations they witness 76 | involving other community members. 77 | 78 | You may report in the following ways: 79 | 80 | In any situation, you may send an email to . 81 | 82 | On the Adafruit Discord, you may send an open message from any channel 83 | to all Community Moderators by tagging @community moderators. You may 84 | also send an open message from any channel, or a direct message to 85 | @kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, 86 | @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. 87 | 88 | Email and direct message reports will be kept confidential. 89 | 90 | In situations on Discord where the issue is particularly egregious, possibly 91 | illegal, requires immediate action, or violates the Discord terms of service, 92 | you should also report the message directly to Discord. 93 | 94 | These are the steps for upholding our community’s standards of conduct. 95 | 96 | 1. Any member of the community may report any situation that violates the 97 | Adafruit Community Code of Conduct. All reports will be reviewed and 98 | investigated. 99 | 2. If the behavior is an egregious violation, the community member who 100 | committed the violation may be banned immediately, without warning. 101 | 3. Otherwise, moderators will first respond to such behavior with a warning. 102 | 4. Moderators follow a soft "three strikes" policy - the community member may 103 | be given another chance, if they are receptive to the warning and change their 104 | behavior. 105 | 5. If the community member is unreceptive or unreasonable when warned by a 106 | moderator, or the warning goes unheeded, they may be banned for a first or 107 | second offense. Repeated offenses will result in the community member being 108 | banned. 109 | 110 | ## Scope 111 | 112 | This Code of Conduct and the enforcement policies listed above apply to all 113 | Adafruit Community venues. This includes but is not limited to any community 114 | spaces (both public and private), the entire Adafruit Discord server, and 115 | Adafruit GitHub repositories. Examples of Adafruit Community spaces include 116 | but are not limited to meet-ups, audio chats on the Adafruit Discord, or 117 | interaction at a conference. 118 | 119 | This Code of Conduct applies both within project spaces and in public spaces 120 | when an individual is representing the project or its community. As a community 121 | member, you are representing our community, and are expected to behave 122 | accordingly. 123 | 124 | ## Attribution 125 | 126 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 127 | version 1.4, available at 128 | , 129 | and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). 130 | 131 | For other projects adopting the Adafruit Community Code of 132 | Conduct, please contact the maintainers of those projects for enforcement. 133 | If you wish to use this code of conduct for your own project, consider 134 | explicitly mentioning your moderation policy or making a copy with your 135 | own moderation policy so as to avoid confusion. 136 | -------------------------------------------------------------------------------- /adafruit_atecc/adafruit_atecc_asn1.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2018 Arduino SA. All rights reserved. 2 | # SPDX-FileCopyrightText: 2019 Brent Rubell for Adafruit Industries 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | # Copyright (c) 2018 Arduino SA. All rights reserved. 7 | # 8 | # This library is free software; you can redistribute it and/or 9 | # modify it under the terms of the GNU Lesser General Public 10 | # License as published by the Free Software Foundation; either 11 | # version 2.1 of the License, or (at your option) any later version. 12 | # 13 | # This library is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | # Lesser General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Lesser General Public 19 | # License along with this library; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 21 | 22 | """ 23 | `adafruit_atecc_asn1` 24 | ================================================================================ 25 | 26 | ASN.1 Utilities for the Adafruit_ATECC Module. 27 | 28 | * Author(s): Brent Rubell 29 | 30 | Implementation Notes 31 | -------------------- 32 | 33 | **Software and Dependencies:** 34 | 35 | * Adafruit CircuitPython firmware for the supported boards: 36 | https://github.com/adafruit/circuitpython/releases 37 | """ 38 | 39 | import struct 40 | 41 | 42 | def get_signature(signature: bytearray, data: bytearray) -> int: 43 | """ 44 | Appends signature data to buffer. 45 | 46 | :param bytearray signature: The signature to append 47 | :param bytearray data: The buffer to append the signature to 48 | :return: Updated length of the buffer 49 | """ 50 | # Signature algorithm 51 | data += b"\x30\x0a\x06\x08" 52 | # ECDSA with SHA256 53 | data += b"\x2a\x86\x48\xce\x3d\x04\x03\x02" 54 | r = signature[0] 55 | s = signature[32] 56 | r_len = 32 57 | s_len = 32 58 | 59 | while r == 0x00 and r_len > 1: 60 | r += 1 61 | r_len -= 1 62 | 63 | while s == 0x00 and s_len > 1: 64 | s += 1 65 | s_len -= 1 66 | 67 | if r & 0x80: 68 | r_len += 1 69 | 70 | if s & 0x80: 71 | s_len += 1 72 | 73 | data += b"\x03" + struct.pack("B", r_len + s_len + 7) + b"\x00" 74 | 75 | data += b"\x30" + struct.pack("B", r_len + s_len + 4) 76 | 77 | data += b"\x02" + struct.pack("B", r_len) 78 | 79 | if r & 0x80: 80 | data += b"\x00" 81 | r_len -= 1 82 | data += signature[0:r_len] 83 | 84 | if r & 0x80: 85 | r_len += 1 86 | 87 | data += b"\x02" + struct.pack("B", s_len) 88 | if s & 0x80: 89 | data += b"\x00" 90 | s_len -= 1 91 | 92 | data += signature[s_len:] 93 | 94 | if s & 0x80: 95 | s_len += 1 96 | 97 | return 21 + r_len + s_len 98 | 99 | 100 | def get_issuer_or_subject( 101 | data: bytearray, 102 | country: str, 103 | state_prov: str, 104 | locality: str, 105 | org: str, 106 | org_unit: str, 107 | common: str, 108 | ): 109 | """ 110 | Appends issuer or subject, if they exist, to data. 111 | 112 | :param bytearray data: buffer to append to 113 | :param str country: The country to append to the buffer 114 | :param str state_prov: The state/province to append to the buffer 115 | :param str locality: The locality to append to the buffer 116 | :param str org: The organization to append to the buffer 117 | :param str org_unit: The organizational unit to append to the buffer 118 | :param str common: The common data to append to the buffer 119 | """ 120 | if country: 121 | get_name(country, 0x06, data) 122 | if state_prov: 123 | get_name(state_prov, 0x08, data) 124 | if locality: 125 | get_name(locality, 0x07, data) 126 | if org: 127 | get_name(org, 0x0A, data) 128 | if org_unit: 129 | get_name(org_unit, 0x0B, data) 130 | if common: 131 | get_name(common, 0x03, data) 132 | 133 | 134 | def get_name(name: str, obj_type: int, data: bytearray) -> int: 135 | """ 136 | Appends ASN.1 string in form: set -> seq -> objid -> string 137 | 138 | :param str name: String to append to buffer. 139 | :param int obj_type: Object identifier type. 140 | :param bytearray data: Buffer to write to. 141 | :return: Length of the updated buffer 142 | """ 143 | # ASN.1 SET 144 | data += b"\x31" + struct.pack("B", len(name) + 9) 145 | # ASN.1 SEQUENCE 146 | data += b"\x30" + struct.pack("B", len(name) + 7) 147 | # ASN.1 OBJECT IDENTIFIER 148 | data += b"\x06\x03\x55\x04" + struct.pack("B", obj_type) 149 | 150 | # ASN.1 PRINTABLE STRING 151 | data += b"\x13" + struct.pack("B", len(name)) 152 | data.extend(name) 153 | return len(name) + 11 154 | 155 | 156 | def get_version(data: bytearray) -> None: 157 | """ 158 | Appends X.509 version to data. 159 | 160 | :param bytearray data: Buffer to append the version to 161 | """ 162 | # If no extensions are present, but a UniqueIdentifier 163 | # is present, the version SHOULD be 2 (value is 1) [4-1-2] 164 | data += b"\x02\x01\x00" 165 | 166 | 167 | def get_sequence_header(length: int, data: bytearray) -> None: 168 | """ 169 | Appends sequence header to provided data. 170 | 171 | :param int length: Length of the buffer 172 | :param bytearray data: The buffer 173 | """ 174 | data += b"\x30" 175 | if length > 255: 176 | data += b"\x82" 177 | data.append((length >> 8) & 0xFF) 178 | elif length > 127: 179 | data += b"\x81" 180 | length_byte = struct.pack("B", (length) & 0xFF) 181 | data += length_byte 182 | 183 | 184 | def get_public_key(data: bytearray, public_key: bytearray) -> None: 185 | """ 186 | Appends public key subject and object identifiers. 187 | 188 | :param bytearray data: buffer 189 | :param bytearray public_key: Public key to append 190 | """ 191 | # Subject: Public Key 192 | data += b"\x30" + struct.pack("B", (0x59) & 0xFF) + b"\x30\x13" 193 | # Object identifier: EC Public Key 194 | data += b"\x06\x07\x2a\x86\x48\xce\x3d\x02\x01" 195 | # Object identifier: PRIME 256 v1 196 | data += b"\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42\x00\x04" 197 | # Extend the buffer by the public key 198 | data += public_key 199 | 200 | 201 | def get_signature_length(signature: bytearray) -> int: 202 | """ 203 | Return length of ECDSA signature. 204 | 205 | :param bytearray signature: Signed SHA256 hash. 206 | :return: length of ECDSA signature. 207 | """ 208 | r = signature[0] 209 | s = signature[32] 210 | r_len = 32 211 | s_len = 32 212 | 213 | while r == 0x00 and r_len > 1: 214 | r += 1 215 | r_len -= 1 216 | 217 | if r & 0x80: 218 | r_len += 1 219 | 220 | while s == 0x00 and s_len > 1: 221 | s += 1 222 | s_len -= 1 223 | 224 | if s & 0x80: 225 | s_len += 1 226 | return 21 + r_len + s_len 227 | 228 | 229 | def get_sequence_header_length(seq_header_len: int) -> int: 230 | """ 231 | Returns length of SEQUENCE header. 232 | 233 | :param int seq_header_len: Sequence header length 234 | :return: Length of the sequence header 235 | """ 236 | if seq_header_len > 255: 237 | return 4 238 | if seq_header_len > 127: 239 | return 3 240 | return 2 241 | 242 | 243 | def issuer_or_subject_length( 244 | country: str, state_prov: str, city: str, org: str, org_unit: str, common: str 245 | ) -> int: 246 | """ 247 | Returns total length of provided certificate information. 248 | 249 | :param str country: Country of certificate 250 | :param str state_prov: State/province of certificate 251 | :param str city: City of certificate 252 | :param str org: Organization of certificate 253 | :param str org_unit: Organization unit of certificate 254 | :param str common: Common data of certificate 255 | :raises: ValueError if return value is <= 0 256 | :return: Total length of provided certificate information. 257 | """ 258 | tot_len = 0 259 | if country: 260 | tot_len += 11 + len(country) 261 | if state_prov: 262 | tot_len += 11 + len(state_prov) 263 | if city: 264 | tot_len += 11 + len(city) 265 | if org: 266 | tot_len += 11 + len(org) 267 | if org_unit: 268 | tot_len += 11 + len(org_unit) 269 | if common: 270 | tot_len += 11 + len(common) 271 | 272 | if tot_len <= 0: 273 | raise ValueError("Provided length must be > 0") 274 | return tot_len 275 | -------------------------------------------------------------------------------- /LICENSES/CC-BY-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International Creative Commons Corporation 2 | ("Creative Commons") is not a law firm and does not provide legal services 3 | or legal advice. Distribution of Creative Commons public licenses does not 4 | create a lawyer-client or other relationship. Creative Commons makes its licenses 5 | and related information available on an "as-is" basis. Creative Commons gives 6 | no warranties regarding its licenses, any material licensed under their terms 7 | and conditions, or any related information. Creative Commons disclaims all 8 | liability for damages resulting from their use to the fullest extent possible. 9 | 10 | Using Creative Commons Public Licenses 11 | 12 | Creative Commons public licenses provide a standard set of terms and conditions 13 | that creators and other rights holders may use to share original works of 14 | authorship and other material subject to copyright and certain other rights 15 | specified in the public license below. The following considerations are for 16 | informational purposes only, are not exhaustive, and do not form part of our 17 | licenses. 18 | 19 | Considerations for licensors: Our public licenses are intended for use by 20 | those authorized to give the public permission to use material in ways otherwise 21 | restricted by copyright and certain other rights. Our licenses are irrevocable. 22 | Licensors should read and understand the terms and conditions of the license 23 | they choose before applying it. Licensors should also secure all rights necessary 24 | before applying our licenses so that the public can reuse the material as 25 | expected. Licensors should clearly mark any material not subject to the license. 26 | This includes other CC-licensed material, or material used under an exception 27 | or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors 28 | 29 | Considerations for the public: By using one of our public licenses, a licensor 30 | grants the public permission to use the licensed material under specified 31 | terms and conditions. If the licensor's permission is not necessary for any 32 | reason–for example, because of any applicable exception or limitation to copyright–then 33 | that use is not regulated by the license. Our licenses grant only permissions 34 | under copyright and certain other rights that a licensor has authority to 35 | grant. Use of the licensed material may still be restricted for other reasons, 36 | including because others have copyright or other rights in the material. A 37 | licensor may make special requests, such as asking that all changes be marked 38 | or described. Although not required by our licenses, you are encouraged to 39 | respect those requests where reasonable. More considerations for the public 40 | : wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution 41 | 4.0 International Public License 42 | 43 | By exercising the Licensed Rights (defined below), You accept and agree to 44 | be bound by the terms and conditions of this Creative Commons Attribution 45 | 4.0 International Public License ("Public License"). To the extent this Public 46 | License may be interpreted as a contract, You are granted the Licensed Rights 47 | in consideration of Your acceptance of these terms and conditions, and the 48 | Licensor grants You such rights in consideration of benefits the Licensor 49 | receives from making the Licensed Material available under these terms and 50 | conditions. 51 | 52 | Section 1 – Definitions. 53 | 54 | a. Adapted Material means material subject to Copyright and Similar Rights 55 | that is derived from or based upon the Licensed Material and in which the 56 | Licensed Material is translated, altered, arranged, transformed, or otherwise 57 | modified in a manner requiring permission under the Copyright and Similar 58 | Rights held by the Licensor. For purposes of this Public License, where the 59 | Licensed Material is a musical work, performance, or sound recording, Adapted 60 | Material is always produced where the Licensed Material is synched in timed 61 | relation with a moving image. 62 | 63 | b. Adapter's License means the license You apply to Your Copyright and Similar 64 | Rights in Your contributions to Adapted Material in accordance with the terms 65 | and conditions of this Public License. 66 | 67 | c. Copyright and Similar Rights means copyright and/or similar rights closely 68 | related to copyright including, without limitation, performance, broadcast, 69 | sound recording, and Sui Generis Database Rights, without regard to how the 70 | rights are labeled or categorized. For purposes of this Public License, the 71 | rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 72 | 73 | d. Effective Technological Measures means those measures that, in the absence 74 | of proper authority, may not be circumvented under laws fulfilling obligations 75 | under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, 76 | and/or similar international agreements. 77 | 78 | e. Exceptions and Limitations means fair use, fair dealing, and/or any other 79 | exception or limitation to Copyright and Similar Rights that applies to Your 80 | use of the Licensed Material. 81 | 82 | f. Licensed Material means the artistic or literary work, database, or other 83 | material to which the Licensor applied this Public License. 84 | 85 | g. Licensed Rights means the rights granted to You subject to the terms and 86 | conditions of this Public License, which are limited to all Copyright and 87 | Similar Rights that apply to Your use of the Licensed Material and that the 88 | Licensor has authority to license. 89 | 90 | h. Licensor means the individual(s) or entity(ies) granting rights under this 91 | Public License. 92 | 93 | i. Share means to provide material to the public by any means or process that 94 | requires permission under the Licensed Rights, such as reproduction, public 95 | display, public performance, distribution, dissemination, communication, or 96 | importation, and to make material available to the public including in ways 97 | that members of the public may access the material from a place and at a time 98 | individually chosen by them. 99 | 100 | j. Sui Generis Database Rights means rights other than copyright resulting 101 | from Directive 96/9/EC of the European Parliament and of the Council of 11 102 | March 1996 on the legal protection of databases, as amended and/or succeeded, 103 | as well as other essentially equivalent rights anywhere in the world. 104 | 105 | k. You means the individual or entity exercising the Licensed Rights under 106 | this Public License. Your has a corresponding meaning. 107 | 108 | Section 2 – Scope. 109 | 110 | a. License grant. 111 | 112 | 1. Subject to the terms and conditions of this Public License, the Licensor 113 | hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, 114 | irrevocable license to exercise the Licensed Rights in the Licensed Material 115 | to: 116 | 117 | A. reproduce and Share the Licensed Material, in whole or in part; and 118 | 119 | B. produce, reproduce, and Share Adapted Material. 120 | 121 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions 122 | and Limitations apply to Your use, this Public License does not apply, and 123 | You do not need to comply with its terms and conditions. 124 | 125 | 3. Term. The term of this Public License is specified in Section 6(a). 126 | 127 | 4. Media and formats; technical modifications allowed. The Licensor authorizes 128 | You to exercise the Licensed Rights in all media and formats whether now known 129 | or hereafter created, and to make technical modifications necessary to do 130 | so. The Licensor waives and/or agrees not to assert any right or authority 131 | to forbid You from making technical modifications necessary to exercise the 132 | Licensed Rights, including technical modifications necessary to circumvent 133 | Effective Technological Measures. For purposes of this Public License, simply 134 | making modifications authorized by this Section 2(a)(4) never produces Adapted 135 | Material. 136 | 137 | 5. Downstream recipients. 138 | 139 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed 140 | Material automatically receives an offer from the Licensor to exercise the 141 | Licensed Rights under the terms and conditions of this Public License. 142 | 143 | B. No downstream restrictions. You may not offer or impose any additional 144 | or different terms or conditions on, or apply any Effective Technological 145 | Measures to, the Licensed Material if doing so restricts exercise of the Licensed 146 | Rights by any recipient of the Licensed Material. 147 | 148 | 6. No endorsement. Nothing in this Public License constitutes or may be construed 149 | as permission to assert or imply that You are, or that Your use of the Licensed 150 | Material is, connected with, or sponsored, endorsed, or granted official status 151 | by, the Licensor or others designated to receive attribution as provided in 152 | Section 3(a)(1)(A)(i). 153 | 154 | b. Other rights. 155 | 156 | 1. Moral rights, such as the right of integrity, are not licensed under this 157 | Public License, nor are publicity, privacy, and/or other similar personality 158 | rights; however, to the extent possible, the Licensor waives and/or agrees 159 | not to assert any such rights held by the Licensor to the limited extent necessary 160 | to allow You to exercise the Licensed Rights, but not otherwise. 161 | 162 | 2. Patent and trademark rights are not licensed under this Public License. 163 | 164 | 3. To the extent possible, the Licensor waives any right to collect royalties 165 | from You for the exercise of the Licensed Rights, whether directly or through 166 | a collecting society under any voluntary or waivable statutory or compulsory 167 | licensing scheme. In all other cases the Licensor expressly reserves any right 168 | to collect such royalties. 169 | 170 | Section 3 – License Conditions. 171 | 172 | Your exercise of the Licensed Rights is expressly made subject to the following 173 | conditions. 174 | 175 | a. Attribution. 176 | 177 | 1. If You Share the Licensed Material (including in modified form), You must: 178 | 179 | A. retain the following if it is supplied by the Licensor with the Licensed 180 | Material: 181 | 182 | i. identification of the creator(s) of the Licensed Material and any others 183 | designated to receive attribution, in any reasonable manner requested by the 184 | Licensor (including by pseudonym if designated); 185 | 186 | ii. a copyright notice; 187 | 188 | iii. a notice that refers to this Public License; 189 | 190 | iv. a notice that refers to the disclaimer of warranties; 191 | 192 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 193 | 194 | B. indicate if You modified the Licensed Material and retain an indication 195 | of any previous modifications; and 196 | 197 | C. indicate the Licensed Material is licensed under this Public License, and 198 | include the text of, or the URI or hyperlink to, this Public License. 199 | 200 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner 201 | based on the medium, means, and context in which You Share the Licensed Material. 202 | For example, it may be reasonable to satisfy the conditions by providing a 203 | URI or hyperlink to a resource that includes the required information. 204 | 205 | 3. If requested by the Licensor, You must remove any of the information required 206 | by Section 3(a)(1)(A) to the extent reasonably practicable. 207 | 208 | 4. If You Share Adapted Material You produce, the Adapter's License You apply 209 | must not prevent recipients of the Adapted Material from complying with this 210 | Public License. 211 | 212 | Section 4 – Sui Generis Database Rights. 213 | 214 | Where the Licensed Rights include Sui Generis Database Rights that apply to 215 | Your use of the Licensed Material: 216 | 217 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, 218 | reuse, reproduce, and Share all or a substantial portion of the contents of 219 | the database; 220 | 221 | b. if You include all or a substantial portion of the database contents in 222 | a database in which You have Sui Generis Database Rights, then the database 223 | in which You have Sui Generis Database Rights (but not its individual contents) 224 | is Adapted Material; and 225 | 226 | c. You must comply with the conditions in Section 3(a) if You Share all or 227 | a substantial portion of the contents of the database. 228 | 229 | For the avoidance of doubt, this Section 4 supplements and does not replace 230 | Your obligations under this Public License where the Licensed Rights include 231 | other Copyright and Similar Rights. 232 | 233 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 234 | 235 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, 236 | the Licensor offers the Licensed Material as-is and as-available, and makes 237 | no representations or warranties of any kind concerning the Licensed Material, 238 | whether express, implied, statutory, or other. This includes, without limitation, 239 | warranties of title, merchantability, fitness for a particular purpose, non-infringement, 240 | absence of latent or other defects, accuracy, or the presence or absence of 241 | errors, whether or not known or discoverable. Where disclaimers of warranties 242 | are not allowed in full or in part, this disclaimer may not apply to You. 243 | 244 | b. To the extent possible, in no event will the Licensor be liable to You 245 | on any legal theory (including, without limitation, negligence) or otherwise 246 | for any direct, special, indirect, incidental, consequential, punitive, exemplary, 247 | or other losses, costs, expenses, or damages arising out of this Public License 248 | or use of the Licensed Material, even if the Licensor has been advised of 249 | the possibility of such losses, costs, expenses, or damages. Where a limitation 250 | of liability is not allowed in full or in part, this limitation may not apply 251 | to You. 252 | 253 | c. The disclaimer of warranties and limitation of liability provided above 254 | shall be interpreted in a manner that, to the extent possible, most closely 255 | approximates an absolute disclaimer and waiver of all liability. 256 | 257 | Section 6 – Term and Termination. 258 | 259 | a. This Public License applies for the term of the Copyright and Similar Rights 260 | licensed here. However, if You fail to comply with this Public License, then 261 | Your rights under this Public License terminate automatically. 262 | 263 | b. Where Your right to use the Licensed Material has terminated under Section 264 | 6(a), it reinstates: 265 | 266 | 1. automatically as of the date the violation is cured, provided it is cured 267 | within 30 days of Your discovery of the violation; or 268 | 269 | 2. upon express reinstatement by the Licensor. 270 | 271 | c. For the avoidance of doubt, this Section 6(b) does not affect any right 272 | the Licensor may have to seek remedies for Your violations of this Public 273 | License. 274 | 275 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material 276 | under separate terms or conditions or stop distributing the Licensed Material 277 | at any time; however, doing so will not terminate this Public License. 278 | 279 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 280 | 281 | Section 7 – Other Terms and Conditions. 282 | 283 | a. The Licensor shall not be bound by any additional or different terms or 284 | conditions communicated by You unless expressly agreed. 285 | 286 | b. Any arrangements, understandings, or agreements regarding the Licensed 287 | Material not stated herein are separate from and independent of the terms 288 | and conditions of this Public License. 289 | 290 | Section 8 – Interpretation. 291 | 292 | a. For the avoidance of doubt, this Public License does not, and shall not 293 | be interpreted to, reduce, limit, restrict, or impose conditions on any use 294 | of the Licensed Material that could lawfully be made without permission under 295 | this Public License. 296 | 297 | b. To the extent possible, if any provision of this Public License is deemed 298 | unenforceable, it shall be automatically reformed to the minimum extent necessary 299 | to make it enforceable. If the provision cannot be reformed, it shall be severed 300 | from this Public License without affecting the enforceability of the remaining 301 | terms and conditions. 302 | 303 | c. No term or condition of this Public License will be waived and no failure 304 | to comply consented to unless expressly agreed to by the Licensor. 305 | 306 | d. Nothing in this Public License constitutes or may be interpreted as a limitation 307 | upon, or waiver of, any privileges and immunities that apply to the Licensor 308 | or You, including from the legal processes of any jurisdiction or authority. 309 | 310 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative 311 | Commons may elect to apply one of its public licenses to material it publishes 312 | and in those instances will be considered the "Licensor." The text of the 313 | Creative Commons public licenses is dedicated to the public domain under the 314 | CC0 Public Domain Dedication. Except for the limited purpose of indicating 315 | that material is shared under a Creative Commons public license or as otherwise 316 | permitted by the Creative Commons policies published at creativecommons.org/policies, 317 | Creative Commons does not authorize the use of the trademark "Creative Commons" 318 | or any other trademark or logo of Creative Commons without its prior written 319 | consent including, without limitation, in connection with any unauthorized 320 | modifications to any of its public licenses or any other arrangements, understandings, 321 | or agreements concerning use of licensed material. For the avoidance of doubt, 322 | this paragraph does not form part of the public licenses. 323 | 324 | Creative Commons may be contacted at creativecommons.org. 325 | -------------------------------------------------------------------------------- /adafruit_atecc/adafruit_atecc.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2018 Arduino SA 2 | # SPDX-FileCopyrightText: 2019 Brent Rubell for Adafruit Industries 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | # Copyright (c) 2018 Arduino SA. All rights reserved. 7 | # 8 | # This library is free software; you can redistribute it and/or 9 | # modify it under the terms of the GNU Lesser General Public 10 | # License as published by the Free Software Foundation; either 11 | # version 2.1 of the License, or (at your option) any later version. 12 | # 13 | # This library is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | # Lesser General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Lesser General Public 19 | # License along with this library; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 21 | 22 | """ 23 | `adafruit_atecc` 24 | ================================================================================ 25 | 26 | CircuitPython module for the Microchip ATECCx08A Cryptographic Co-Processor 27 | 28 | 29 | * Author(s): Brent Rubell 30 | 31 | Implementation Notes 32 | -------------------- 33 | 34 | **Software and Dependencies:** 35 | 36 | * Adafruit CircuitPython firmware for the supported boards: 37 | https://github.com/adafruit/circuitpython/releases 38 | 39 | * Adafruit Bus Device library: 40 | https://github.com/adafruit/Adafruit_CircuitPython_BusDevice 41 | 42 | * Adafruit binascii library: 43 | https://github.com/adafruit/Adafruit_CircuitPython_binascii 44 | 45 | """ 46 | 47 | import time 48 | from struct import pack 49 | 50 | # Since the board may or may not have access to the typing library we need 51 | # to have this in a try/except to enable type hinting for the IDEs while 52 | # not breaking the runtime on the controller. 53 | try: 54 | from typing import Any, Optional, Sized 55 | 56 | from busio import I2C 57 | except ImportError: 58 | pass 59 | 60 | from adafruit_binascii import hexlify, unhexlify 61 | from adafruit_bus_device.i2c_device import I2CDevice 62 | from micropython import const 63 | 64 | __version__ = "0.0.0+auto.0" 65 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ATECC.git" 66 | 67 | 68 | def _convert_i2c_addr_to_atecc_addr(i2c_addr=0x60): 69 | int(hex(i2c_addr), 16) 70 | return i2c_addr << 1 71 | 72 | 73 | # Device Address 74 | _I2C_ADDR = 0x60 75 | _REG_ATECC_ADDR = _convert_i2c_addr_to_atecc_addr(i2c_addr=_I2C_ADDR) 76 | 77 | _REG_ATECC_DEVICE_ADDR = _REG_ATECC_ADDR >> 1 78 | 79 | # Version Registers 80 | _ATECC_508_VER = const(0x50) 81 | _ATECC_608_VER = const(0x60) 82 | 83 | # Clock constants 84 | _WAKE_CLK_FREQ = 100000 # slower clock speed 85 | _TWLO_TIME = 6e-5 # TWlo, in microseconds 86 | 87 | # Command Opcodes (9-1-3) 88 | OP_COUNTER = const(0x24) 89 | OP_INFO = const(0x30) 90 | OP_NONCE = const(0x16) 91 | OP_RANDOM = const(0x1B) 92 | OP_SHA = const(0x47) 93 | OP_LOCK = const(0x17) 94 | OP_GEN_KEY = const(0x40) 95 | OP_SIGN = const(0x41) 96 | OP_WRITE = const(0x12) 97 | OP_ECDH = const(0x43) 98 | 99 | # Maximum execution times, in milliseconds (9-4) 100 | EXEC_TIME = { 101 | OP_COUNTER: const(20), 102 | OP_INFO: const(1), 103 | OP_NONCE: const(7), 104 | OP_RANDOM: const(23), 105 | OP_SHA: const(47), 106 | OP_LOCK: const(32), 107 | OP_GEN_KEY: const(115), 108 | OP_SIGN: const(70), 109 | OP_WRITE: const(26), 110 | OP_ECDH: const(80), 111 | } 112 | 113 | """ 114 | Configuration Zone Bytes 115 | 116 | Serial Number (Bytes 0-3 and 8-12), Revision Number (Bytes 4-7) 117 | AES Enable (Byte 13), I2C Enable (Byte 14), Reserved (Byte 15) 118 | I2C Address (Byte 16), Reserved (Byte 17); Count Match (Byte 18) 119 | Chip Mode (Byte 19), Slot Config (Bytes 20-51) 120 | Counter 0 (Bytes 52-59), Counter 1 (Bytes 60-67) 121 | Use Lock (Byte 68), Volatile Key Permission (Byte 69) 122 | Secure Boot (Bytes 70-71), KDF (Bytes 72-74) 123 | Reserved (Bytes 75-83), User Extra (Bytes 84-85) 124 | Lock Config (Bytes 86-89), Chip Options (Bytes 90-91) 125 | X509 (Bytes 92-95), Key Config (Bytes 96-127) 126 | 127 | I2C Config 128 | 129 | +------+-------+---------+-------------+---------------------------------------------------------------+ 130 | | HEX | DEC | BIN | Description | 131 | +======+=======+=========+=============+===============================================================+ 132 | | Byte 14: C0 | 192 | 1100 0000 | | 133 | | | | ^xxx xxxx | Bit 0 (MSB): 0:Single Wire, 1:I2C; Bit 1-7: Set by Microchip | 134 | +--------------+---------+-------------+---------------------------------------------------------------+ 135 | | Byte 16: C0 | 192 | 1100 0000 | Default 7 bit I2C Address: 0xC0>>1: 0x60 ATECC608A-MAHDA | 136 | +--------------+---------+-------------+---------------------------------------------------------------+ 137 | | Byte 16: 6A | 106 | 0110 1010 | Default 7 bit I2C Address: 0x6A>>1: 0x35 ATECC608A-TNGTLS | 138 | +--------------+---------+-------------+---------------------------------------------------------------+ 139 | | Byte 16: 20 | 32 | 0010 0000 | Default 7 bit I2C Address: 0x20>>1: 0x10 ATECC608A-UNKNOWN | 140 | +--------------+---------+-------------+---------------------------------------------------------------+ 141 | 142 | """ 143 | 144 | CFG_TLS = bytes( 145 | bytearray( 146 | unhexlify( 147 | ( 148 | "01 23 00 00 00 00 50 00 00 00 00 00 00 c0 71 00" 149 | "20 20 20 20 20 20 20 20 20 20 20 20 20 c0 00 55" 150 | "00 83 20 87 20 87 20 87 2f 87 2f 8f 8f 9f 8f af" 151 | "20 20 20 20 20 20 20 20 20 20 20 20 20 8f 00 00" 152 | "00 00 00 00 00 00 00 00 00 00 00 00 20 20 20 20" 153 | "20 20 20 20 20 20 20 20 20 af 8f ff ff ff ff 00" 154 | "00 00 00 ff ff ff ff 00 20 20 20 20 20 20 20 20" 155 | "20 20 20 20 20 00 00 00 ff ff ff ff ff ff ff ff" 156 | "ff ff ff ff 20 20 20 20 20 20 20 20 20 20 20 20" 157 | "20 ff ff ff ff 00 00 55 55 ff ff 00 00 00 00 00" 158 | "00 33 20 20 20 20 20 20 20 20 20 20 20 20 20 00" 159 | "33 00 33 00 33 00 33 00 1c 00 1c 00 1c 00 3c 00" 160 | "3c 00 3c 00 3c 20 20 20 20 20 20 20 20 20 20 20" 161 | "20 20 00 3c 00 3c 00 3c 00 1c 00" 162 | ).replace(" ", "") 163 | ) 164 | ) 165 | ) 166 | 167 | # Convert I2C address to config byte 16 and update CFG_TLS 168 | _CFG_BYTES_LIST = list(bytearray(CFG_TLS)) 169 | _CFG_BYTE_16 = bytes(bytearray(unhexlify(hex(_I2C_ADDR << 1).replace("0x", "")))) 170 | _CFG_BYTES_LIST_MOD = _CFG_BYTES_LIST[0:16] + list(_CFG_BYTE_16) + _CFG_BYTES_LIST[17:] 171 | CFG_TLS = bytes(_CFG_BYTES_LIST_MOD) 172 | 173 | 174 | class ATECC: 175 | """ 176 | CircuitPython interface for ATECCx08A Crypto Co-Processor Devices. 177 | """ 178 | 179 | def __init__(self, i2c_bus: I2C, address: int = _REG_ATECC_DEVICE_ADDR, debug: bool = False): 180 | """ 181 | Initializes an ATECC device. 182 | 183 | :param busio i2c_bus: I2C Bus object. 184 | :param int address: Device address, defaults to _ATECC_DEVICE_ADDR. 185 | :param bool debug: Library debugging enabled 186 | """ 187 | self._debug = debug 188 | self._i2cbuf = bytearray(12) 189 | # don't probe, the device will NACK until woken up 190 | self._wake_device = I2CDevice(i2c_bus, 0x00, probe=False) 191 | self._i2c_device = I2CDevice(i2c_bus, address, probe=False) 192 | if (self.version() >> 8) not in {_ATECC_508_VER, _ATECC_608_VER}: 193 | raise RuntimeError("Failed to find 608 or 508 chip. Please check your wiring.") 194 | 195 | def wakeup(self): 196 | """Wakes up THE ATECC608A from sleep or idle modes.""" 197 | # This is a hack to generate the ATECC Wake condition, which is SDA 198 | # held low for t > 60us (twlo). For an I2C clock freq of 100kHz, 8 199 | # clock cycles will be 80us. This signal is generated by trying to 200 | # address something at 0x00. It will fail, but the pattern should 201 | # wake up the ATECC. 202 | try: 203 | with self._wake_device as i2c: 204 | i2c.write(bytes([0x00])) 205 | except Exception: 206 | pass 207 | time.sleep(0.001) 208 | 209 | def idle(self): 210 | """Puts the chip into idle mode 211 | until wakeup is called. 212 | """ 213 | self._i2cbuf[0] = 0x2 214 | with self._i2c_device as i2c: 215 | i2c.write(self._i2cbuf, end=1) 216 | time.sleep(0.001) 217 | 218 | def sleep(self): 219 | """Puts the chip into low-power 220 | sleep mode until wakeup is called. 221 | """ 222 | self._i2cbuf[0] = 0x1 223 | with self._i2c_device as i2c: 224 | i2c.write(self._i2cbuf, end=1) 225 | time.sleep(0.001) 226 | 227 | @property 228 | def locked(self): 229 | """Returns if the ATECC is locked.""" 230 | config = bytearray(4) 231 | self._read(0x00, 0x15, config) 232 | time.sleep(0.001) 233 | return config[2] == 0x0 and config[3] == 0x00 234 | 235 | @property 236 | def serial_number(self): 237 | """Returns the ATECC serial number.""" 238 | serial_num = bytearray(9) 239 | # 4-byte reads only 240 | temp_sn = bytearray(4) 241 | # SN<0:3> 242 | self._read(0, 0x00, temp_sn) 243 | serial_num[0:4] = temp_sn 244 | time.sleep(0.001) 245 | # SN<4:8> 246 | self._read(0, 0x02, temp_sn) 247 | serial_num[4:8] = temp_sn 248 | time.sleep(0.001) 249 | # Append Rev 250 | self._read(0, 0x03, temp_sn) 251 | serial_num[8] = temp_sn[0] 252 | time.sleep(0.001) 253 | # neaten up the serial for printing 254 | serial_num = str(hexlify(serial_num), "utf-8") 255 | serial_num = serial_num.upper() 256 | return serial_num 257 | 258 | def version(self): 259 | """Returns the ATECC608As revision number""" 260 | self.wakeup() 261 | self.idle() 262 | vers = bytearray(4) 263 | vers = self.info(0x00) 264 | return (vers[2] << 8) | vers[3] 265 | 266 | def lock_all_zones(self): 267 | """Locks Config, Data and OTP Zones.""" 268 | self.lock(0) 269 | self.lock(1) 270 | 271 | def lock(self, zone: int): 272 | """Locks specific ATECC zones. 273 | :param int zone: ATECC zone to lock. 274 | """ 275 | self.wakeup() 276 | self._send_command(0x17, 0x80 | zone, 0x0000) 277 | time.sleep(EXEC_TIME[OP_LOCK] / 1000) 278 | res = bytearray(1) 279 | self._get_response(res) 280 | assert res[0] == 0x00, "Failed locking ATECC!" 281 | self.idle() 282 | 283 | def info(self, mode: int, param: Optional[Any] = None) -> bytearray: 284 | """ 285 | Returns device state information 286 | 287 | :param int mode: Mode encoding, see Table 9-26. 288 | :param param: Optional parameter 289 | :return: bytearray containing the response 290 | """ 291 | self.wakeup() 292 | if not param: 293 | self._send_command(OP_INFO, mode) 294 | else: 295 | self._send_command(OP_INFO, mode, param) 296 | time.sleep(EXEC_TIME[OP_INFO] / 1000) 297 | info_out = bytearray(4) 298 | self._get_response(info_out) 299 | self.idle() 300 | return info_out 301 | 302 | def nonce(self, data: bytearray, mode: int = 0, zero: int = 0x0000) -> bytearray: 303 | """ 304 | Generates a nonce by combining internally generated random number 305 | with an input value. 306 | 307 | :param bytearray data: Input value from system or external. 308 | :param int mode: Controls the internal RNG and seed mechanism. 309 | :param int zero: Param2, see Table 9-35. 310 | :return: bytearray containing the calculated nonce 311 | """ 312 | self.wakeup() 313 | if mode in {0x00, 0x01}: 314 | if zero == 0x00: 315 | assert len(data) == 20, "Data value must be 20 bytes long." 316 | self._send_command(OP_NONCE, mode, zero, data) 317 | # nonce returns 32 bytes 318 | calculated_nonce = bytearray(32) 319 | elif mode == 0x03: 320 | # Operating in Nonce pass-through mode 321 | assert len(data) == 32, "Data value must be 32 bytes long." 322 | self._send_command(OP_NONCE, mode, zero, data) 323 | # nonce returns 1 byte 324 | calculated_nonce = bytearray(1) 325 | else: 326 | raise RuntimeError("Invalid mode specified!") 327 | time.sleep(EXEC_TIME[OP_NONCE] / 1000) 328 | self._get_response(calculated_nonce) 329 | time.sleep(1 / 1000) 330 | if mode == 0x03: 331 | assert calculated_nonce[0] == 0x00, "Incorrectly calculated nonce in pass-thru mode" 332 | self.idle() 333 | return calculated_nonce 334 | 335 | def counter(self, counter: int = 0, increment_counter: bool = True) -> bytearray: 336 | """ 337 | Reads the binary count value from one of the two monotonic 338 | counters located on the device within the configuration zone. 339 | The maximum value that the counter may have is 2,097,151. 340 | 341 | :param int counter: Device's counter to increment. 342 | :param bool increment_counter: Increments the value of the counter specified. 343 | :return: bytearray with the count 344 | """ 345 | counter = 0x00 346 | self.wakeup() 347 | if counter == 1: 348 | counter = 0x01 349 | if increment_counter: 350 | self._send_command(OP_COUNTER, 0x01, counter) 351 | else: 352 | self._send_command(OP_COUNTER, 0x00, counter) 353 | time.sleep(EXEC_TIME[OP_COUNTER] / 1000) 354 | count = bytearray(4) 355 | self._get_response(count) 356 | self.idle() 357 | return count 358 | 359 | def random(self, rnd_min: int = 0, rnd_max: int = 0) -> int: 360 | """ 361 | Generates a random number for use by the system. 362 | 363 | :param int rnd_min: Minimum Random value to generate. 364 | :param int rnd_max: Maximum random value to generate. 365 | :return: Random integer 366 | """ 367 | if rnd_max: 368 | rnd_min = 0 369 | if rnd_min >= rnd_max: 370 | return rnd_min 371 | delta = rnd_max - rnd_min 372 | r = bytearray(16) 373 | r = self._random(r) 374 | data = 0 375 | for i in enumerate(r): 376 | data += r[i[0]] 377 | if data < 0: 378 | data = -data 379 | data = data % delta 380 | return data + rnd_min 381 | 382 | def _random(self, data: bytearray) -> bytearray: 383 | """ 384 | Initializes the random number generator and returns. 385 | 386 | :param bytearray data: Response buffer. 387 | :return: bytearray 388 | """ 389 | self.wakeup() 390 | data_len = len(data) 391 | while data_len: 392 | self._send_command(OP_RANDOM, 0x00, 0x0000) 393 | time.sleep(EXEC_TIME[OP_RANDOM] / 1000) 394 | resp = bytearray(32) 395 | self._get_response(resp) 396 | copy_len = min(32, data_len) 397 | data = resp[0:copy_len] 398 | data_len -= copy_len 399 | self.idle() 400 | return data 401 | 402 | # SHA-256 Commands 403 | def sha_start(self) -> bytearray: 404 | """ 405 | Initializes the SHA-256 calculation engine 406 | and the SHA context in memory. 407 | This method MUST be called before sha_update or sha_digest 408 | """ 409 | self.wakeup() 410 | self._send_command(OP_SHA, 0x00) 411 | time.sleep(EXEC_TIME[OP_SHA] / 1000) 412 | status = bytearray(1) 413 | self._get_response(status) 414 | assert status[0] == 0x00, "Error during sha_start." 415 | self.idle() 416 | return status 417 | 418 | def sha_update(self, message: bytes) -> bytearray: 419 | """ 420 | Appends bytes to the message. Can be repeatedly called. 421 | 422 | :param bytes message: Up to 64 bytes of data to be included 423 | into the hash operation. 424 | :return: bytearray containing the status 425 | """ 426 | self.wakeup() 427 | self._send_command(OP_SHA, 0x01, 64, message) 428 | time.sleep(EXEC_TIME[OP_SHA] / 1000) 429 | status = bytearray(1) 430 | self._get_response(status) 431 | assert status[0] == 0x00, "Error during SHA Update" 432 | self.idle() 433 | return status 434 | 435 | def sha_digest(self, message: bytearray = None) -> bytearray: 436 | """ 437 | Returns the digest of the data passed to the 438 | sha_update method so far. 439 | 440 | :param bytearray message: Up to 64 bytes of data to be included 441 | into the hash operation. 442 | :return: bytearray containing the digest 443 | """ 444 | if not hasattr(message, "append") and message is not None: 445 | message = pack("B", message) 446 | self.wakeup() 447 | # Include optional message 448 | if message: 449 | self._send_command(OP_SHA, 0x02, len(message), message) 450 | else: 451 | self._send_command(OP_SHA, 0x02) 452 | time.sleep(EXEC_TIME[OP_SHA] / 1000) 453 | digest = bytearray(32) 454 | self._get_response(digest) 455 | assert len(digest) == 32, "SHA response length does not match expected length." 456 | self.idle() 457 | return digest 458 | 459 | def ecdh(self, slot_num: int, public_key: bytearray, mode: int = 0x0C) -> bytearray: 460 | """ 461 | Performs ECDH key agreement operation. 462 | :param int slot_num: ECC slot (0-4) containing private key. 463 | :param bytearray public_key: 64-byte public key (X||Y). 464 | :param int mode: Mode parameter, defaults to 0x0C. 465 | :return: bytearray containing the shared secret 466 | """ 467 | 468 | assert len(public_key) == 64, "Public key must be 64 bytes (X||Y)" 469 | 470 | self.wakeup() 471 | # Send ECDH command (opcode 0x43) 472 | self._send_command(OP_ECDH, mode, slot_num, public_key) 473 | time.sleep(EXEC_TIME[OP_ECDH] / 1000) 474 | 475 | response = bytearray(32) # shared secret 476 | self._get_response(response) 477 | self.idle() 478 | return response 479 | 480 | def gen_key(self, key: bytearray, slot_num: int, private_key: bool = False) -> bytearray: 481 | """ 482 | Generates a private or public key. 483 | 484 | :param key: Buffer to put the key into 485 | :param int slot_num: ECC slot (from 0 to 4). 486 | :param bool private_key: Generates a private key if true. 487 | :return: The requested key 488 | """ 489 | assert 0 <= slot_num <= 4, "Provided slot must be between 0 and 4." 490 | self.wakeup() 491 | if private_key: 492 | self._send_command(OP_GEN_KEY, 0x04, slot_num) 493 | else: 494 | self._send_command(OP_GEN_KEY, 0x00, slot_num) 495 | time.sleep(EXEC_TIME[OP_GEN_KEY] / 1000) 496 | self._get_response(key) 497 | time.sleep(0.001) 498 | self.idle() 499 | return key 500 | 501 | def ecdsa_sign(self, slot: int, message: bytearray) -> bytearray: 502 | """ 503 | Generates and returns a signature using the ECDSA algorithm. 504 | 505 | :param int slot: Which ECC slot to use. 506 | :param bytearray message: Message to be signed. 507 | :return: bytearray containing the signature 508 | """ 509 | # Load the message digest into TempKey using Nonce (9.1.8) 510 | self.nonce(message, 0x03) 511 | # Generate and return a signature 512 | sig = bytearray(64) 513 | sig = self.sign(slot) 514 | return sig 515 | 516 | def sign(self, slot_id: int) -> bytearray: 517 | """ 518 | Performs ECDSA signature calculation with key in provided slot. 519 | 520 | :param int slot_id: ECC slot containing key for use with signature. 521 | :return: bytearray containing the signature 522 | """ 523 | self.wakeup() 524 | self._send_command(0x41, 0x80, slot_id) 525 | time.sleep(EXEC_TIME[OP_SIGN] / 1000) 526 | signature = bytearray(64) 527 | self._get_response(signature) 528 | self.idle() 529 | return signature 530 | 531 | def write_config(self, data: bytearray): 532 | """ 533 | Writes configuration data to the device's EEPROM. 534 | 535 | :param bytearray data: Configuration data to-write 536 | """ 537 | # First 16 bytes of data are skipped, not writable 538 | for i in range(16, 128, 4): 539 | if i == 84: 540 | # can't write 541 | continue 542 | self._write(0, i // 4, data[i : i + 4]) 543 | 544 | def _write(self, zone: Any, address: int, buffer: bytearray): 545 | """ 546 | Writes to the I2C 547 | 548 | :param Any zone: Zone to send to 549 | :param int address: The address to send to 550 | :param bytearray buffer: The buffer to send 551 | """ 552 | self.wakeup() 553 | if len(buffer) not in {4, 32}: 554 | raise RuntimeError("Only 4 or 32-byte writes supported.") 555 | if len(buffer) == 32: 556 | zone |= 0x80 557 | self._send_command(0x12, zone, address, buffer) 558 | time.sleep(26 / 1000) 559 | status = bytearray(1) 560 | self._get_response(status) 561 | self.idle() 562 | 563 | def _read(self, zone: int, address: int, buffer: bytearray): 564 | """ 565 | Reads from the I2C 566 | 567 | :param int zone: Zone to read from 568 | :param int address: The address to read from 569 | :param bytearray buffer: The buffer to read to 570 | """ 571 | self.wakeup() 572 | if len(buffer) not in {4, 32}: 573 | raise RuntimeError("Only 4 and 32 byte reads supported") 574 | if len(buffer) == 32: 575 | zone |= 0x80 576 | self._send_command(2, zone, address) 577 | time.sleep(0.005) 578 | self._get_response(buffer) 579 | time.sleep(0.001) 580 | self.idle() 581 | 582 | def _send_command(self, opcode: int, param_1: int, param_2: int = 0x00, data: Sized = ""): 583 | """ 584 | Sends a security command packet over i2c. 585 | 586 | :param byte opcode: The command Opcode 587 | :param byte param_1: The first parameter 588 | :param byte param_2: The second parameter, can be two bytes. 589 | :param byte param_3 data: Optional remaining input data. 590 | """ 591 | # assembling command packet 592 | command_packet = bytearray(8 + len(data)) 593 | # word address 594 | command_packet[0] = 0x03 595 | # i/o group: count 596 | command_packet[1] = len(command_packet) - 1 # count 597 | # security command packets 598 | command_packet[2] = opcode 599 | command_packet[3] = param_1 600 | command_packet[4] = param_2 & 0xFF 601 | command_packet[5] = param_2 >> 8 602 | for i, cmd in enumerate(data): 603 | command_packet[6 + i] = cmd 604 | if self._debug: 605 | print("Command Packet Sz: ", len(command_packet)) 606 | print("\tSending:", [hex(i) for i in command_packet]) 607 | # Checksum, CRC16 verification 608 | crc = self._at_crc(command_packet[1:-2]) 609 | command_packet[-1] = crc >> 8 610 | command_packet[-2] = crc & 0xFF 611 | 612 | self.wakeup() 613 | with self._i2c_device as i2c: 614 | i2c.write(command_packet) 615 | # small sleep 616 | time.sleep(0.001) 617 | 618 | def _get_response(self, buf: Sized, length: int = None, retries: int = 20) -> int: 619 | self.wakeup() 620 | if length is None: 621 | length = len(buf) 622 | response = bytearray(length + 3) # 1 byte header, 2 bytes CRC, len bytes data 623 | with self._i2c_device as i2c: 624 | for _ in range(retries): 625 | try: 626 | i2c.readinto(response) 627 | break 628 | except OSError: 629 | pass 630 | else: 631 | raise RuntimeError("Failed to read data from chip") 632 | if self._debug: 633 | print("\tReceived: ", [hex(i) for i in response]) 634 | crc = response[-2] | (response[-1] << 8) 635 | crc2 = self._at_crc(response[0:-2]) 636 | if crc != crc2: 637 | raise RuntimeError("CRC Mismatch") 638 | for i in range(length): 639 | buf[i] = response[i + 1] 640 | return response[1] 641 | 642 | @staticmethod 643 | def _at_crc(data: Sized, length: int = None) -> int: 644 | if length is None: 645 | length = len(data) 646 | if not data or not length: 647 | return 0 648 | polynom = 0x8005 649 | crc = 0x0 650 | for b in data: 651 | for shift in range(8): 652 | data_bit = 0 653 | if b & (1 << shift): 654 | data_bit = 1 655 | crc_bit = (crc >> 15) & 0x1 656 | crc <<= 1 657 | crc &= 0xFFFF 658 | if data_bit != crc_bit: 659 | crc ^= polynom 660 | crc &= 0xFFFF 661 | return crc & 0xFFFF 662 | --------------------------------------------------------------------------------