pax_global_header00006660000000000000000000000064143324300550014511gustar00rootroot0000000000000052 comment=1d29aa4a33b8db5e3337163e3c311175d4ade985 python-xeddsa-1.0.2/000077500000000000000000000000001433243005500143005ustar00rootroot00000000000000python-xeddsa-1.0.2/.flake8000066400000000000000000000001661433243005500154560ustar00rootroot00000000000000[flake8] max-line-length = 110 doctests = True ignore = E201,E202,W503 per-file-ignores = xeddsa/project.py:E203 python-xeddsa-1.0.2/.github/000077500000000000000000000000001433243005500156405ustar00rootroot00000000000000python-xeddsa-1.0.2/.github/workflows/000077500000000000000000000000001433243005500176755ustar00rootroot00000000000000python-xeddsa-1.0.2/.github/workflows/test-and-publish.yml000066400000000000000000000136461433243005500236150ustar00rootroot00000000000000name: Test & Publish on: [push, pull_request] permissions: contents: read jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "pypy-3.9"] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install libsodium and libxeddsa on ubuntu-latest run: | sudo apt-get install -y libsodium-dev sudo curl -L -o /usr/local/lib/libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-linux-amd64.a if: matrix.os == 'ubuntu-latest' - name: Install libxeddsa on macos-latest run: | curl -L -o /usr/local/lib/libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-macos-amd64.a if: matrix.os == 'macos-latest' - name: Download libsodium and libxeddsa on windows-latest shell: bash run: | curl -L -o libsodium-1.0.18-stable-msvc.zip https://download.libsodium.org/libsodium/releases/libsodium-1.0.18-stable-msvc.zip unzip libsodium-1.0.18-stable-msvc.zip mv libsodium/x64/Release/v141/static/libsodium.lib . curl -L -o libxeddsa.lib https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-windows-amd64.lib if: matrix.os == 'windows-latest' - name: Install/update package management dependencies run: python -m pip install --upgrade pip setuptools wheel - name: Build and install python-xeddsa run: pip install . - name: Install test dependencies run: pip install --upgrade pytest pytest-cov mypy pylint flake8 - name: Type-check using mypy shell: bash run: MYPYPATH=stubs/ mypy --strict xeddsa/ setup.py libxeddsa/ tests/ - name: Lint using pylint run: pylint xeddsa/ setup.py libxeddsa/ tests/ - name: Format-check using Flake8 run: flake8 xeddsa/ setup.py libxeddsa/ tests/ - name: Test using pytest run: pytest --cov=xeddsa --cov-report term-missing:skip-covered build_sdist: name: Build source distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install libsodium and libxeddsa run: | sudo apt-get install -y libsodium-dev sudo curl -L -o /usr/local/lib/libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-linux-amd64.a - name: Build source distribution run: python3 setup.py sdist - uses: actions/upload-artifact@v3 with: path: dist/*.tar.gz build_wheels_linux: name: Build wheels for Linux runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Download libxeddsa run: curl -L -o libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-linux-amd64.a - name: Build wheels using cibuildwheel uses: pypa/cibuildwheel@v2.11.2 env: CIBW_ARCHS_LINUX: auto64 CIBW_SKIP: "*-musllinux_*" CIBW_BEFORE_ALL_LINUX: yum install -y libsodium-devel && cp libxeddsa.a /usr/local/lib/ - uses: actions/upload-artifact@v3 with: path: ./wheelhouse/*.whl build_wheels_macos: name: Build wheels for MacOS ${{ matrix.arch }} runs-on: macos-latest strategy: fail-fast: false matrix: arch: [amd64, arm64] steps: - uses: actions/checkout@v3 - name: Install ${{ matrix.arch }} version of libxeddsa run: curl -L -o /usr/local/lib/libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-macos-${{ matrix.arch }}.a - name: Install arm64 version of libsodium run: | brew uninstall --ignore-dependencies libsodium brew fetch --force --bottle-tag=arm64_ventura libsodium | tee brew_output downloaded_to=$(grep "Downloaded to" brew_output) downloaded_to_split=($downloaded_to) brew install ${downloaded_to_split[2]} if: matrix.arch == 'arm64' - name: Build amd64 wheels using cibuildwheel uses: pypa/cibuildwheel@v2.11.2 env: CIBW_ARCHS_MACOS: x86_64 if: matrix.arch == 'amd64' - name: Build arm64 wheels using cibuildwheel uses: pypa/cibuildwheel@v2.11.2 env: CIBW_ARCHS_MACOS: arm64 if: matrix.arch == 'arm64' - uses: actions/upload-artifact@v3 with: path: ./wheelhouse/*.whl build_wheels_windows: name: Build wheels for Windows runs-on: windows-latest steps: - uses: actions/checkout@v3 - name: Download libsodium and libxeddsa shell: bash run: | curl -L -o libsodium-1.0.18-stable-msvc.zip https://download.libsodium.org/libsodium/releases/libsodium-1.0.18-stable-msvc.zip unzip libsodium-1.0.18-stable-msvc.zip mv libsodium/x64/Release/v141/static/libsodium.lib . curl -L -o libxeddsa.lib https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-windows-amd64.lib - name: Build wheels using cibuildwheel uses: pypa/cibuildwheel@v2.11.2 env: CIBW_ARCHS_WINDOWS: auto64 - uses: actions/upload-artifact@v3 with: path: ./wheelhouse/*.whl publish: needs: [test, build_sdist, build_wheels_linux, build_wheels_macos, build_wheels_windows] runs-on: ubuntu-latest if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/download-artifact@v3 with: name: artifact path: dist - uses: pypa/gh-action-pypi-publish@v1.5.1 with: user: __token__ password: ${{ secrets.pypi_token }} python-xeddsa-1.0.2/.gitignore000066400000000000000000000001711433243005500162670ustar00rootroot00000000000000dist/ XEdDSA.egg-info/ __pycache__/ .pytest_cache/ .mypy_cache/ .coverage build/ docs/_build xeddsa/xeddsa.brython.js python-xeddsa-1.0.2/.readthedocs.yaml000066400000000000000000000006251433243005500175320ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3" apt_packages: - libsodium-dev jobs: post_system_dependencies: - curl -L -o libxeddsa.a https://github.com/Syndace/libxeddsa/releases/download/v2.0.0/libxeddsa-linux-amd64.a sphinx: configuration: docs/conf.py fail_on_warning: true python: install: - requirements: docs/requirements.txt - method: pip path: . python-xeddsa-1.0.2/.vscode/000077500000000000000000000000001433243005500156415ustar00rootroot00000000000000python-xeddsa-1.0.2/.vscode/settings.json000066400000000000000000000000771433243005500204000ustar00rootroot00000000000000{ "python.analysis.extraPaths": [ "./stubs" ] }python-xeddsa-1.0.2/CHANGELOG.md000066400000000000000000000017271433243005500161200ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.2] - 8th of November 2022 ### Changed - Exclude tests from the packages - Fixed a small type error that appeared with the newest version of mypy ## [1.0.1] - 3rd of November 2022 ### Added - Python 3.11 to the list of supported versions ## [1.0.0] - 1st of November 2022 ### Added - Provide bindings to libxeddsa (version 2.0.0+) ### Removed - Pre-stable (i.e. versions before 1.0.0) changelog omitted. [Unreleased]: https://github.com/Syndace/python-xeddsa/compare/v1.0.2...HEAD [1.0.2]: https://github.com/Syndace/python-xeddsa/compare/v1.0.1...v1.0.2 [1.0.1]: https://github.com/Syndace/python-xeddsa/compare/v1.0.0...v1.0.1 [1.0.0]: https://github.com/Syndace/python-xeddsa/releases/tag/v1.0.0 python-xeddsa-1.0.2/LICENSE000066400000000000000000000020711433243005500153050ustar00rootroot00000000000000The MIT License Copyright (c) 2022 Tim Henkes (Syndace) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-xeddsa-1.0.2/MANIFEST.in000066400000000000000000000000661433243005500160400ustar00rootroot00000000000000recursive-include libxeddsa * include xeddsa/py.typed python-xeddsa-1.0.2/README.md000066400000000000000000000061711433243005500155640ustar00rootroot00000000000000[![PyPI](https://img.shields.io/pypi/v/XEdDSA.svg)](https://pypi.org/project/XEdDSA/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/XEdDSA.svg)](https://pypi.org/project/XEdDSA/) [![Build Status](https://github.com/Syndace/python-xeddsa/actions/workflows/test-and-publish.yml/badge.svg)](https://github.com/Syndace/python-xeddsa/actions/workflows/test-and-publish.yml) [![Documentation Status](https://readthedocs.org/projects/python-xeddsa/badge/?version=latest)](https://python-xeddsa.readthedocs.io/) # python-xeddsa # Python bindings to [libxeddsa](https://github.com/Syndace/libxeddsa). ## Installation ## python-xeddsa depends on two system libraries, [libxeddsa](https://github.com/Syndace/libxeddsa)>=2,<3 and [libsodium](https://download.libsodium.org/doc/). Install the latest release using pip (`pip install XEdDSA`), from the wheels available in the artifacts of the [Test & Publish workflow](https://github.com/Syndace/python-xeddsa/actions/workflows/test-and-publish.yml), or manually from source by running `pip install .` in the cloned repository. The installation from source requires libxeddsa, libsodium and the Python development headers to be installed. ## Testing, Type Checks and Linting ## python-xeddsa uses [pytest](https://docs.pytest.org/en/latest/) as its testing framework, [mypy](http://mypy-lang.org/) for static type checks and both [pylint](https://pylint.pycqa.org/en/latest/) and [Flake8](https://flake8.pycqa.org/en/latest/) for linting. All tests/checks can be run locally with the following commands: ```sh $ pip install --upgrade pytest pytest-cov mypy pylint flake8 $ export MYPYPATH=stubs/ $ mypy --strict xeddsa/ setup.py libxeddsa/ tests/ $ pylint xeddsa/ setup.py libxeddsa/ tests/ $ flake8 xeddsa/ setup.py libxeddsa/ tests/ $ pytest --cov=xeddsa --cov-report term-missing:skip-covered ``` ## Usage with Brython ## python-xeddsa can be used in the browser with Brython, thanks to the Emscripten build of libxeddsa. Refer to `tests/test_brython.html` for the setup routine required to load the Emscripten build for usage with Brython. In summary, Brython's initialization is deferred until after the libxeddsa WebAssembly module and wrapper have been loaded. Other than that, python-xeddsa can be used as usual and handled with Brython like a pure Python package. The tests can be run with Brython by running the following commands from the root of this repository: ``` $ # You need brython-cli in the version fitting your local Python installation $ pip install brython==$YOUR_PYTHON_VERSION $ cd xeddsa/ $ # Older versions of brython-cli use `--make_package` instead of just `make_package` $ brython-cli --make_package xeddsa $ cd ../ $ python3 -m http.server 8080 $ xdg-open http://localhost:8080/tests/test_brython.html ``` You'll find the output in the browser's dev console. ## Documentation ## View the documentation on [readthedocs.io](https://python-xeddsa.readthedocs.io/) or build it locally, which requires the Python packages listed in `docs/requirements.txt`. With all dependencies installed, run `make html` in the `docs/` directory. You can find the generated documentation in `docs/_build/html/`. python-xeddsa-1.0.2/docs/000077500000000000000000000000001433243005500152305ustar00rootroot00000000000000python-xeddsa-1.0.2/docs/Makefile000066400000000000000000000011331433243005500166660ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = XEdDSA SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)python-xeddsa-1.0.2/docs/_static/000077500000000000000000000000001433243005500166565ustar00rootroot00000000000000python-xeddsa-1.0.2/docs/_static/.gitkeep000066400000000000000000000000001433243005500202750ustar00rootroot00000000000000python-xeddsa-1.0.2/docs/conf.py000066400000000000000000000064571433243005500165430ustar00rootroot00000000000000# Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a full list see # the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, add these # directories to sys.path here. If the directory is relative to the documentation root, # use os.path.abspath to make it absolute, like shown here. import os import sys this_file_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(this_file_path, "..", "xeddsa")) from version import __version__ as __version from project import project as __project # -- Project information ----------------------------------------------------------------- project = __project["name"] author = __project["author"] copyright = f"{__project['year']}, {__project['author']}" # The short X.Y version version = __version["short"] # The full version, including alpha/beta/rc tags release = __version["full"] # -- General configuration --------------------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions coming # with Sphinx (named "sphinx.ext.*") or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.napoleon", "sphinx_autodoc_typehints" ] # Add any paths that contain templates here, relative to this directory. templates_path = [ "_templates" ] # List of patterns, relative to source directory, that match files and directories to # ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [ "_build", "Thumbs.db", ".DS_Store" ] # -- Options for HTML output ------------------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for a list of # builtin themes. html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, relative to # this directory. They are copied after the builtin static files, so a file named # "default.css" will overwrite the builtin "default.css". html_static_path = [ "_static" ] # -- Autodoc Configuration --------------------------------------------------------------- # The following two options seem to be ignored... autodoc_typehints = "description" autodoc_type_aliases = { type_alias: f"{type_alias}" for type_alias in { "Priv", "Seed", "Curve25519Pub", "Ed25519Pub", "Ed25519Signature", "Nonce", "SharedSecret" } } def autodoc_skip_member_handler(app, what, name, obj, skip, options): # Skip private members, i.e. those that start with double underscores but do not end in underscores if name.startswith("__") and not name.endswith("_"): return True # Could be achieved using exclude-members, but this is more comfy if name in { "__module__", "__weakref__" }: return True # Skip __init__s without documentation. Those are just used for type hints. if name == "__init__" and obj.__doc__ is None: return True return None def setup(app): app.connect("autodoc-skip-member", autodoc_skip_member_handler) python-xeddsa-1.0.2/docs/index.rst000066400000000000000000000002321433243005500170660ustar00rootroot00000000000000python-xeddsa - Python bindings to libxeddsa. ============================================= .. toctree:: installation API Documentation python-xeddsa-1.0.2/docs/installation.rst000066400000000000000000000021071433243005500204630ustar00rootroot00000000000000Installation ============ python-xeddsa depends on two system libraries, `libxeddsa `__>=2,<3, and `libsodium `__. Install the latest release using pip (``pip install XEdDSA``), from the wheels available in the artifacts of the `Test & Publish workflow `_, or manually from source by running ``pip install .`` in the cloned repository. The installation from source requires libxeddsa, libsodium and the Python development headers to be installed. Usage with Brython ------------------ python-xeddsa can be used in the browser with Brython, thanks to the Emscripten build of libxeddsa. Refer to ``tests/test_brython.html`` for the setup routine required to load the Emscripten build for usage with Brython. In summary, Brython's initialization is deferred until after the libxeddsa WebAssembly module and wrapper have been loaded. Other than that, python-xeddsa can be used as usual and handled with Brython like a pure Python package. python-xeddsa-1.0.2/docs/make.bat000066400000000000000000000014521433243005500166370ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=XEdDSA if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd python-xeddsa-1.0.2/docs/requirements.txt000066400000000000000000000000611433243005500205110ustar00rootroot00000000000000sphinx sphinx-rtd-theme sphinx-autodoc-typehints python-xeddsa-1.0.2/docs/xeddsa.rst000066400000000000000000000024621433243005500172360ustar00rootroot00000000000000xeddsa.bindings =============== Formats ------- The library follows following standards for serialization formats: * Curve25519/Ed25519 private keys: 32 bytes scalar value. No specific format. Clamped before every use as per `RFC 7748, section 5 "The X25519 and X448 Functions" `_. * Curve25519/Ed25519 seeds: 32 bytes. No specific format. The private key is derived from the seed using SHA-512 as per `RFC 8032, section 3.2 "Keys" `_. * Curve25519 public keys: 32 bytes, the little-endian encoding of the u coordinate as per `RFC 7748, section 5 "The X25519 and X448 Functions" `_. * Ed25519 public keys: 32 bytes, the little-endian encoding of the y coordinate with the sign bit of the x coordinate stored in the most significant bit as per `RFC 8032, section 3.2 "Keys" `_. * Ed25519 signatures: 64 bytes, following the format defined in `RFC 8032, section 3.3 "Sign" `_. API --- .. automodule:: xeddsa.bindings :members: :special-members: :private-members: :undoc-members: :member-order: bysource :show-inheritance: python-xeddsa-1.0.2/libxeddsa/000077500000000000000000000000001433243005500162375ustar00rootroot00000000000000python-xeddsa-1.0.2/libxeddsa/build.py000066400000000000000000000007711433243005500177150ustar00rootroot00000000000000import os import platform import cffi # type: ignore[import] ffibuilder = cffi.FFI() libxeddsa_header = os.path.join(os.path.dirname(os.path.abspath(__file__)), "xeddsa.h") with open(libxeddsa_header, encoding="utf-8") as f: ffibuilder.cdef(f.read()) ffibuilder.set_source( "_libxeddsa", '#include "' + libxeddsa_header + '"', libraries=[ "libxeddsa", "libsodium" ] if platform.system() == "Windows" else [ "xeddsa", "sodium" ] ) if __name__ == "__main__": ffibuilder.compile() python-xeddsa-1.0.2/libxeddsa/xeddsa.h000066400000000000000000000017651433243005500176710ustar00rootroot00000000000000// #include // #include extern void ed25519_priv_sign(uint8_t*, const uint8_t*, const uint8_t*, const uint32_t, const uint8_t*); extern void ed25519_seed_sign(uint8_t*, const uint8_t*, const uint8_t*, const uint32_t); extern int ed25519_verify(const uint8_t*, const uint8_t*, const uint8_t*, const uint32_t); extern void curve25519_pub_to_ed25519_pub(uint8_t*, const uint8_t*, const bool); extern int ed25519_pub_to_curve25519_pub(uint8_t*, const uint8_t*); extern void priv_to_curve25519_pub(uint8_t*, const uint8_t*); extern void priv_to_ed25519_pub(uint8_t*, const uint8_t*); extern void seed_to_ed25519_pub(uint8_t*, const uint8_t*); extern void priv_force_sign(uint8_t*, const uint8_t*, const bool); extern void seed_to_priv(uint8_t*, const uint8_t*); extern int x25519(uint8_t*, const uint8_t*, const uint8_t*); extern int xeddsa_init(); extern const unsigned XEDDSA_VERSION_MAJOR; extern const unsigned XEDDSA_VERSION_MINOR; extern const unsigned XEDDSA_VERSION_REVISION; python-xeddsa-1.0.2/pylintrc000066400000000000000000000362611433243005500160770ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist=_libxeddsa # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=missing-module-docstring, duplicate-code, fixme, logging-fstring-interpolation # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=useless-suppression [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'error', 'warning', 'refactor', and 'convention' # which contain the number of messages in each category, as well as 'statement' # which is the total number of statements analyzed. This score is used by the # global evaluation report (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it work, # install the python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=no # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [LOGGING] # Format style used to check logging format string. `old` means using % # formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=110 # Maximum number of lines in a module. max-module-lines=10000 # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=yes [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=no # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=no # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # List of decorators that change the signature of a decorated function. signature-mutators= [STRING] # This flag controls whether the implicit-str-concat-in-sequence should # generate a warning on implicit string concatenation in sequences defined over # several lines. check-str-concat-over-line-jumps=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=UPPER_CASE # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=any # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, e, # exceptions in except blocks _ # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=yes # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, __post_init__, create # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=100 # Maximum number of attributes for a class (see R0902). max-attributes=100 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=10 # Maximum number of branch for function / method body. max-branches=100 # Maximum number of locals for function / method body. max-locals=100 # Maximum number of parents for a class (see R0901). max-parents=10 # Maximum number of public methods for a class (see R0904). max-public-methods=100 # Maximum number of return / yield for function / method body. max-returns=100 # Maximum number of statements in function / method body. max-statements=1000 # Minimum number of public methods for a class (see R0903). min-public-methods=0 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=BaseException, Exception python-xeddsa-1.0.2/pyproject.toml000066400000000000000000000001211433243005500172060ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" python-xeddsa-1.0.2/requirements.txt000066400000000000000000000000151433243005500175600ustar00rootroot00000000000000cffi>=1.14.5 python-xeddsa-1.0.2/setup.py000066400000000000000000000041001433243005500160050ustar00rootroot00000000000000# pylint: disable=exec-used import os from typing import Dict, Union, List from setuptools import setup, find_packages # type: ignore[import] source_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "xeddsa") version_scope: Dict[str, Dict[str, str]] = {} with open(os.path.join(source_root, "version.py"), encoding="utf-8") as f: exec(f.read(), version_scope) version = version_scope["__version__"] project_scope: Dict[str, Dict[str, Union[str, List[str]]]] = {} with open(os.path.join(source_root, "project.py"), encoding="utf-8") as f: exec(f.read(), project_scope) project = project_scope["project"] with open("README.md", encoding="utf-8") as f: long_description = f.read() classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] classifiers.extend(project["categories"]) if version["tag"] == "alpha": classifiers.append("Development Status :: 3 - Alpha") if version["tag"] == "beta": classifiers.append("Development Status :: 4 - Beta") if version["tag"] == "stable": classifiers.append("Development Status :: 5 - Production/Stable") del project["categories"] del project["year"] setup( version=version["short"], long_description=long_description, long_description_content_type="text/markdown", license="MIT", packages=find_packages(exclude=["tests"]), install_requires=[ "cffi>=1.14.5" ], setup_requires=[ "cffi>=1.14.5" ], cffi_modules=[ os.path.join("libxeddsa", "build.py") + ":ffibuilder" ], python_requires=">=3.7", include_package_data=True, zip_safe=False, classifiers=classifiers, **project ) python-xeddsa-1.0.2/stubs/000077500000000000000000000000001433243005500154405ustar00rootroot00000000000000python-xeddsa-1.0.2/stubs/_libxeddsa.pyi000066400000000000000000000027531433243005500202700ustar00rootroot00000000000000from typing import Optional class cdata: def __bytes__(self) -> bytes: ... class lib: @staticmethod def ed25519_priv_sign(sig: cdata, priv: cdata, msg: cdata, msg_size: int, nonce: cdata) -> None: ... @staticmethod def ed25519_seed_sign(sig: cdata, seed: cdata, msg: cdata, msg_size: int) -> None: ... @staticmethod def ed25519_verify(sig: cdata, ed25519_pub: cdata, msg: cdata, msg_size: int) -> int: ... @staticmethod def curve25519_pub_to_ed25519_pub(ed25519_pub: cdata, curve25519_pub: cdata, set_sign_bit: bool) -> None: ... @staticmethod def ed25519_pub_to_curve25519_pub(curve25519_pub: cdata, ed25519_pub: cdata) -> int: ... @staticmethod def priv_to_curve25519_pub(curve25519_pub: cdata, priv: cdata) -> None: ... @staticmethod def priv_to_ed25519_pub(ed25519_pub: cdata, priv: cdata) -> None: ... @staticmethod def seed_to_ed25519_pub(ed25519_pub: cdata, seed: cdata) -> None: ... @staticmethod def priv_force_sign(priv_out: cdata, priv_in: cdata, set_sign_bit: bool) -> None: ... @staticmethod def seed_to_priv(priv: cdata, seed: cdata) -> None: ... @staticmethod def x25519(shared_secret: cdata, priv: cdata, curve25519_pub: cdata) -> int: ... @staticmethod def xeddsa_init() -> int: ... XEDDSA_VERSION_MAJOR: int XEDDSA_VERSION_MINOR: int XEDDSA_VERSION_REVISION: int class ffi: @staticmethod def new(type_definition: str, data: Optional[bytes] = None) -> cdata: ... python-xeddsa-1.0.2/tests/000077500000000000000000000000001433243005500154425ustar00rootroot00000000000000python-xeddsa-1.0.2/tests/__init__.py000066400000000000000000000000401433243005500175450ustar00rootroot00000000000000# To make relative imports work python-xeddsa-1.0.2/tests/test_brython.html000066400000000000000000000034621433243005500210610ustar00rootroot00000000000000 python-xeddsa python-xeddsa-1.0.2/tests/test_conversion_uniqueness.py000066400000000000000000000032371433243005500235240ustar00rootroot00000000000000import secrets import xeddsa __all__ = [ # pylint: disable=unused-variable "test_conversion_uniqueness" ] NUM_KEYS = 8192 def test_conversion_uniqueness() -> None: """ Test conversion uniqueness between public key formats. """ # Test on a set of different keys for _ in range(NUM_KEYS): # Generate a Curve25519 key pair (the private key is not used). curve_priv = secrets.token_bytes(32) curve_pub_original = xeddsa.priv_to_curve25519_pub(curve_priv) # Convert the Curve25519 public key to an Ed25519 public key ed_pub_converted = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub_original, False) # Convert the Ed25519 public key back into a Curve25519 public key curve_pub_converted = xeddsa.ed25519_pub_to_curve25519_pub(ed_pub_converted) # Check whether the converted Curve25519 public key is equal to the original assert curve_pub_original == curve_pub_converted # Generate an Ed25519 key pair (the private key is not used). ed_priv = secrets.token_bytes(32) ed_pub_original = xeddsa.priv_to_ed25519_pub(ed_priv) # Convert the Ed25519 public key to a Curve25519 public key curve_pub_converted = xeddsa.ed25519_pub_to_curve25519_pub(ed_pub_original) # Convert the Curve25519 public key back into an Ed25519 public key. Set the sign accordingly. original_sign = bool(ed_pub_original[31] & 0x80) ed_pub_converted = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub_converted, original_sign) # Check whether the converted Ed25519 public key is equal to the original assert ed_pub_original == ed_pub_converted python-xeddsa-1.0.2/tests/test_signing.py000066400000000000000000000055001433243005500205110ustar00rootroot00000000000000import os import random import secrets import xeddsa __all__ = [ # pylint: disable=unused-variable "test_signing" ] NUM_MESSAGES = 8 NUM_KEY_PAIRS = 8 def test_signing() -> None: """ Test signing/verification flows for Curve25519, Ed25519 and seed-based key pairs. """ # Test on a set of different messages for _ in range(NUM_MESSAGES): # Fill the message with random bytes. Randomize the size of the message. msg = os.urandom(random.randrange(0, 65535)) # Test each message on a set of different key pairs for _ in range(NUM_KEY_PAIRS): # Generate a Curve25519 key pair. curve_priv = secrets.token_bytes(32) curve_pub = xeddsa.priv_to_curve25519_pub(curve_priv) # Adjust the private key such that the sign of the derived Ed25519 public key is zero priv = xeddsa.priv_force_sign(curve_priv, False) # Sign the message using the Curve25519 private key sig = xeddsa.ed25519_priv_sign(priv, msg) # Convert the Curve25519 public key to an Ed25519 public key ed_pub = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub, False) # Verify the message using the converted public key. assert xeddsa.ed25519_verify(sig, ed_pub, msg) # Convert the Curve25519 public key to an Ed25519 public key, intentionally choosing the wrong # sign ed_pub = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub, True) # Verify the message using the converted public key. assert not xeddsa.ed25519_verify(sig, ed_pub, msg) # Adjust the private key such that the sign of the derived Ed25519 public key is one priv = xeddsa.priv_force_sign(curve_priv, True) # Sign the message using the Curve25519 private key sig = xeddsa.ed25519_priv_sign(priv, msg) # Convert the Curve25519 public key to an Ed25519 public key ed_pub = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub, True) # Verify the message using the converted public key. assert xeddsa.ed25519_verify(sig, ed_pub, msg) # Convert the Curve25519 public key to an Ed25519 public key, intentionally choosing the wrong # sign ed_pub = xeddsa.curve25519_pub_to_ed25519_pub(curve_pub, False) # Verify the message using the converted public key. assert not xeddsa.ed25519_verify(sig, ed_pub, msg) # Generate an Ed25519 key pair. ed_seed = secrets.token_bytes(32) ed_pub = xeddsa.seed_to_ed25519_pub(ed_seed) # Sign the message normally sig = xeddsa.ed25519_seed_sign(ed_seed, msg) # Verify the message normally assert xeddsa.ed25519_verify(sig, ed_pub, msg) python-xeddsa-1.0.2/xeddsa/000077500000000000000000000000001433243005500155505ustar00rootroot00000000000000python-xeddsa-1.0.2/xeddsa/__init__.py000066400000000000000000000025771433243005500176740ustar00rootroot00000000000000from .version import __version__ from .project import project from .bindings import ( Priv, PRIV_SIZE, Seed, SEED_SIZE, Curve25519Pub, CURVE_25519_PUB_SIZE, Ed25519Pub, ED_25519_PUB_SIZE, Ed25519Signature, ED_25519_SIGNATURE_SIZE, Nonce, NONCE_SIZE, SharedSecret, SHARED_SECRET_SIZE, XEdDSAException, ed25519_priv_sign, ed25519_seed_sign, ed25519_verify, curve25519_pub_to_ed25519_pub, ed25519_pub_to_curve25519_pub, priv_to_curve25519_pub, priv_to_ed25519_pub, seed_to_ed25519_pub, priv_force_sign, seed_to_priv, x25519 ) # Fun: # https://github.com/PyCQA/pylint/issues/6006 # https://github.com/python/mypy/issues/10198 __all__ = [ # pylint: disable=unused-variable # .version "__version__", # .project "project", # .bindings "Priv", "PRIV_SIZE", "Seed", "SEED_SIZE", "Curve25519Pub", "CURVE_25519_PUB_SIZE", "Ed25519Pub", "ED_25519_PUB_SIZE", "Ed25519Signature", "ED_25519_SIGNATURE_SIZE", "Nonce", "NONCE_SIZE", "SharedSecret", "SHARED_SECRET_SIZE", "XEdDSAException", "ed25519_priv_sign", "ed25519_seed_sign", "ed25519_verify", "curve25519_pub_to_ed25519_pub", "ed25519_pub_to_curve25519_pub", "priv_to_curve25519_pub", "priv_to_ed25519_pub", "seed_to_ed25519_pub", "priv_force_sign", "seed_to_priv", "x25519" ] python-xeddsa-1.0.2/xeddsa/bindings.py000066400000000000000000000257751433243005500177370ustar00rootroot00000000000000# This import from future (theoretically) enables sphinx_autodoc_typehints to handle type aliases better from __future__ import annotations # pylint: disable=unused-variable import secrets from typing import Optional try: from _libxeddsa import ffi, lib except ImportError: from .libxeddsa_emscripten import ffi, lib # type: ignore[assignment] __all__ = [ # pylint: disable=unused-variable "Priv", "PRIV_SIZE", "Seed", "SEED_SIZE", "Curve25519Pub", "CURVE_25519_PUB_SIZE", "Ed25519Pub", "ED_25519_PUB_SIZE", "Ed25519Signature", "ED_25519_SIGNATURE_SIZE", "Nonce", "NONCE_SIZE", "SharedSecret", "SHARED_SECRET_SIZE", "XEdDSAException", "ed25519_priv_sign", "ed25519_seed_sign", "ed25519_verify", "curve25519_pub_to_ed25519_pub", "ed25519_pub_to_curve25519_pub", "priv_to_curve25519_pub", "priv_to_ed25519_pub", "seed_to_ed25519_pub", "priv_force_sign", "seed_to_priv", "x25519" ] Priv = bytes PRIV_SIZE = 32 PRIV_FFI = f"uint8_t[{PRIV_SIZE}]" Seed = bytes SEED_SIZE = 32 SEED_FFI = f"uint8_t[{SEED_SIZE}]" Curve25519Pub = bytes CURVE_25519_PUB_SIZE = 32 CURVE_25519_PUB_FFI = f"uint8_t[{CURVE_25519_PUB_SIZE}]" Ed25519Pub = bytes ED_25519_PUB_SIZE = 32 ED_25519_PUB_FFI = f"uint8_t[{ED_25519_PUB_SIZE}]" Ed25519Signature = bytes ED_25519_SIGNATURE_SIZE = 64 ED_25519_SIGNATURE_FFI = f"uint8_t[{ED_25519_SIGNATURE_SIZE}]" Nonce = bytes NONCE_SIZE = 64 NONCE_FFI = f"uint8_t[{NONCE_SIZE}]" SharedSecret = bytes SHARED_SECRET_SIZE = 32 SHARED_SECRET_FFI = f"uint8_t[{SHARED_SECRET_SIZE}]" class XEdDSAException(Exception): """ Exception raised in case of critical security errors. """ def ed25519_priv_sign(priv: Priv, msg: bytes, nonce: Optional[Nonce] = None) -> Ed25519Signature: """ Sign a message using a Curve25519/Ed25519 private key. Args: priv: The Curve25519/Ed25519 private key to sign with. msg: The message to sign. nonce: 64 bytes of secure random data. If `None` is passed, the nonce is generated for you. Returns: An Ed25519-compatible signature of `msg`. """ if len(priv) != PRIV_SIZE: raise ValueError(f"Expected size of the private key in bytes: {PRIV_SIZE} (PRIV_SIZE)") if nonce is None: nonce = secrets.token_bytes(NONCE_SIZE) if len(nonce) != NONCE_SIZE: raise ValueError(f"Expected size of the nonce in bytes: {NONCE_SIZE} (NONCE_SIZE") sig_ffi = ffi.new(ED_25519_SIGNATURE_FFI) priv_ffi = ffi.new(PRIV_FFI, priv) msg_ffi = ffi.new("uint8_t[]", msg) msg_size = len(msg) nonce_ffi = ffi.new(NONCE_FFI, nonce) lib.ed25519_priv_sign(sig_ffi, priv_ffi, msg_ffi, msg_size, nonce_ffi) return bytes(sig_ffi) def ed25519_seed_sign(seed: Seed, msg: bytes) -> Ed25519Signature: """ Sign a message using a Curve25519/Ed25519 seed. Args: seed: The Curve25519/Ed25519 seed to sign with. msg: The message to sign. Returns: An Ed25519-compatible signature of `msg`. """ if len(seed) != SEED_SIZE: raise ValueError(f"Expected size of the seed in bytes: {SEED_SIZE} (SEED_SIZE)") sig_ffi = ffi.new(ED_25519_SIGNATURE_FFI) seed_ffi = ffi.new(SEED_FFI, seed) msg_ffi = ffi.new("uint8_t[]", msg) msg_size = len(msg) lib.ed25519_seed_sign(sig_ffi, seed_ffi, msg_ffi, msg_size) return bytes(sig_ffi) def ed25519_verify(sig: Ed25519Signature, ed25519_pub: Ed25519Pub, msg: bytes) -> bool: """ Verify an Ed25519 signature. Args: sig: An Ed25519-compatible signature of `msg`. ed25519_pub: The Ed25519 public key to verify the signature with. msg: The message. Returns: Whether the signature verification was successful. """ if len(sig) != ED_25519_SIGNATURE_SIZE: raise ValueError( f"Expected size of the signature in bytes: {ED_25519_SIGNATURE_SIZE} (ED_25519_SIGNATURE_SIZE)" ) if len(ed25519_pub) != ED_25519_PUB_SIZE: raise ValueError( f"Expected size of the Ed25519 public key in bytes: {ED_25519_PUB_SIZE} (ED_25519_PUB_SIZE)" ) sig_ffi = ffi.new(ED_25519_SIGNATURE_FFI, sig) ed25519_pub_ffi = ffi.new(ED_25519_PUB_FFI, ed25519_pub) msg_ffi = ffi.new("uint8_t[]", msg) msg_size = len(msg) return lib.ed25519_verify(sig_ffi, ed25519_pub_ffi, msg_ffi, msg_size) == 0 def curve25519_pub_to_ed25519_pub(curve25519_pub: Curve25519Pub, set_sign_bit: bool) -> Ed25519Pub: """ Convert a Curve25519 public key into an Ed25519 public key. Args: curve25519_pub: The Curve25519 public key to convert into its Ed25519 equivalent. set_sign_bit: Whether to set the sign bit of the output Ed25519 public key. Returns: The Ed25519 public key corresponding to the Curve25519 public key. """ if len(curve25519_pub) != CURVE_25519_PUB_SIZE: raise ValueError( f"Expected size of the Curve25519 public key in bytes: {CURVE_25519_PUB_SIZE}" " (CURVE_25519_PUB_SIZE)" ) ed25519_pub_ffi = ffi.new(ED_25519_PUB_FFI) curve25519_pub_ffi = ffi.new(CURVE_25519_PUB_FFI, curve25519_pub) lib.curve25519_pub_to_ed25519_pub(ed25519_pub_ffi, curve25519_pub_ffi, set_sign_bit) return bytes(ed25519_pub_ffi) def ed25519_pub_to_curve25519_pub(ed25519_pub: Ed25519Pub) -> Curve25519Pub: """ Convert an Ed25519 public key into a Curve25519 public key. Re-export of libsodiums/ref10s `crypto_sign_ed25519_pk_to_curve25519` function for convenience. Args: ed25519_pub: The Ed25519 public key to convert into its Curve25519 equivalent. Returns: The Curve25519 public key corresponding to the Ed25519 public key. Raises: XEdDSAException: if the public key was rejected due to suboptimal security propierties. """ if len(ed25519_pub) != ED_25519_PUB_SIZE: raise ValueError( f"Expected size of the Ed25519 public key in bytes: {ED_25519_PUB_SIZE} (ED_25519_PUB_SIZE)" ) curve25519_pub_ffi = ffi.new(CURVE_25519_PUB_FFI) ed25519_pub_ffi = ffi.new(ED_25519_PUB_FFI, ed25519_pub) if lib.ed25519_pub_to_curve25519_pub(curve25519_pub_ffi, ed25519_pub_ffi) != 0: raise XEdDSAException("Ed25519 public key rejected due to suboptimal security properties.") return bytes(curve25519_pub_ffi) def priv_to_curve25519_pub(priv: Priv) -> Curve25519Pub: """ Derive the Curve25519 public key from a Curve25519/Ed25519 private key. Args: priv: The Curve25519/Ed25519 private key. Returns: The Curve25519 public key. """ if len(priv) != PRIV_SIZE: raise ValueError(f"Expected size of the private key in bytes: {PRIV_SIZE} (PRIV_SIZE)") curve25519_pub_ffi = ffi.new(CURVE_25519_PUB_FFI) priv_ffi = ffi.new(PRIV_FFI, priv) lib.priv_to_curve25519_pub(curve25519_pub_ffi, priv_ffi) return bytes(curve25519_pub_ffi) def priv_to_ed25519_pub(priv: Priv) -> Ed25519Pub: """ Derive the Ed25519 public key from a Curve25519/Ed25519 private key. Args: priv: The Curve25519/Ed25519 private key. Returns: The Ed25519 public key. """ if len(priv) != PRIV_SIZE: raise ValueError(f"Expected size of the private key in bytes: {PRIV_SIZE} (PRIV_SIZE)") ed25519_pub_ffi = ffi.new(ED_25519_PUB_FFI) priv_ffi = ffi.new(PRIV_FFI, priv) lib.priv_to_ed25519_pub(ed25519_pub_ffi, priv_ffi) return bytes(ed25519_pub_ffi) def seed_to_ed25519_pub(seed: Seed) -> Ed25519Pub: """ Derive the Ed25519 public key from a Curve25519/Ed25519 seed. Args: seed: The Curve25519/Ed25519 seed. Returns: The Ed25519 public key. """ if len(seed) != SEED_SIZE: raise ValueError(f"Expected size of the seed in bytes: {SEED_SIZE} (SEED_SIZE)") ed25519_pub_ffi = ffi.new(ED_25519_PUB_FFI) seed_ffi = ffi.new(SEED_FFI, seed) lib.seed_to_ed25519_pub(ed25519_pub_ffi, seed_ffi) return bytes(ed25519_pub_ffi) def priv_force_sign(priv: Priv, set_sign_bit: bool) -> Priv: """ Negate a Curve25519/Ed25519 private key if necessary, such that the corresponding Ed25519 public key has the sign bit set (or not set) as requested. Args: priv: The original Curve25519/Ed25519 private key. set_sign_bit: Whether the goal is for the sign bit to be set on the Ed25519 public key corresponding to the adjusted Curve25519/Ed25519 private key. Returns: The adjusted Curve25519/Ed25519 private key. """ if len(priv) != PRIV_SIZE: raise ValueError(f"Expected size of the private key in bytes: {PRIV_SIZE} (PRIV_SIZE)") priv_out_ffi = ffi.new(PRIV_FFI) priv_in_ffi = ffi.new(PRIV_FFI, priv) lib.priv_force_sign(priv_out_ffi, priv_in_ffi, set_sign_bit) return bytes(priv_out_ffi) def seed_to_priv(seed: Seed) -> Priv: """ Derive the Curve25519/Ed25519 private key from a Curve25519/Ed25519 seed. Re-export of libsodiums/ref10s `crypto_sign_ed25519_sk_to_curve25519` function for convenience. Args: seed: The Curve25519/Ed25519 seed. Returns: The Curve25519/Ed25519 private key derived from the seed. """ if len(seed) != SEED_SIZE: raise ValueError(f"Expected size of the seed in bytes: {SEED_SIZE} (SEED_SIZE)") priv_ffi = ffi.new(PRIV_FFI) seed_ffi = ffi.new(SEED_FFI, seed) lib.seed_to_priv(priv_ffi, seed_ffi) return bytes(priv_ffi) def x25519(priv: Priv, curve25519_pub: Curve25519Pub) -> SharedSecret: """ Perform Diffie-Hellman key agreement on Curve25519, also known as X25519. Args: priv: The private key partaking in the key agreement. curve25519_pub: The public key partaking in the key agreement. Returns: The shared secret. Raises: XEdDSAException: if the public key was rejected due to suboptimal security propierties or if the shared secret consists of only zeros """ if len(priv) != PRIV_SIZE: raise ValueError(f"Expected size of the private key in bytes: {PRIV_SIZE} (PRIV_SIZE)") if len(curve25519_pub) != CURVE_25519_PUB_SIZE: raise ValueError( f"Expected size of the Curve25519 public key in bytes: {CURVE_25519_PUB_SIZE}" " (CURVE_25519_PUB_SIZE)" ) shared_secret_ffi = ffi.new(SHARED_SECRET_FFI) priv_ffi = ffi.new(PRIV_FFI, priv) curve25519_pub_ffi = ffi.new(CURVE_25519_PUB_FFI, curve25519_pub) if lib.x25519(shared_secret_ffi, priv_ffi, curve25519_pub_ffi) != 0: raise XEdDSAException( "Key agreement failed, either due to suboptimal security properties of the public key, or due to" " the shared secret consisting of only zeros." ) return bytes(shared_secret_ffi) if not 2 <= lib.XEDDSA_VERSION_MAJOR < 3: raise Exception( "Wrong version of libxeddsa bound. Expected >=2,<3, got" f" {lib.XEDDSA_VERSION_MAJOR}.{lib.XEDDSA_VERSION_MINOR}.{lib.XEDDSA_VERSION_REVISION}" ) if lib.xeddsa_init() < 0: raise Exception("libxeddsa couldn't be initialized.") python-xeddsa-1.0.2/xeddsa/libxeddsa_emscripten.py000066400000000000000000000133361433243005500223200ustar00rootroot00000000000000# pylint: skip-file from browser import window # type: ignore[import] import re from typing import Any, Optional, cast __all__ = [ "cdata", "lib", "ffi" ] class cdata: def __init__(self, array: Any) -> None: self.__array = array @property def array(self) -> Any: return self.__array def __bytes__(self) -> bytes: return bytes(window.Array["from"](self.__array)) class lib: @staticmethod def ed25519_priv_sign(sig: cdata, priv: cdata, msg: cdata, msg_size: int, nonce: cdata) -> None: sig_ptr = window.Module._malloc(sig.array.length) window.ed25519_priv_sign(sig_ptr, priv.array, msg.array, msg_size, nonce.array) sig.array.set(window.HEAPU8.subarray(sig_ptr, sig_ptr + sig.array.length)) window.Module._free(sig_ptr) @staticmethod def ed25519_seed_sign(sig: cdata, seed: cdata, msg: cdata, msg_size: int) -> None: sig_ptr = window.Module._malloc(sig.array.length) window.ed25519_seed_sign(sig_ptr, seed.array, msg.array, msg_size) sig.array.set(window.HEAPU8.subarray(sig_ptr, sig_ptr + sig.array.length)) window.Module._free(sig_ptr) @staticmethod def ed25519_verify(sig: cdata, ed25519_pub: cdata, msg: cdata, msg_size: int) -> int: return cast(int, window.ed25519_verify(sig.array, ed25519_pub.array, msg.array, msg_size)) @staticmethod def curve25519_pub_to_ed25519_pub(ed25519_pub: cdata, curve25519_pub: cdata, set_sign_bit: bool) -> None: ed25519_pub_ptr = window.Module._malloc(ed25519_pub.array.length) window.curve25519_pub_to_ed25519_pub(ed25519_pub_ptr, curve25519_pub.array, set_sign_bit) ed25519_pub.array.set(window.HEAPU8.subarray( ed25519_pub_ptr, ed25519_pub_ptr + ed25519_pub.array.length )) window.Module._free(ed25519_pub_ptr) @staticmethod def ed25519_pub_to_curve25519_pub(curve25519_pub: cdata, ed25519_pub: cdata) -> int: curve25519_pub_ptr = window.Module._malloc(curve25519_pub.array.length) result = cast(int, window.ed25519_pub_to_curve25519_pub(curve25519_pub_ptr, ed25519_pub.array)) curve25519_pub.array.set(window.HEAPU8.subarray( curve25519_pub_ptr, curve25519_pub_ptr + curve25519_pub.array.length )) window.Module._free(curve25519_pub_ptr) return result @staticmethod def priv_to_curve25519_pub(curve25519_pub: cdata, priv: cdata) -> None: curve25519_pub_ptr = window.Module._malloc(curve25519_pub.array.length) window.priv_to_curve25519_pub(curve25519_pub_ptr, priv.array) curve25519_pub.array.set(window.HEAPU8.subarray( curve25519_pub_ptr, curve25519_pub_ptr + curve25519_pub.array.length )) window.Module._free(curve25519_pub_ptr) @staticmethod def priv_to_ed25519_pub(ed25519_pub: cdata, priv: cdata) -> None: ed25519_pub_ptr = window.Module._malloc(ed25519_pub.array.length) window.priv_to_ed25519_pub(ed25519_pub_ptr, priv.array) ed25519_pub.array.set(window.HEAPU8.subarray( ed25519_pub_ptr, ed25519_pub_ptr + ed25519_pub.array.length )) window.Module._free(ed25519_pub_ptr) @staticmethod def seed_to_ed25519_pub(ed25519_pub: cdata, seed: cdata) -> None: ed25519_pub_ptr = window.Module._malloc(ed25519_pub.array.length) window.seed_to_ed25519_pub(ed25519_pub_ptr, seed.array) ed25519_pub.array.set(window.HEAPU8.subarray( ed25519_pub_ptr, ed25519_pub_ptr + ed25519_pub.array.length )) window.Module._free(ed25519_pub_ptr) @staticmethod def priv_force_sign(priv_out: cdata, priv_in: cdata, set_sign_bit: bool) -> None: priv_out_ptr = window.Module._malloc(priv_out.array.length) window.priv_force_sign(priv_out_ptr, priv_in.array, set_sign_bit) priv_out.array.set(window.HEAPU8.subarray( priv_out_ptr, priv_out_ptr + priv_out.array.length )) window.Module._free(priv_out_ptr) @staticmethod def seed_to_priv(priv: cdata, seed: cdata) -> None: priv_ptr = window.Module._malloc(priv.array.length) window.seed_to_priv(priv_ptr, seed.array) priv.array.set(window.HEAPU8.subarray(priv_ptr, priv_ptr + priv.array.length)) window.Module._free(priv_ptr) @staticmethod def x25519(shared_secret: cdata, priv: cdata, curve25519_pub: cdata) -> int: shared_secret_ptr = window.Module._malloc(shared_secret.array.length) result = cast(int, window.x25519(shared_secret_ptr, priv.array, curve25519_pub.array)) shared_secret.array.set(window.HEAPU8.subarray( shared_secret_ptr, shared_secret_ptr + shared_secret.array.length )) window.Module._free(shared_secret_ptr) return result @staticmethod def xeddsa_init() -> int: return cast(int, window.xeddsa_init()) XEDDSA_VERSION_MAJOR: int = window.XEDDSA_VERSION_MAJOR XEDDSA_VERSION_MINOR: int = window.XEDDSA_VERSION_MINOR XEDDSA_VERSION_REVISION: int = window.XEDDSA_VERSION_REVISION class ffi: @staticmethod def new(type_definition: str, data: Optional[bytes] = None) -> cdata: match = re.match(r"uint8_t\[(\d+)?\]", type_definition) if match is None: raise ValueError("Only uint8_t arrays are supported for now.") array_size = match.group(1) if array_size is None and data is None: raise ValueError("Data must be supplied if an array of unknown size is requested.") return cdata( window.Uint8Array.new(array_size) if data is None else window.Uint8Array["from"](list(data)) ) python-xeddsa-1.0.2/xeddsa/project.py000066400000000000000000000006321433243005500175710ustar00rootroot00000000000000__all__ = [ "project" ] # pylint: disable=unused-variable project = { "name" : "XEdDSA", "description" : "Python bindings to libxeddsa.", "url" : "https://github.com/Syndace/python-xeddsa", "year" : "2022", "author" : "Tim Henkes (Syndace)", "author_email" : "me@syndace.dev", "categories" : [ "Topic :: Security :: Cryptography" ] } python-xeddsa-1.0.2/xeddsa/py.typed000066400000000000000000000000001433243005500172350ustar00rootroot00000000000000python-xeddsa-1.0.2/xeddsa/version.py000066400000000000000000000003231433243005500176050ustar00rootroot00000000000000__all__ = [ "__version__" ] # pylint: disable=unused-variable __version__ = {} __version__["short"] = "1.0.2" __version__["tag"] = "stable" __version__["full"] = f"{__version__['short']}-{__version__['tag']}"