././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7690542 spake2-0.9/0000755000175000017500000000000014674653710012070 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/.coveragerc0000644000175000017500000000013414654534712014205 0ustar00meejahmeejah# -*- conf -*- [run] include = src/spake2/* omit = */spake2/_version.py */spake2/test/* ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/.travis.yml0000644000175000017500000000047514652777131014207 0ustar00meejahmeejahsudo: false language: python cache: pip before_cache: - rm -f $HOME/.cache/pip/log/debug.log python: - "2.6" - "2.7" - "3.3" - "3.4" - "3.5" - "3.6" - "pypy" install: - pip install -U tox virtualenv coverage python-coveralls script: - tox -e coverage - tox -e speed after_success: - coveralls ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/LICENSE0000644000175000017500000000211014652777131013067 0ustar00meejahmeejah"python-spake2" Copyright (c) 2015 Brian Warner The MIT License (MIT) 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/MANIFEST.in0000644000175000017500000000017414652777131013630 0ustar00meejahmeejahinclude versioneer.py include src/spake2/_version.py include README.md NEWS LICENSE include tox.ini .travis.yml .coveragerc ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727219453.0 spake2-0.9/NEWS0000644000175000017500000000541514674643375012602 0ustar00meejahmeejah User-Visible Changes in python-spake2 * Upcoming Release (Put notes about merged features here). * Release 0.9 (24-Sep-2024) This release mainly deals with packaging simplifications: two dependencies ("six" and "hkdf") are removed. The "cryptography" library takes the place of "hkdf" for key derivation. There is no longer a vendored version of "six" (nor internal use of it, thanks a-dieste). The "versioneer" library is updated to 0.29. * Release 0.8 (14-Feb-2018) API BREAK (but not a compatibility break) Applications using this release will start up faster. The library includes multiple groups (with different message sizes, performance, and security levels), and each group uses a different blinding factor. These factors take a relatively long time to compute. The previous release did this computation for all groups, even ones that the application never imported. This release changes the import API to avoid the unnecessary calculations, which saves about 400ms at import time on my 2016-era laptop (and several seconds on a Raspberry Pi). Applications must use different "import" statements when upgrading to this release ("from spake2.parameters.ed25519 import ParamsEd25519" instead of "from spake2 import ParamsEd25519"). However this release retains message compatibility with spake2-0.7: apps using 0.8 can interoperate with apps using 0.7 without problems. * Release 0.7 (12-May-2016) COMPATIBILITY BREAK This release changes the way passwords are turned into scalars, and the way the final transcript hash is formatted. Hopefully this will be compatible with the proposed SJCL (Javascript) implementation described in the comments of https://github.com/bitwiseshiftleft/sjcl/pull/273 . Applications which use python-spake2-0.3 or earlier will not interoperate with those which use 0.7 or later: the session keys will never match. pypy3 support has been dropped, until pypy3 handles python3.3 or later (it currently implements the equivalent of python3.2). python-spake2 now depends on the "hkdf" package. Tox and py.test are now used for running tests. setup.py has been switched from distutils to setuptools. * Release 0.3 (22-Sep-2015) Use the faster "M=N" blinding factors for SPAKE2_Symmetric, instead of running two sessions in parallel and combining the results. This gets the same speed and message size as the asymmetric (SPAKE2_A/SPAKE2_B) approach, and is probably safe (see README for the security proofs). * Release 0.2 (08-Apr-2015) Use Ed25519 group/parameters by default (improves speed, security, and message size). Note that both sides must use the same parameter set for compatibility. * Release 0.1 (13-Feb-2015) Initial release. Includes SPAKE2_A/SPAKE2_B, and SPAKE2_Symmetric. Provides three integer-group parameter sets (Params1024, Params2048, Params3072). ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7690542 spake2-0.9/PKG-INFO0000644000175000017500000000101214674653710013157 0ustar00meejahmeejahMetadata-Version: 2.1 Name: spake2 Version: 0.9 Summary: SPAKE2 password-authenticated key exchange (pure python) Home-page: https://github.com/warner/python-spake2 Author: Brian Warner Author-email: warner-pyspake2@lothar.com License: MIT Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Security :: Cryptography License-File: LICENSE Requires-Dist: cryptography ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989450.0 spake2-0.9/README.md0000644000175000017500000003554214654535612013356 0ustar00meejahmeejah # Pure-Python SPAKE2 * License: MIT * Dependencies: "cryptography" (for hkdf) * Compatible With: Python 3.9, 3.10, 3.11, 3.12, PyPy3 * [![Build Status](https://travis-ci.org/warner/python-spake2.png?branch=master)](https://travis-ci.org/warner/python-spake2) [![Windows Build Status](https://ci.appveyor.com/api/projects/status/j2q57qee3xwbqp5l/branch/master?svg=true)](https://ci.appveyor.com/project/warner/python-spake2) [![Coverage Status](https://coveralls.io/repos/warner/python-spake2/badge.svg)](https://coveralls.io/r/warner/python-spake2) This library implements the SPAKE2 password-authenticated key exchange ("PAKE") algorithm. This allows two parties, who share a weak password, to safely derive a strong shared secret (and therefore build an encrypted+authenticated channel). A passive attacker who eavesdrops on the connection learns no information about the password or the generated secret. An active attacker (man-in-the-middle) gets exactly one guess at the password, and unless they get it right, they learn no information about the password or the generated secret. Each execution of the protocol enables one guess. The use of a weak password is made safer by the rate-limiting of guesses: no off-line dictionary attack is available to the network-level attacker, and the protocol does not depend upon having previously-established confidentiality of the network (unlike e.g. sending a plaintext password over TLS). The protocol requires the exchange of one pair of messages, so only one round trip is necessary to establish the session key. If key-confirmation is necessary, that will require a second round trip. All messages are bytestrings. For the default security level (using the Ed25519 elliptic curve, roughly equivalent to an 128-bit symmetric key), the message is 33 bytes long. ## What Is It Good For? PAKE can be used in a pairing protocol, like the initial version of Firefox Sync (the one with J-PAKE), to introduce one device to another and help them share secrets. In this mode, one device creates a random code, the user copies that code to the second device, then both devices use the code as a one-time password and run the PAKE protocol. Once both devices have a shared strong key, they can exchange other secrets safely. PAKE can also be used (carefully) in a login protocol, where SRP is perhaps the best-known approach. Traditional non-PAKE login consists of sending a plaintext password through a TLS-encrypted channel, to a server which then checks it (by hashing/stretching and comparing against a stored verifier). In a PAKE login, both sides put the password into their PAKE protocol, and then confirm that their generated key is the same. This nominally does not require the initial TLS-protected channel. However note that it requires other, deeper design considerations (the PAKE protocol must be bound to whatever protected channel you end up using, else the attacker can wait for PAKE to complete normally and then steal the channel), and is not simply a drop-in replacement. In addition, the server cannot hash/stretch the password very much (see the note on "Augmented PAKE" below), so unless the client is willing to perform key-stretching before running PAKE, the server's stored verifier will be vulnerable to a low-cost dictionary attack. ## Usage Alice and Bob both initialize their SPAKE2 instances with the same (weak) password. They will exchange messages to (hopefully) derive a shared secret key. The protocol is symmetric: for each operation that Alice does, Bob will do the same. However, there are two roles in the SPAKE2 protocol, "A" and "B". The two sides must agree ahead of time which one will play which role (the messages they generate depend upon which side they play). There are two separate classes, `SPAKE2_A` and `SPAKE2_B`, and a complete interaction will use one of each (one `SPAKE2_A` on one computer, and one `SPAKE2_B` on the other computer). Each instance of a SPAKE2 protocol uses a set of shared parameters. These include a group, a generator, and a pair of arbitrary group elements. This library comes with several pre-generated parameter sets, with various security levels. You start by creating an instance (either `SPAKE2_A` or `SPAKE2_B`) with the password. Then you ask the instance for the outbound message by calling `msg_out=s.start()`, and send it to your partner. Once you receive the corresponding inbound message, you pass it into the instance and extract the (shared) key bytestring with `key=s.finish(msg_in)`. For example, the client-side might do: ```python from spake2 import SPAKE2_A s = SPAKE2_A(b"our password") msg_out = s.start() send(msg_out) # this is message A->B msg_in = receive() key = s.finish(msg_in) ``` while the server-side might do: ```python from spake2 import SPAKE2_B q = SPAKE2_B(b"our password") msg_out = q.start() send(msg_out) msg_in = receive() # this is message A->B key = q.finish(msg_in) ``` If both sides used the same password, and there is no man-in-the-middle, then both sides will obtain the same `key`. If not, the two sides will get different keys, so using "key" for data encryption will result in garbled data. The shared "key" can be used as an HMAC key to provide data integrity on subsequent messages, or as an authenticated-encryption key (e.g. nacl.secretbox). It can also be fed into [HKDF] [1] to derive other session keys as necessary. The `SPAKE2` instances, and the messages they create, are single-use. Create a new one for each new session. ### Key Confirmation To safely test for identical keys before use, you can perform a second message exchange at the end of the protocol, before actually using the key (be careful to not simply send the shared key over the wire: this would allow a MitM to learn the key that they could otherwise not guess). Alice does this: ```python ... key = s.finish(msg_in) confirm_A = HKDF(key, info="confirm_A", length=32) expected_confirm_B = HKDF(key, info="confirm_B", length=32) send(confirm_A) confirm_B = receive() assert confirm_B == expected_confirm_B ``` And Bob does this: ```python ... key = q.finish(msg_in) expected_confirm_A = HKDF(key, info="confirm_A", length=32) confirm_B = HKDF(key, info="confirm_B", length=32) send(confirm_B) confirm_A = receive() assert confirm_A == expected_confirm_A ``` ## Symmetric Usage A single SPAKE2 instance must be used asymmetrically: the two sides must somehow decide (ahead of time) which role they will each play. The implementation includes the side identifier in the exchanged message to guard against an `SPAKE2_A` talking to another `SPAKE2_A`. Typically a "client" will take on the `A` role, and the "server" will be `B`. This is a nuisance for more egalitarian protocols, where there's no clear way to assign these roles ahead of time. In this case, use `SPAKE2_Symmetric` on both sides. This uses a different set of parameters (so it is not interoperable with `SPAKE2_A` or `SPAKE2_B`, but should otherwise behave the same way. Carol does: ```python s1 = SPAKE2_Symmetric(pw) outmsg1 = s1.start() send(outmsg1) ``` Dave does the same: ```python s2 = SPAKE2_Symmetric(pw) outmsg2 = s2.start() send(outmsg2) ``` Carol then processes Dave's incoming message: ```python inmsg2 = receive() # this is outmsg1 key = s1.finish(inmsg2) ``` And Dave does the same: ```python inmsg1 = receive() # this is outmsg2 key = s2.finish(inmsg1) ``` ## Identifier Strings The SPAKE2 protocol includes a pair of "identity strings" `idA` and `idB` that are included in the final key-derivation hash. This binds the key to a single pair of parties, or for some specific purpose. For example, when user "alice" logs into "example.com", both sides should set `idA = b"alice"` and `idB = b"example.com"`. This prevents an attacker from substituting messages from unrelated login sessions (other users on the same server, or other servers for the same user). This also makes sure the session is established with the correct service. If Alice has one password for "example.com" but uses it for both login and file-transfer services, `idB` should be different for the two services. Otherwise if Alice is simultaneously connecting to both services, and attacker could rearrange the messages and cause her login client to connect to the file-transfer server, and vice versa. If provided, `idA` and `idB` must be bytestrings. They default to an empty string. `SPAKE2_Symmetric` uses a single `idSymmetric=` string, instead of `idA` and `idB`. Both sides must provide the same `idSymmetric=`, or leave it empty. ## Serialization Sometimes, you can't hold the SPAKE2 instance in memory for the whole negotiation: perhaps all your program state is stored in a database, and nothing lives in RAM for more than a few moments. You can persist the data from a SPAKE2 instance with `data = p.serialize()`, after the call to `start`. Then later, when the inbound message is received, you can reconstruct the instance with `p = SPAKE2_A.from_serialized(data)` before calling `p.finish(msg)`. ```python def first(): p = SPAKE2_A(password) send(p.start()) open('saved','w').write(p.serialize()) def second(inbound_message): p = SPAKE2_A.from_serialized(open('saved').read()) key = p.finish(inbound_message) return key ``` The instance data is highly sensitive and includes the password: protect it carefully. An eavesdropper who learns the instance state from just one side will be able to reconstruct the shared key. `data` is a printable ASCII bytestring (the JSON-encoding of a small dictionary). For `ParamsEd25519`, the serialized data requires 221 bytes. Note that you must restore the instance with the same side (`SPAKE2_A` vs `SPAKE2_B`) and `params=` (if overridden) as you used when first creating it. Otherwise `from_serialized()` will throw an exception. If you use non-default parameters, you might want to store an indicator along with the serialized state. Also remember that you must never re-use a SPAKE2 instance for multiple key agreements: that would reveal the key and/or password. Never use `.from_serialized()` more than once on the same saved state, and delete the state as soon as the incoming message is processed. SPAKE2 has internal checks to throw exceptions when instances are used multiple times, but the serialize/restore process can bypass those checks, so use with care. Database-backed applications should store the outbound message (`p.start()`) in the DB next to the serialized SPAKE2 state, so they can re-send the same message if the application crashes before it has been successfully delivered. `p.start()` cannot be called on the instance that `.from_serialized()` produces. ## Security SPAKE2's strength against cryptographic attacks depends upon the parameters you use, which also influence the execution speed. Use the strongest parameters your time budget can afford. The library defaults to the fast and secure Ed25519 elliptic-curve group through the `ParamsEd25519` parameter set. This offers a 128-bit security level, small messages, and fairly fast execution speed. If for some reason you don't care for elliptic curves, the `spake2.params` module includes three integer-group parameter sets: `Params1024`, `Params2048`, `Params3072`, offering 80-bit, 112-bit, and 128-bit security levels respectively. To override the default parameters, include a `params=` value when you create the SPAKE2 instance. Both sides must use the same parameters. ```python from spake2 import SPAKE2_A from spake2.parameters.i3072 import Params3072 s = SPAKE2_A(b"password", params=Params3072) ``` Note that if you serialize an instance with non-default `params=`, you must restore it with the same parameters, otherwise you will get an exception: ```python s = SPAKE2_A.from_serialized(data, params=Params3072) ``` This library is very much *not* constant-time, and does not protect against timing attacks. Do not allow attackers to measure how long it takes you to create or respond to a message. This library depends upon a strong source of random numbers. Do not use it on a system where os.urandom() is weak. ## Speed To run the built-in speed tests, just run `python setup.py speed`. SPAKE2 consists of two phases, separated by a single message exchange. The time these phases take is split roughly 40/60. On my 2012 Mac Mini (2.6GHz Core-i7), the default `ParamsEd25519` security level takes about 14ms to complete both phases. For the integer groups, larger groups are slower and require larger messages (and their serialized state is larger), but are more secure. The complete output of `python setup.py speed` is: ParamsEd25519: msglen= 33, statelen=221, full=13.9ms, start= 5.5ms Params1024 : msglen=129, statelen=197, full= 4.3ms, start= 1.8ms Params2048 : msglen=257, statelen=213, full=20.8ms, start= 8.5ms Params3072 : msglen=385, statelen=221, full=41.5ms, start=16.5ms A slower CPU (1.8GHz Intel Atom) takes about 8x as long (76/32/157/322ms). This library uses only Python. A version which used C speedups for the large modular multiplication operations would probably be an order of magnitude faster. ## Testing To run the built-in test suite from a source directory, for all supported python versions, do: tox On my computer, the tests take approximately two seconds (per version). ## History The protocol was described as "PAKE2" in ["cryptobook"] [2] from Dan Boneh and Victor Shoup. This is a form of "SPAKE2", defined by Abdalla and Pointcheval at [RSA 2005] [3]. Additional recommendations for groups and distinguished elements were published in [Ladd's IETF draft] [4]. The Ed25519 implementation uses code adapted from Daniel Bernstein (djb), Matthew Dempsky, Daniel Holth, Ron Garret, with further optimizations by Brian Warner[5]. The "arbitrary element" computation, which must be the same for both participants, is from python-pure25519 version 0.5. The Boneh/Shoup chapter that defines PAKE2 also defines an augmented variant named "PAKE2+", which changes one side (typically a server) to record a derivative of the password instead of the actual password. In PAKE2+, a server compromise does not immediately give access to the passwords: instead, the attacker must perform an offline dictionary attack against the stolen data before they can learn the passwords. PAKE2+ support is planned, but not yet implemented. The security of the symmetric case was proved by Kobara/Imai[6] in 2003, and uses different (slightly weaker?) reductions than that of the asymmetric form. See also Mike Hamburg's analysis[7] from 2015. Brian Warner first wrote this Python version in July 2010. #### footnotes [1]: https://tools.ietf.org/html/rfc5869 "HKDF" [2]: http://crypto.stanford.edu/~dabo/cryptobook/ "cryptobook" [3]: http://www.di.ens.fr/~pointche/Documents/Papers/2005_rsa.pdf "RSA 2005" [4]: https://tools.ietf.org/html/draft-ladd-spake2-01 "Ladd's IETF draft" [5]: https://github.com/warner/python-pure25519 [6]: http://eprint.iacr.org/2003/038.pdf "Pretty-Simple Password-Authenticated Key-Exchange Under Standard Assumptions" [7]: https://moderncrypto.org/mail-archive/curves/2015/000419.html "PAKE questions" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7730546 spake2-0.9/setup.cfg0000644000175000017500000000032114674653710013705 0ustar00meejahmeejah[versioneer] VCS = git style = pep440 versionfile_source = src/spake2/_version.py versionfile_build = spake2/_version.py tag_prefix = v parentdir_prefix = python-spake2- [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989099.0 spake2-0.9/setup.py0000755000175000017500000000534314654535053013607 0ustar00meejahmeejah#!/usr/bin/env python import timeit from setuptools import setup, Command import versioneer cmdclass = {} cmdclass.update(versioneer.get_cmdclass()) class Speed(Command): description = "run speed benchmarks" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): def do(setup_statements, statement): # extracted from timeit.py t = timeit.Timer(stmt=statement, setup="\n".join(setup_statements)) # determine number so that 0.2 <= total time < 2.0 for i in range(1, 10): number = 10**i x = t.timeit(number) if x >= 0.2: break return x / number def abbrev(t): if t > 1.0: return "%.3fs" % t if t > 1e-3: return "%.1fms" % (t*1e3) return "%.1fus" % (t*1e6) for params in ["ParamsEd25519", "Params1024", "Params2048", "Params3072"]: S1 = "from spake2 import SPAKE2_A, SPAKE2_B; from spake2.parameters.all import %s" % params S2 = "sB = SPAKE2_B(b'password', params=%s)" % params S3 = "mB = sB.start()" S4 = "sA = SPAKE2_A(b'password', params=%s)" % params S5 = "mA = sA.start()" S8 = "key = sA.finish(mB)" full = do([S1, S2, S3], ";".join([S4, S5, S8])) start = do([S1], ";".join([S4, S5])) # how large is the generated message? from spake2.parameters import all as all_params from spake2 import SPAKE2_A p = getattr(all_params, params) s = SPAKE2_A(b"pw", params=p) msglen = len(s.start()) statelen = len(s.serialize()) print("%-13s: msglen=%3d, statelen=%3d, full=%6s, start=%6s" % (params, msglen, statelen, abbrev(full), abbrev(start))) cmdclass["speed"] = Speed setup(name="spake2", version=versioneer.get_version(), description="SPAKE2 password-authenticated key exchange (pure python)", author="Brian Warner", author_email="warner-pyspake2@lothar.com", url="https://github.com/warner/python-spake2", package_dir={"": "src"}, packages=["spake2", "spake2.parameters", "spake2.test"], license="MIT", cmdclass=cmdclass, classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Security :: Cryptography", ], install_requires=["cryptography"], ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7610538 spake2-0.9/src/0000755000175000017500000000000014674653710012657 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1727223751.765054 spake2-0.9/src/spake2/0000755000175000017500000000000014674653710014044 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/src/spake2/__init__.py0000644000175000017500000000032014654534712016146 0ustar00meejahmeejah from .spake2 import SPAKE2_A, SPAKE2_B, SPAKE2_Symmetric, SPAKEError SPAKE2_A, SPAKE2_B, SPAKE2_Symmetric, SPAKEError # hush pyflakes from . import _version __version__ = _version.get_versions()['version'] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7730546 spake2-0.9/src/spake2/_version.py0000644000175000017500000000075714674653710016253 0ustar00meejahmeejah # This file was generated by 'versioneer.py' (0.29) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' { "date": "2024-09-24T18:07:09-0600", "dirty": false, "error": null, "full-revisionid": "e1d1d51d357249a939b2b416a6956d4c191477b3", "version": "0.9" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1723079780.0 spake2-0.9/src/spake2/ed25519_basic.py0000644000175000017500000003004214655016144016545 0ustar00meejahmeejahimport binascii, hashlib, itertools from .groups import expand_arbitrary_element_seed Q = 2**255 - 19 L = 2**252 + 27742317777372353535851937790883648493 def inv(x): return pow(x, Q-2, Q) d = -121665 * inv(121666) I = pow(2,(Q-1)//4,Q) def xrecover(y): xx = (y*y-1) * inv(d*y*y+1) x = pow(xx,(Q+3)//8,Q) if (x*x - xx) % Q != 0: x = (x*I) % Q if x % 2 != 0: x = Q-x return x By = 4 * inv(5) Bx = xrecover(By) B = [Bx % Q,By % Q] # Extended Coordinates: x=X/Z, y=Y/Z, x*y=T/Z # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html def xform_affine_to_extended(pt): (x, y) = pt return (x%Q, y%Q, 1, (x*y)%Q) # (X,Y,Z,T) def xform_extended_to_affine(pt): (x, y, z, _) = pt return ((x*inv(z))%Q, (y*inv(z))%Q) def double_element(pt): # extended->extended # dbl-2008-hwcd (X1, Y1, Z1, _) = pt A = (X1*X1) B = (Y1*Y1) C = (2*Z1*Z1) D = (-A) % Q J = (X1+Y1) % Q E = (J*J-A-B) % Q G = (D+B) % Q F = (G-C) % Q H = (D-B) % Q X3 = (E*F) % Q Y3 = (G*H) % Q Z3 = (F*G) % Q T3 = (E*H) % Q return (X3, Y3, Z3, T3) def add_elements(pt1, pt2): # extended->extended # add-2008-hwcd-3 . Slightly slower than add-2008-hwcd-4, but -3 is # unified, so it's safe for general-purpose addition (X1, Y1, Z1, T1) = pt1 (X2, Y2, Z2, T2) = pt2 A = ((Y1-X1)*(Y2-X2)) % Q B = ((Y1+X1)*(Y2+X2)) % Q C = T1*(2*d)*T2 % Q D = Z1*2*Z2 % Q E = (B-A) % Q F = (D-C) % Q G = (D+C) % Q H = (B+A) % Q X3 = (E*F) % Q Y3 = (G*H) % Q T3 = (E*H) % Q Z3 = (F*G) % Q return (X3, Y3, Z3, T3) def scalarmult_element_safe_slow(pt, n): # this form is slightly slower, but tolerates arbitrary points, including # those which are not in the main 1*L subgroup. This includes points of # order 1 (the neutral element Zero), 2, 4, and 8. assert n >= 0 if n==0: return xform_affine_to_extended((0,1)) _ = double_element(scalarmult_element_safe_slow(pt, n>>1)) return add_elements(_, pt) if n&1 else _ def _add_elements_nonunfied(pt1, pt2): # extended->extended # add-2008-hwcd-4 : NOT unified, only for pt1!=pt2. About 10% faster than # the (unified) add-2008-hwcd-3, and safe to use inside scalarmult if you # aren't using points of order 1/2/4/8 (X1, Y1, Z1, T1) = pt1 (X2, Y2, Z2, T2) = pt2 A = ((Y1-X1)*(Y2+X2)) % Q B = ((Y1+X1)*(Y2-X2)) % Q C = (Z1*2*T2) % Q D = (T1*2*Z2) % Q E = (D+C) % Q F = (B-A) % Q G = (B+A) % Q H = (D-C) % Q X3 = (E*F) % Q Y3 = (G*H) % Q Z3 = (F*G) % Q T3 = (E*H) % Q return (X3, Y3, Z3, T3) def scalarmult_element(pt, n): # extended->extended # This form only works properly when given points that are a member of # the main 1*L subgroup. It will give incorrect answers when called with # the points of order 1/2/4/8, including point Zero. (it will also work # properly when given points of order 2*L/4*L/8*L) assert n >= 0 if n==0: return xform_affine_to_extended((0,1)) _ = double_element(scalarmult_element(pt, n>>1)) return _add_elements_nonunfied(_, pt) if n&1 else _ # points are encoded as 32-bytes little-endian, b255 is sign, b2b1b0 are 0 def encodepoint(P): x = P[0] y = P[1] # MSB of output equals x.b0 (=x&1) # rest of output is little-endian y assert 0 <= y < (1<<255) # always < 0x7fff..ff if x & 1: y += 1<<255 return binascii.unhexlify(("%064x" % y).encode("ascii"))[::-1] def isoncurve(P): x = P[0] y = P[1] return (-x*x + y*y - 1 - d*x*x*y*y) % Q == 0 class NotOnCurve(Exception): pass def decodepoint(s): unclamped = int(binascii.hexlify(s[:32][::-1]), 16) clamp = (1 << 255) - 1 y = unclamped & clamp # clear MSB x = xrecover(y) if bool(x & 1) != bool(unclamped & (1<<255)): x = Q-x P = [x,y] if not isoncurve(P): raise NotOnCurve("decoding point that is not on curve") return P # scalars are encoded as 32-bytes little-endian def bytes_to_scalar(s): assert len(s) == 32, len(s) return int(binascii.hexlify(s[::-1]), 16) def bytes_to_clamped_scalar(s): # Ed25519 private keys clamp the scalar to ensure two things: # 1: integer value is in L/2 .. L, to avoid small-logarithm # non-wraparaound # 2: low-order 3 bits are zero, so a small-subgroup attack won't learn # any information # set the top two bits to 01, and the bottom three to 000 a_unclamped = bytes_to_scalar(s) AND_CLAMP = (1<<254) - 1 - 7 OR_CLAMP = (1<<254) a_clamped = (a_unclamped & AND_CLAMP) | OR_CLAMP return a_clamped def random_scalar(entropy_f): # 0..L-1 inclusive # reduce the bias to a safe level by generating 256 extra bits oversized = int(binascii.hexlify(entropy_f(32+32)), 16) return oversized % L # unused, in favor of common HKDF approach in groups.py #def password_to_scalar(pw): # oversized = hashlib.sha512(pw).digest() # return int(binascii.hexlify(oversized), 16) % L def scalar_to_bytes(y): y = y % L assert 0 <= y < 2**256 return binascii.unhexlify(("%064x" % y).encode("ascii"))[::-1] # Elements, of various orders def is_extended_zero(XYTZ): # catch Zero (X, Y, Z, T) = XYTZ Y = Y % Q Z = Z % Q if X==0 and Y==Z and Y!=0: return True return False class ElementOfUnknownGroup: # This is used for points of order 2,4,8,2*L,4*L,8*L def __init__(self, XYTZ): assert isinstance(XYTZ, tuple) assert len(XYTZ) == 4 self.XYTZ = XYTZ def add(self, other): if not isinstance(other, ElementOfUnknownGroup): raise TypeError("elements can only be added to other elements") sum_XYTZ = add_elements(self.XYTZ, other.XYTZ) if is_extended_zero(sum_XYTZ): return Zero return ElementOfUnknownGroup(sum_XYTZ) def scalarmult(self, s): if isinstance(s, ElementOfUnknownGroup): raise TypeError("elements cannot be multiplied together") assert s >= 0 product = scalarmult_element_safe_slow(self.XYTZ, s) return ElementOfUnknownGroup(product) def to_bytes(self): return encodepoint(xform_extended_to_affine(self.XYTZ)) def __eq__(self, other): return self.to_bytes() == other.to_bytes() def __ne__(self, other): return not self == other class Element(ElementOfUnknownGroup): # this only holds elements in the main 1*L subgroup. It never holds Zero, # or elements of order 1/2/4/8, or 2*L/4*L/8*L. def add(self, other): if not isinstance(other, ElementOfUnknownGroup): raise TypeError("elements can only be added to other elements") sum_element = ElementOfUnknownGroup.add(self, other) if sum_element is Zero: return sum_element if isinstance(other, Element): # adding two subgroup elements results in another subgroup # element, or Zero, and we've already excluded Zero return Element(sum_element.XYTZ) # not necessarily a subgroup member, so assume not return sum_element def scalarmult(self, s): if isinstance(s, ElementOfUnknownGroup): raise TypeError("elements cannot be multiplied together") # scalarmult of subgroup members can be done modulo the subgroup # order, and using the faster non-unified function. s = s % L # scalarmult(s=0) gets you Zero if s == 0: return Zero # scalarmult(s=1) gets you self, which is a subgroup member # scalarmult(s= scalar_size_bytes i = bytes_to_number(oversized) return i % q def expand_arbitrary_element_seed(data, num_bytes): return hkdf.HKDF( algorithm=hashes.SHA256(), length=num_bytes, salt=b"", info=b"SPAKE2 arbitrary element" ).derive(data) class _Element: def __init__(self, group, e): self._group = group self._e = e def add(self, other): return self._group._add(self, other) def scalarmult(self, s): return self._group._scalarmult(self, s) def to_bytes(self): return self._group._element_to_bytes(self) class IntegerGroup: def __init__(self, p, q, g): self.q = q # the subgroup order, used for scalars self.scalar_size_bytes = size_bytes(self.q) _s = self.scalar_to_bytes(self.password_to_scalar(b"")) assert isinstance(_s, bytes) assert len(_s) >= self.scalar_size_bytes self.Zero = _Element(self, 1) self.Base = _Element(self, g) # generator of the subgroup # these are the public system parameters self.p = p # the field size self.element_size_bits = size_bits(self.p) self.element_size_bytes = size_bytes(self.p) # double-check that the generator has the right order assert pow(g, self.q, self.p) == 1 def order(self): return self.q def random_scalar(self, entropy_f): return unbiased_randrange(0, self.q, entropy_f) def scalar_to_bytes(self, i): # both for hashing into transcript, and save/restore of # intermediate state assert isinstance(i, int) assert 0 <= 0 < self.q return number_to_bytes(i, self.q) def bytes_to_scalar(self, b): # for restore of intermediate state assert isinstance(b, bytes) assert len(b) == self.scalar_size_bytes i = bytes_to_number(b) assert 0 <= i < self.q, (0, i, self.q) return i def password_to_scalar(self, pw): return password_to_scalar(pw, self.scalar_size_bytes, self.q) def arbitrary_element(self, seed): # we do *not* know the discrete log of this one. Nobody should. assert isinstance(seed, bytes) processed_seed = expand_arbitrary_element_seed(seed, self.element_size_bytes) assert isinstance(processed_seed, bytes) assert len(processed_seed) == self.element_size_bytes # The larger (non-prime-order) group (Zp*) we're using has order # p-1. The smaller (prime-order) subgroup has order q. Subgroup # orders always divide the larger group order, so r*q=p-1 for # some integer r. If h is an arbitrary element of the larger # group Zp*, then e=h^r will be an element of the subgroup. If h # is selected uniformly at random, so will e, and nobody will # know its discrete log. We can enforce this for pre-selected # parameters by choosing h as the output of a hash function. r = (self.p - 1) // self.q assert r * self.q == self.p - 1 h = bytes_to_number(processed_seed) % self.p element = _Element(self, pow(h, r, self.p)) assert self._is_member(element) return element def _is_member(self, e): if not e._group is self: return False if pow(e._e, self.q, self.p) == 1: return True return False def _element_to_bytes(self, e): # for sending to other side, and hashing into transcript assert isinstance(e, _Element) assert e._group is self return number_to_bytes(e._e, self.p) def bytes_to_element(self, b): # for receiving from other side: test group membership here assert isinstance(b, bytes) assert len(b) == self.element_size_bytes i = bytes_to_number(b) if i <= 0 or i >= self.p: # Zp* excludes 0 raise ValueError("alleged element not in the field") e = _Element(self, i) if not self._is_member(e): raise ValueError("element is not in the right group") return e def _scalarmult(self, e1, i): if not isinstance(e1, _Element): raise TypeError("E*N requires E be an element") assert e1._group is self if not isinstance(i, int): raise TypeError("E*N requires N be a scalar") return _Element(self, pow(e1._e, i % self.q, self.p)) def _add(self, e1, e2): if not isinstance(e1, _Element): raise TypeError("E*N requires E be an element") assert e1._group is self if not isinstance(e2, _Element): raise TypeError("E*N requires E be an element") assert e2._group is self return _Element(self, (e1._e * e2._e) % self.p) # This 1024-bit group originally came from the J-PAKE demo code, # http://haofeng66.googlepages.com/JPAKEDemo.java . That java code # recommended these 2048 and 3072 bit groups from this NIST document: # http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/DSA2_All.pdf # L=1024, N=160 I1024 = IntegerGroup( p=0xE0A67598CD1B763BC98C8ABB333E5DDA0CD3AA0E5E1FB5BA8A7B4EABC10BA338FAE06DD4B90FDA70D7CF0CB0C638BE3341BEC0AF8A7330A3307DED2299A0EE606DF035177A239C34A912C202AA5F83B9C4A7CF0235B5316BFC6EFB9A248411258B30B839AF172440F32563056CB67A861158DDD90E6A894C72A5BBEF9E286C6B, q=0xE950511EAB424B9A19A2AEB4E159B7844C589C4F, g=0xD29D5121B0423C2769AB21843E5A3240FF19CACC792264E3BB6BE4F78EDD1B15C4DFF7F1D905431F0AB16790E1F773B5CE01C804E509066A9919F5195F4ABC58189FD9FF987389CB5BEDF21B4DAB4F8B76A055FFE2770988FE2EC2DE11AD92219F0B351869AC24DA3D7BA87011A701CE8EE7BFE49486ED4527B7186CA4610A75, ) # L=2048, N=224 I2048 = IntegerGroup( p=0xC196BA05AC29E1F9C3C72D56DFFC6154A033F1477AC88EC37F09BE6C5BB95F51C296DD20D1A28A067CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE428782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE619ECACC7E0B51652A8776D02A425567DED36EABD90CA33A1E8D988F0BBB92D02D1D20290113BB562CE1FC856EEB7CDD92D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BFFAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E5320121496DC65B3930E38047294FF877831A16D5228418DE8AB275D7D75651CEFED65F78AFC3EA7FE4D79B35F62A0402A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83, q=0x90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D, g=0xA59A749A11242C58C894E9E5A91804E8FA0AC64B56288F8D47D51B1EDC4D65444FECA0111D78F35FC9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E5048B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B6E770409494B7FEE1DBB1E4B2BC2A53D4F893D418B7159592E4FFFDF6969E91D770DAEBD0B5CB14C00AD68EC7DC1E5745EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDFD049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E695515B05BD412F5B8C2F4C77EE10DA48ABD53F5DD498927EE7B692BBBCDA2FB23A516C5B4533D73980B2A3B60E384ED200AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085, ) # L=3072, N=256 I3072 = IntegerGroup( p=0x90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F009D20A7E7880E4E5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA129F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D3485261CD068699B6BA58A1DDBBEF6DB51E8FE34E8A78E542D7BA351C21EA8D8F1D29F5D5D15939487E27F4416B0CA632C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0EE6F29AF7F642773EBE8CD5402415A01451A840476B2FCEB0E388D30D4B376C37FE401C2A2C2F941DAD179C540C1C8CE030D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504FB0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C560EA878DE87C11E3D597F1FEA742D73EEC7F37BE43949EF1A0D15C3F3E3FC0A8335617055AC91328EC22B50FC15B941D3D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73, q=0xCFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D, g=0x5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE3B7ACCC54D521E37F84A4BDD5B06B0970CC2D2BBB715F7B82846F9A0C393914C792E6A923E2117AB805276A975AADB5261D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A60126FEB2CF05DB8A7F0F09B3397F3937F2E90B9E5B9C9B6EFEF642BC48351C46FB171B9BFA9EF17A961CE96C7E7A7CC3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B67299E231F8BD90B39AC3AE3BE0C6B6CACEF8289A2E2873D58E51E029CAFBD55E6841489AB66B5B4B9BA6E2F784660896AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B988567A88126B914D7828E2B63A6D7ED0747EC59E0E0A23CE7D8A74C1D2C2A7AFB6A29799620F00E11C33787F7DED3B30E1A22D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7690542 spake2-0.9/src/spake2/parameters/0000755000175000017500000000000014674653710016207 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/__init__.py0000644000175000017500000000000014652777131020306 0ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/all.py0000644000175000017500000000017514652777131017334 0ustar00meejahmeejahfrom .ed25519 import ParamsEd25519 from .i1024 import Params1024 from .i2048 import Params2048 from .i3072 import Params3072 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/ed25519.py0000644000175000017500000000015514652777131017560 0ustar00meejahmeejahfrom ..params import _Params from ..ed25519_group import Ed25519Group ParamsEd25519 = _Params(Ed25519Group) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/i1024.py0000644000175000017500000000026114652777131017317 0ustar00meejahmeejahfrom ..params import _Params from ..groups import I1024 # Params1024 is roughly as secure as an 80-bit symmetric key, and uses a # 1024-bit modulus. Params1024 = _Params(I1024) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/i2048.py0000644000175000017500000000021314652777131017323 0ustar00meejahmeejahfrom ..params import _Params from ..groups import I2048 # Params2048 has 112-bit security and comes from NIST. Params2048 = _Params(I2048) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/parameters/i3072.py0000644000175000017500000000016714652777131017331 0ustar00meejahmeejahfrom ..params import _Params from ..groups import I3072 # Params3072 has 128-bit security. Params3072 = _Params(I3072) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/params.py0000644000175000017500000000142014652777131015676 0ustar00meejahmeejah # M and N are defined as "randomly chosen elements of the group". It is # important that nobody knows their discrete log (if your # parameter-provider picked a secret 'haha' and told you to use # M=pow(g,haha,p), you couldn't tell that M wasn't randomly chosen, but # they could then mount an active attack against your PAKE session). S # is the same, but used for both sides of a symmetric session. # # The safe way to choose these is to hash a public string. class _Params: def __init__(self, group, M=b"M", N=b"N", S=b"symmetric"): self.group = group self.M = group.arbitrary_element(seed=M) self.N = group.arbitrary_element(seed=N) self.S = group.arbitrary_element(seed=S) self.M_str = M self.N_str = N self.S_str = S ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/spake2.py0000644000175000017500000002670514652777131015615 0ustar00meejahmeejahimport os, json from binascii import hexlify, unhexlify from hashlib import sha256 from .params import _Params from .parameters.ed25519 import ParamsEd25519 DefaultParams = ParamsEd25519 class SPAKEError(Exception): pass class OnlyCallStartOnce(SPAKEError): """start() may only be called once. Re-using a SPAKE2 instance is likely to reveal the password or the derived key.""" class OnlyCallFinishOnce(SPAKEError): """finish() may only be called once. Re-using a SPAKE2 instance is likely to reveal the password or the derived key.""" class OffSides(SPAKEError): """I received a message from someone on the same side that I'm on: I was expecting the opposite side.""" class SerializedTooEarly(SPAKEError): pass class WrongSideSerialized(SPAKEError): """You tried to unserialize data stored for the other side.""" class WrongGroupError(SPAKEError): pass class ReflectionThwarted(SPAKEError): """Someone tried to reflect our message back to us.""" SideA = b"A" SideB = b"B" SideSymmetric = b"S" # x = random(Zp) # X = scalarmult(g, x) # X* = X + scalarmult(M, int(pw)) # y = random(Zp) # Y = scalarmult(g, y) # Y* = Y + scalarmult(N, int(pw)) # KA = scalarmult(Y* + scalarmult(N, -int(pw)), x) # key = H(H(pw) + H(idA) + H(idB) + X* + Y* + KA) # KB = scalarmult(X* + scalarmult(M, -int(pw)), y) # key = H(H(pw) + H(idA) + H(idB) + X* + Y* + KB) # to serialize intermediate state, just remember x and A-vs-B. And M/N. def finalize_SPAKE2(idA, idB, X_msg, Y_msg, K_bytes, pw): transcript = b"".join([sha256(pw).digest(), sha256(idA).digest(), sha256(idB).digest(), X_msg, Y_msg, K_bytes]) key = sha256(transcript).digest() return key def finalize_SPAKE2_symmetric(idSymmetric, msg1, msg2, K_bytes, pw): # since we don't know which side is which, we must sort the messages first_msg, second_msg = sorted([msg1, msg2]) transcript = b"".join([sha256(pw).digest(), sha256(idSymmetric).digest(), first_msg, second_msg, K_bytes]) key = sha256(transcript).digest() return key class _SPAKE2_Base: "This class manages one side of a SPAKE2 key negotiation." side = None # set by the subclass def __init__(self, password, params=DefaultParams, entropy_f=os.urandom): assert isinstance(password, bytes) self.pw = password self.pw_scalar = params.group.password_to_scalar(password) assert isinstance(params, _Params), repr(params) self.params = params self.entropy_f = entropy_f self._started = False self._finished = False def start(self): if self._started: raise OnlyCallStartOnce("start() can only be called once") self._started = True g = self.params.group self.xy_scalar = g.random_scalar(self.entropy_f) self.xy_elem = g.Base.scalarmult(self.xy_scalar) self.compute_outbound_message() # Guard against both sides using the same side= by adding a side byte # to the message. This is not included in the transcript hash at the # end. outbound_side_and_message = self.side + self.outbound_message return outbound_side_and_message def compute_outbound_message(self): #message_elem = self.xy_elem + (self.my_blinding() * self.pw_scalar) pw_blinding = self.my_blinding().scalarmult(self.pw_scalar) message_elem = self.xy_elem.add(pw_blinding) self.outbound_message = message_elem.to_bytes() def finish(self, inbound_side_and_message): if self._finished: raise OnlyCallFinishOnce("finish() can only be called once") self._finished = True self.inbound_message = self._extract_message(inbound_side_and_message) g = self.params.group inbound_elem = g.bytes_to_element(self.inbound_message) if inbound_elem.to_bytes() == self.outbound_message: raise ReflectionThwarted #K_elem = (inbound_elem + (self.my_unblinding() * -self.pw_scalar) # ) * self.xy_scalar pw_unblinding = self.my_unblinding().scalarmult(-self.pw_scalar) K_elem = inbound_elem.add(pw_unblinding).scalarmult(self.xy_scalar) K_bytes = K_elem.to_bytes() key = self._finalize(K_bytes) return key def hash_params(self): # We can't really reconstruct the group from static data, but we'll # record enough of the params to confirm that we're using the same # ones upon restore. Otherwise the failure mode is silent key # disagreement. Any changes to the group or the M/N seeds should # cause this to change. g = self.params.group pieces = [g.arbitrary_element(b"").to_bytes(), g.scalar_to_bytes(g.password_to_scalar(b"")), self.params.M.to_bytes(), self.params.N.to_bytes(), ] return sha256(b"".join(pieces)).hexdigest() def serialize(self): if not self._started: raise SerializedTooEarly("call .start() before .serialize()") return json.dumps(self._serialize_to_dict()).encode("ascii") @classmethod def from_serialized(klass, data, params=DefaultParams): d = json.loads(data.decode("ascii")) return klass._deserialize_from_dict(d, params) class _SPAKE2_Asymmetric(_SPAKE2_Base): def __init__(self, password, idA=b"", idB=b"", params=DefaultParams, entropy_f=os.urandom): _SPAKE2_Base.__init__(self, password, params=params, entropy_f=entropy_f) assert isinstance(idA, bytes), repr(idA) assert isinstance(idB, bytes), repr(idB) self.idA = idA self.idB = idB def _extract_message(self, inbound_side_and_message): other_side = inbound_side_and_message[0:1] inbound_message = inbound_side_and_message[1:] if other_side not in (SideA, SideB): raise OffSides("I don't know what side they're on") if self.side == other_side: if self.side == SideA: raise OffSides("I'm A, but I got a message from A (not B).") else: raise OffSides("I'm B, but I got a message from B (not A).") return inbound_message def _finalize(self, K_bytes): return finalize_SPAKE2(self.idA, self.idB, self.X_msg(), self.Y_msg(), K_bytes, self.pw) def _serialize_to_dict(self): g = self.params.group d = {"hashed_params": self.hash_params(), "side": self.side.decode("ascii"), "idA": hexlify(self.idA).decode("ascii"), "idB": hexlify(self.idB).decode("ascii"), "password": hexlify(self.pw).decode("ascii"), "xy_scalar": hexlify(g.scalar_to_bytes(self.xy_scalar)).decode("ascii"), } return d @classmethod def _deserialize_from_dict(klass, d, params): def _should_be_unused(count): raise NotImplementedError self = klass(password=unhexlify(d["password"].encode("ascii")), idA=unhexlify(d["idA"].encode("ascii")), idB=unhexlify(d["idB"].encode("ascii")), params=params, entropy_f=_should_be_unused) if d["side"].encode("ascii") != self.side: raise WrongSideSerialized if d["hashed_params"] != self.hash_params(): err = ("SPAKE2.from_serialized() must be called with the same" "params= that were used to create the serialized data." "These are different somehow.") raise WrongGroupError(err) g = self.params.group self._started = True xy_scalar_bytes = unhexlify(d["xy_scalar"].encode("ascii")) self.xy_scalar = g.bytes_to_scalar(xy_scalar_bytes) self.xy_elem = g.Base.scalarmult(self.xy_scalar) self.compute_outbound_message() return self # applications should use SPAKE2_A and SPAKE2_B, not raw _SPAKE2_Base() class SPAKE2_A(_SPAKE2_Asymmetric): side = SideA def my_blinding(self): return self.params.M def my_unblinding(self): return self.params.N def X_msg(self): return self.outbound_message def Y_msg(self): return self.inbound_message class SPAKE2_B(_SPAKE2_Asymmetric): side = SideB def my_blinding(self): return self.params.N def my_unblinding(self): return self.params.M def X_msg(self): return self.inbound_message def Y_msg(self): return self.outbound_message class SPAKE2_Symmetric(_SPAKE2_Base): side = SideSymmetric def __init__(self, password, idSymmetric=b"", params=DefaultParams, entropy_f=os.urandom): _SPAKE2_Base.__init__(self, password, params=params, entropy_f=entropy_f) self.idSymmetric = idSymmetric def my_blinding(self): return self.params.S def my_unblinding(self): return self.params.S def _extract_message(self, inbound_side_and_message): other_side = inbound_side_and_message[0:1] inbound_message = inbound_side_and_message[1:] if other_side == SideA: raise OffSides("I'm Symmetric, but I got a message from A") if other_side == SideB: raise OffSides("I'm Symmetric, but I got a message from B") assert other_side == SideSymmetric return inbound_message def _finalize(self, K_bytes): return finalize_SPAKE2_symmetric(self.idSymmetric, self.inbound_message, self.outbound_message, K_bytes, self.pw) def hash_params(self): g = self.params.group pieces = [g.arbitrary_element(b"").to_bytes(), g.scalar_to_bytes(g.password_to_scalar(b"")), self.params.S.to_bytes(), ] return sha256(b"".join(pieces)).hexdigest() def _serialize_to_dict(self): g = self.params.group d = {"hashed_params": self.hash_params(), "side": self.side.decode("ascii"), "idS": hexlify(self.idSymmetric).decode("ascii"), "password": hexlify(self.pw).decode("ascii"), "xy_scalar": hexlify(g.scalar_to_bytes(self.xy_scalar)).decode("ascii"), } return d @classmethod def _deserialize_from_dict(klass, d, params): if d["side"].encode("ascii") != SideSymmetric: raise WrongSideSerialized def _should_be_unused(count): raise NotImplementedError self = klass(password=unhexlify(d["password"].encode("ascii")), idSymmetric=unhexlify(d["idS"].encode("ascii")), params=params, entropy_f=_should_be_unused) if d["hashed_params"] != self.hash_params(): err = ("SPAKE2.from_serialized() must be called with the same" "params= that were used to create the serialized data." "These are different somehow.") raise WrongGroupError(err) g = self.params.group self._started = True xy_scalar_bytes = unhexlify(d["xy_scalar"].encode("ascii")) self.xy_scalar = g.bytes_to_scalar(xy_scalar_bytes) self.xy_elem = g.Base.scalarmult(self.xy_scalar) self.compute_outbound_message() return self # add ECC version for smaller messages/storage # consider timing attacks # try for compatibility with Boneh's JS version ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7690542 spake2-0.9/src/spake2/test/0000755000175000017500000000000014674653710015023 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/test/__init__.py0000644000175000017500000000000014652777131017122 0ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/src/spake2/test/common.py0000644000175000017500000000142714654534712016667 0ustar00meejahmeejahfrom hashlib import sha256 from itertools import count class PRG: # this returns a callable which, when invoked with an integer N, will # return N pseudorandom bytes derived from the seed def __init__(self, seed): self.generator = self.block_generator(seed) def __call__(self, numbytes): return b"".join([next(self.generator) for i in range(numbytes)]) def block_generator(self, seed): assert isinstance(seed, type(b"")) for counter in count(): cseed = b"".join([b"prng-", str(counter).encode("ascii"), b"-", seed]) block = sha256(cseed).digest() for i in range(len(block)): yield block[i:i+1] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/test/myhkdf.py0000644000175000017500000001447014652777131016665 0ustar00meejahmeejahfrom hashlib import sha256, sha1 from binascii import unhexlify import hmac def HKDF(IKM, dkLen, salt=None, info=b"", digest=sha256, _test_expected_PRK=None): assert isinstance(IKM, bytes) assert isinstance(salt, (bytes,type(None))) assert isinstance(info, bytes) hlen = len(digest(b"").digest()) assert dkLen <= hlen*255 if salt is None: salt = b"\x00"*hlen # extract PRK = hmac.new(salt, IKM, digest).digest() if _test_expected_PRK and _test_expected_PRK != PRK: raise ValueError("test failed") # expand blocks = [] counter = 1 t = b"" while hlen*len(blocks) < dkLen: t = hmac.new(PRK, t+info+unhexlify("%02x"%counter), digest).digest() blocks.append(t) counter += 1 return b"".join(blocks)[:dkLen] def power_on_self_test(): from binascii import hexlify, unhexlify def _test(IKM, salt, info, L, PRK, OKM, digest=sha256): def remove_prefix(prefix, s): assert s.startswith(prefix) return s[len(prefix):] ikm = unhexlify(remove_prefix("0x", IKM)) salt = unhexlify(remove_prefix("0x", salt)) info = unhexlify(remove_prefix("0x", info)) prk = unhexlify(remove_prefix("0x", PRK)) okm = unhexlify(remove_prefix("0x", OKM)) assert isinstance(ikm, bytes) assert isinstance(salt, bytes) assert isinstance(info, bytes) assert isinstance(prk, bytes) assert isinstance(okm, bytes) if digest is None: out = HKDF(ikm, L, salt, info, _test_expected_PRK=prk) else: out = HKDF(ikm, L, salt, info, digest=digest, _test_expected_PRK=prk) if okm != out: raise ValueError("got %s, expected %s" % (hexlify(out), hexlify(okm))) # test vectors from RFC5869 _test(IKM="0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt="0x000102030405060708090a0b0c", info="0xf0f1f2f3f4f5f6f7f8f9", L=42, PRK=("0x077709362c2e32df0ddc3f0dc47bba63" "90b6c73bb50f9c3122ec844ad7c2b3e5"), OKM=("0x3cb25f25faacd57a90434f64d0362f2a" "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" "34007208d5b887185865")) _test(IKM=("0x000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f" "303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f"), salt=("0x606162636465666768696a6b6c6d6e6f" "707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"), info=("0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), L=82, PRK=("0x06a6b88c5853361a06104c9ceb35b45c" "ef760014904671014a193f40c15fc244"), OKM=("0xb11e398dc80327a1c8e7f78c596a4934" "4f012eda2d4efad8a050cc4c19afa97c" "59045a99cac7827271cb41c65e590e09" "da3275600c2f09b8367793a9aca3db71" "cc30c58179ec3e87c14c01d5c1f3434f" "1d87")) _test(IKM="0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt="0x", info="0x", L=42, PRK=("0x19ef24a32c717b167f33a91d6f648bdf" "96596776afdb6377ac434c1c293ccb04"), OKM=("0x8da4e775a563c18f715f802a063c5a31" "b8a11f5c5ee1879ec3454e5f3c738d2d" "9d201395faa4b61a96c8")) _test(digest=sha1, IKM="0x0b0b0b0b0b0b0b0b0b0b0b", salt="0x000102030405060708090a0b0c", info="0xf0f1f2f3f4f5f6f7f8f9", L=42, PRK="0x9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243", OKM=("0x085a01ea1b10f36933068b56efa5ad81" "a4f14b822f5b091568a9cdd4f155fda2" "c22e422478d305f3f896")) _test(digest=sha1, IKM=("0x000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f" "303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f"), salt=("0x606162636465666768696a6b6c6d6e6f" "707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"), info=("0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), L=82, PRK="0x8adae09a2a307059478d309b26c4115a224cfaf6", OKM=("0x0bd770a74d1160f7c9f12cd5912a06eb" "ff6adcae899d92191fe4305673ba2ffe" "8fa3f1a4e5ad79f3f334b3b202b2173c" "486ea37ce3d397ed034c7f9dfeb15c5e" "927336d0441f4c4300e2cff0d0900b52" "d3b4")) _test(digest=sha1, IKM="0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt="0x", info="0x", L=42, PRK="0xda8c8a73c7fa77288ec6f5e7c297786aa0d32d01", OKM=("0x0ac1af7002b3d761d1e55298da9d0506" "b9ae52057220a306e07b6b87e8df21d0" "ea00033de03984d34918")) _test(digest=sha1, IKM="0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", salt="0x", info="0x", L=42, PRK="0x2adccada18779e7c2077ad2eb19d3f3e731385dd", OKM=("0x2c91117204d745f3500d636a62f64f0a" "b3bae548aa53d423b0d1f27ebba6f5e5" "673a081d70cce7acfc48")) # finally test that HKDF() without a digest= uses SHA256 _test(digest=None, IKM="0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt="0x", info="0x", L=42, PRK=("0x19ef24a32c717b167f33a91d6f648bdf" "96596776afdb6377ac434c1c293ccb04"), OKM=("0x8da4e775a563c18f715f802a063c5a31" "b8a11f5c5ee1879ec3454e5f3c738d2d" "9d201395faa4b61a96c8")) #print "all test passed" power_on_self_test() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722554584.0 spake2-0.9/src/spake2/test/test_compat.py0000644000175000017500000003633514653014330017713 0ustar00meejahmeejahimport unittest from binascii import hexlify, unhexlify from hashlib import sha256 from cryptography.hazmat.primitives.kdf import hkdf from cryptography.hazmat.primitives import hashes from .myhkdf import HKDF as myHKDF from spake2 import groups, ed25519_group from spake2.spake2 import (SPAKE2_A, SPAKE2_B, SPAKE2_Symmetric, finalize_SPAKE2, finalize_SPAKE2_symmetric) from .common import PRG class TestPRG(unittest.TestCase): def test_basic(self): PRGA = PRG(b"A") dataA = PRGA(16) self.assertEqual(hexlify(dataA), b"c1d59d78903e9d7874d9064e12d36c58") PRGB = PRG(b"B") dataB = PRGB(16) self.assertEqual(hexlify(dataB), b"2af6d4b843a9e6cd1d185eb5de870f77") class SPAKE2(unittest.TestCase): """Make sure we know when an incompatible change has landed""" def test_asymmetric(self): PRGA = PRG(b"A") PRGB = PRG(b"B") pw = b"password" sA,sB = SPAKE2_A(pw, entropy_f=PRGA), SPAKE2_B(pw, entropy_f=PRGB) m1A,m1B = sA.start(), sB.start() self.assertEqual(hexlify(m1A), b"416fc960df73c9cf8ed7198b0c9534e2e96a5984bfc5edc023fd24dacf371f2af9") self.assertEqual(hexlify(m1B), b"42354e97b88406922b1df4bea1d7870f17aed3dba7c720b313edae315b00959309") # peek at the scalars, since it ought to be stable, and other # implementations that want to use this as a test vector might start # with the scalar, rather than duplicating our deterministic RNG self.assertEqual(sA.pw_scalar, 3515301705789368674385125653994241092664323519848410154015274772661223168839) self.assertEqual(sB.pw_scalar, 3515301705789368674385125653994241092664323519848410154015274772661223168839) self.assertEqual(sA.xy_scalar, 2611694063369306139794446498317402240796898290761098242657700742213257926693) self.assertEqual(sB.xy_scalar, 7002393159576182977806091886122272758628412261510164356026361256515836884383) kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), b"a480bca13fa04464bb644f10e340125e96c9494f7399fef7c2bda67eb0fdf06d") self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) def test_symmetric(self): PRG1 = PRG(b"1") PRG2 = PRG(b"2") pw = b"password" s1 = SPAKE2_Symmetric(pw, entropy_f=PRG1) s2 = SPAKE2_Symmetric(pw, entropy_f=PRG2) m11,m12 = s1.start(), s2.start() self.assertEqual(hexlify(m11), b"5308f692d38c4034ad6e2e1054c469ca1dbe990bcaec4bbd3ad78c7d968eadd0b3") self.assertEqual(hexlify(m12), b"5329e2d5f9b7a53e609204115c6458921b0bb27419ce82a27679fc5961002897df") k1,k2 = s1.finish(m12), s2.finish(m11) self.assertEqual(hexlify(k1), b"9c4fccaa3f0740615cee6fd10ed5d3a311b91b5bdc65f53e4ea7cb2fe8aa96eb") self.assertEqual(hexlify(k1), hexlify(k2)) self.assertEqual(len(k1), len(sha256().digest())) GROUPS = { "I1024": groups.I1024, "I2048": groups.I2048, "I3072": groups.I3072, "Ed25519": ed25519_group.Ed25519Group, } # These vectors exercise the password-to-scalar conversion step. The vectors # should be all JSON, so in the future we can cut-and-paste them into other # implementations for compatibility testing. # hexlify(b"pw") == "7077" # "0001feff" is meant to test non-ASCII passwords P2S_TEST_VECTORS = [ {"group": "I1024", "pw_hex": "7077", "bytes_hex": "28f73d0d793a38cb21694b751cd0affb181474be"}, {"group": "I1024", "pw_hex": "0001feff", "bytes_hex": "37044fd99e0499af9b263a21e13dd737b7b022bf"}, {"group": "I2048", "pw_hex": "7077", "bytes_hex": "56db566c2740f46557d8c3695a5eb6fb736797b63f98c58931267ae6"}, {"group": "I2048", "pw_hex": "0001feff", "bytes_hex": "058062c322379afd9eba83c084b8cf5b23aa9f69aeb659bac912222a"}, {"group": "I3072", "pw_hex": "7077", "bytes_hex": "49454ea9faa9e70213573c8f271163d6d430b994fdba8af482478c3a3ae43f04"}, {"group": "I3072", "pw_hex": "0001feff", "bytes_hex": "a1b0ffda72070f4d1bc565933904fb92307b40bc2d32ad1394eea3598128ba9a"}, {"group": "Ed25519", "pw_hex": "7077", "bytes_hex": "cf090b60384cb818b12c8d972dfbaf910c0c7295c5cfe560e508f5f062f3960f"}, {"group": "Ed25519", "pw_hex": "0001feff", "bytes_hex": "e86622bb57ea0f6f9f963354f2973a43a9e981901a478e6478682374441b0c04"}, ] class PasswordToScalar(unittest.TestCase): def test_vectors(self): for vector in P2S_TEST_VECTORS: group = GROUPS[vector["group"]] pw = unhexlify(vector["pw_hex"].encode("ascii")) scalar = group.password_to_scalar(pw) scalar_bytes = group.scalar_to_bytes(scalar) self.assertEqual(len(scalar_bytes), group.scalar_size_bytes) #print(hexlify(scalar_bytes)) expected = vector["bytes_hex"].encode("ascii") self.assertEqual(hexlify(scalar_bytes), expected, vector) # check for endian issues, number-of-leading-zeros S2B_TEST_VECTORS = [ {"group": "I1024", "scalar": 1, "bytes_hex": "0000000000000000000000000000000000000001"}, {"group": "I1024", "scalar": 2, "bytes_hex": "0000000000000000000000000000000000000002"}, {"group": "I2048", "scalar": 1, "bytes_hex": "00000000000000000000000000000000000000000000000000000001"}, {"group": "I2048", "scalar": 2, "bytes_hex": "00000000000000000000000000000000000000000000000000000002"}, {"group": "I3072", "scalar": 1, "bytes_hex": "0000000000000000000000000000000000000000000000000000000000000001"}, {"group": "I3072", "scalar": 2, "bytes_hex": "0000000000000000000000000000000000000000000000000000000000000002"}, {"group": "Ed25519", "scalar": 1, "bytes_hex": "0100000000000000000000000000000000000000000000000000000000000000"}, {"group": "Ed25519", "scalar": 2, "bytes_hex": "0200000000000000000000000000000000000000000000000000000000000000"}, ] class ScalarToBytes(unittest.TestCase): def test_vectors(self): for vector in S2B_TEST_VECTORS: group = GROUPS[vector["group"]] scalar = vector["scalar"] scalar_bytes = group.scalar_to_bytes(scalar) #print(hexlify(scalar_bytes)) expected = vector["bytes_hex"].encode("ascii") self.assertEqual(hexlify(scalar_bytes), expected, vector) AE_TEST_VECTORS = [ {"group": "I1024", "seed_hex": "41", "element_hex": "933084f15747174af82ece8ba242f83e38db4a64b8887f9ef275c318ae0b0f4338e9fafc6ff601d1b0f8b3dfe63bbaf774117c820abb16f5d054833e897647813083d2bed14c88d54717e2b5e9d161bc87fd0265c2d10002a6ac14fadf8da81fd3710c1d179c7247ffecc148f764d0a19c9319c698aa553dd825ae4112e6128d"}, {"group": "I1024", "seed_hex": "42", "element_hex": "4ac273e831a27542a1a9017d896dc32128e8e19aa726d261ae0214d7860a69958d82ad1525a8fa16c78a7b66cf52a977aefd6f4d99fb5aa26b99b0d1d9e8a8079ebd272ac78ea574df52dccb454fa253a9fad9621f8edf824b2235e02b129d357b8d3c10026357734dd4c98f018fc9ff15978679347e9b6e0a3bbd1f5402a679"}, {"group": "I2048", "seed_hex": "41", "element_hex": "bb192daef4e0ab05f5e908a3f3ddefedfc8388b4a4daae894a23125322fd24c95606b85fb7d4a041c9f312d890a057c8d3587bedfe7843d997e78140fdd530d0cb2bb2738f9ec0befbb09a863f48a5ea3b503300db65a8666e55ba875640f6db8c3cfd2d55ef3b4c67bb51d28d4dd4ba3fd443e655870fa54dfa1ce7b4b493d48c692c1c46977eeac82ea5e87afe72db3d778112a689ad0275135cd0fc8378139d700e03cfd2f7bfc0f142b6f4a5f5ecd12e09ea960e91fe3c10db637770f188fb9cb3004fda24ef7957bb7f8890fd12b77b8ade48a95620dc3442aa717b9d04dcec7ffec8a33cbf51735ab4acb1520f82e03d0b465c9c9a23f75e32f6b58208"}, {"group": "I2048", "seed_hex": "42", "element_hex": "a4964933a4dd3e8b5e172e5a48e01dc346d046b4d960004e0802f2da0636d081f21a9975f470480874c36dcd2e83f41cdeeb192659b8f03c4c7339eca7861672cab1f0ed765de48d8ac68cdeb2cd873b1415a73bb03eef497b221ff1a5635e6bcb96de1a444d09f986e964e2e842fb010712c261678d2ac8adb35f30986f90bda797528e32cefcfbb0733a15d59758e1021a3f13ff117e2519ba06ceeff3956212ddf07c1516ae68499c89d7c373c586119948e2b05c518d0a736baee46ffabd6756d354d38cb642b53ca7778eb3786b035163e76a868828dc71b28a63b6a24c11e9e280e5bf147f4dc20cb2cbd7fb7a961a2b0983119285d6dd6988554cb45b"}, {"group": "I3072", "seed_hex": "41", "element_hex": "5459e7c980132e3002b49d6756b06139ae80b4ec7183607d9534f9f0fcb7a80cdd8db3707feddca4132ef0ea2733cd09b715092dfd330da941454cc3230188b24453878223ab6498c99a64384cf6d14f9f57213aac2fb95d7a77ccb3304e9345eb09d59dea807ff9644ffb83c5b33eff26876b5261261295e1b732b77ea26b745934499d4120d7d345edee9d1d004eda574d71884436ffe953ab7d857cebad2b5b062814c649256a20fcf1b6957c0513fd7fc3ac21edd335a368812a31daa654eec5c320d235357e642eba0c3964e1d3e40cdd913da23a88ceb8272ab920e939026348580999aceef6dbbd0babec1846be0b35b5134f8420fabbddec2ad0188dbff920e9f839208b0140f240dd24890f50b89a09899f50f26422b28fa99cefb16b9b2d6d08342be802f2d84861475ee6a47d940e681cd735c42fd124403c3ce78c5c90be8203f8497c15f07f16553f31a155ae7b5eb4b5cc93f52ff8d095f56d5930c5ff9944589d89f0e153d61b6ecb00649e716f0cb95fe8280ebb282c9f3a"}, {"group": "I3072", "seed_hex": "42", "element_hex": "69e247a5284cb5683fa48c3f60ce7b83857b0f67db156d9b120a7338a52514f223d319c3a39dc81169c4a0efdcc03742a0dd08d7c1e177f8c83c19d4a1fb7955b6572051d73b0ca241a48477194fb84020e917081dc2e04ab474f6b018f68ef797cd2d2403049c6af7f6583faf19651f6e263f6a8ddf3a23165cf1703ead9dfaf3d59f6520906fd13479aa72f12777a9ea469518d4159cc832b1f39ce2b84153e3a2bc3940cdd07ee6353e7f7867bf0cb8634b54a33967958f709e5429e992eb76dfb49341530916d237cb1d2f42412443f62beeb6042c270af3633ea9561dd0cde544e21cb8b11f550f44020d3c744faa3cfc153657512000d2c13cdf53fd950c79e39cd74a0efd39c5a6f7f835e9287fbaf031c120e657ae1eeb29800e049d97517772c8dd504e0b1a124abb7b3592d1434caa0e786f01b673d19548b9e6498782b83962a5fffc389d6c4c6afe618ce5c1e9fe479e7dfef9777c62de43a657bff65218a050826bdc3ae3ba978a3fc018cc5413008b9fd7903a62a0758d51f1"}, {"group": "Ed25519", "seed_hex": "41", "element_hex": "4637592ae2914247de5804be805867266ccac99c635df8077dcdc1d72becf354"}, {"group": "Ed25519", "seed_hex": "42", "element_hex": "88228ee4046ba5d5fa2f23a0480a99efb1a9554ce50153d69330928215d50775"}, ] class ArbitraryElement(unittest.TestCase): def test_vectors(self): for vector in AE_TEST_VECTORS: group = GROUPS[vector["group"]] seed = unhexlify(vector["seed_hex"].encode("ascii")) elem = group.arbitrary_element(seed) elem_bytes = elem.to_bytes() self.assertEqual(len(elem_bytes), group.element_size_bytes) #print(hexlify(elem_bytes)) expected = vector["element_hex"].encode("ascii") self.assertEqual(hexlify(elem_bytes), expected, vector) # test vectors from RFC5869 HKDF_TEST_VECTORS = [ { "IKM": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "salt": "000102030405060708090a0b0c", "info": "f0f1f2f3f4f5f6f7f8f9", "L": 42, "PRK": "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", "OKM": "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865" }, { "IKM": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", "salt": "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "info": "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "L": 82, "PRK": "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244", "OKM": "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87" }, { "IKM": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "salt": "", "info": "", "L": 42, "PRK": "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04", "OKM": "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8" }, ] # some additional short vectors. Note that "salt" is zero-padded to length of # the hash (and hashed down if longer), so e.g. salt="", salt="00", and # salt="0000" all give the same results. HKDF_TEST_VECTORS += [ {"salt": "", "IKM": "01", "info": "02", "L": 4, "OKM": "f4a855e4"}, {"salt": "00", "IKM": "01", "info": "02", "L": 4, "OKM": "f4a855e4"}, {"salt": "", "IKM": "01", "info": "", "L": 4, "OKM": "be7e83fb"}, {"salt": "00", "IKM": "01", "info": "", "L": 4, "OKM": "be7e83fb"}, {"salt": "01", "IKM": "01", "info": "", "L": 4, "OKM": "f0f7dcf9"}, {"salt": "01", "IKM": "01", "info": "", "L": 8, "OKM": "f0f7dcf9fe847ae5"}, {"salt": "01", "IKM": "01", "info": "", "L": 16, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52"}, {"salt": "01", "IKM": "01", "info": "", "L": 31, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52bf6a4a45810f5d819ec3932eaa6012"}, {"salt": "01", "IKM": "01", "info": "", "L": 32, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52bf6a4a45810f5d819ec3932eaa601290"}, {"salt": "01", "IKM": "01", "info": "", "L": 33, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52bf6a4a45810f5d819ec3932eaa60129072"}, {"salt": "01", "IKM": "01", "info": "", "L": 64, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52bf6a4a45810f5d819ec3932eaa60129072a91afe92cffe2f2327b65ba4e2b2b6b51ed34363c9c4cca58ae7409209b97d"}, {"salt": "01", "IKM": "01", "info": "", "L": 65, "OKM": "f0f7dcf9fe847ae58a24e82b13737c52bf6a4a45810f5d819ec3932eaa60129072a91afe92cffe2f2327b65ba4e2b2b6b51ed34363c9c4cca58ae7409209b97d76"}, {"salt": "00", "IKM": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "info": "", "L": 4, "OKM": "37ad2910"}, ] class TestHKDF(unittest.TestCase): def test_vectors(self): for vector in HKDF_TEST_VECTORS: salt = unhexlify(vector["salt"].encode("ascii")) IKM = unhexlify(vector["IKM"].encode("ascii")) info = unhexlify(vector["info"].encode("ascii")) h = hkdf.HKDF(algorithm=hashes.SHA256(), length=vector["L"], salt=salt, info=info) digest = h.derive(IKM) self.assertEqual(digest, myHKDF(IKM, vector["L"], salt, info)) #print(hexlify(digest)) expected = vector["OKM"].encode("ascii") self.assertEqual(hexlify(digest), expected, vector) class Finalize(unittest.TestCase): def test_asymmetric(self): key = finalize_SPAKE2(b"idA", b"idB", b"X_msg", b"Y_msg", b"K_bytes", b"pw") self.assertEqual(hexlify(key), b"aa02a627537543399bb1b4b430646480b6d36ab5c44842e738c8f78694d8afac") def test_symmetric(self): key1 = finalize_SPAKE2_symmetric(b"idSymmetric", b"X_msg", b"Y_msg", b"K_bytes", b"pw") self.assertEqual(hexlify(key1), b"330a7ce7bb010fea7dae7e15b2261315403ab5dc269e461f6eb1cc6566620790") key2 = finalize_SPAKE2_symmetric(b"idSymmetric", b"Y_msg", b"X_msg", b"K_bytes", b"pw") self.assertEqual(hexlify(key1), hexlify(key2)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/test/test_group.py0000644000175000017500000001624314652777131017576 0ustar00meejahmeejahimport unittest from binascii import hexlify from hashlib import sha256 from spake2 import groups, ed25519_group from spake2.parameters.i1024 import Params1024 from spake2.parameters.i2048 import Params2048 from spake2.parameters.i3072 import Params3072 from spake2.parameters.ed25519 import ParamsEd25519 from spake2.spake2 import SPAKE2_A, SPAKE2_B from .common import PRG ALL_INTEGER_GROUPS = [groups.I1024, groups.I2048, groups.I3072] ALL_GROUPS = ALL_INTEGER_GROUPS + [ed25519_group.Ed25519Group] ALL_INTEGER_PARAMS = [Params1024, Params2048, Params3072] ALL_PARAMS = ALL_INTEGER_PARAMS + [ParamsEd25519] def random_element(g, entropy_f): s = g.random_scalar(entropy_f) return s, g.Base.scalarmult(s) class Group(unittest.TestCase): def assertElementsEqual(self, e1, e2, msg=None): self.assertEqual(hexlify(e1.to_bytes()), hexlify(e2.to_bytes()), msg) def assertElementsNotEqual(self, e1, e2, msg=None): self.assertNotEqual(hexlify(e1.to_bytes()), hexlify(e2.to_bytes()), msg) def test_basic(self): for g in ALL_GROUPS: fr = PRG(b"0") i = g.random_scalar(entropy_f=fr) self.assertTrue(0 <= i < g.order()) b = g.scalar_to_bytes(i) self.assertEqual(len(b), g.scalar_size_bytes) self.assertEqual(i, g.bytes_to_scalar(b)) e = g.Base.scalarmult(i) self.assertEqual(len(e.to_bytes()), g.element_size_bytes) e = g.arbitrary_element(b"") self.assertEqual(len(e.to_bytes()), g.element_size_bytes) self.assertElementsEqual(e, g.bytes_to_element(e.to_bytes())) def test_math(self): for g in ALL_GROUPS: sb = g.Base.scalarmult e0 = sb(0) self.assertElementsEqual(e0, g.Zero) e1 = sb(1) e2 = sb(2) self.assertElementsEqual(e1.add(e0), e1) self.assertElementsEqual(e1.add(e1), e1.scalarmult(2)) self.assertElementsEqual(e1.scalarmult(2), e2) self.assertElementsEqual(e1.add(e2), e2.add(e1)) e_m1 = sb(g.order()-1) self.assertElementsEqual(e_m1, sb(-1)) self.assertElementsEqual(e_m1.add(e1), e0) e3 = sb(3) e4 = sb(4) e5 = sb(5) self.assertElementsEqual(e2.add(e3), e1.add(e4)) #self.assertElementsEqual(e5 - e3, e2) self.assertElementsEqual(e1.scalarmult(g.order()), e0) self.assertElementsEqual(e2.scalarmult(g.order()), e0) self.assertElementsEqual(e3.scalarmult(g.order()), e0) self.assertElementsEqual(e4.scalarmult(g.order()), e0) self.assertElementsEqual(e5.scalarmult(g.order()), e0) def test_bad_math(self): for g in ALL_GROUPS: base = g.Base # you cannot multiply two group elements together, only add them self.assertRaises(TypeError, lambda: base.scalarmult(base)) # you cannot add group elements to scalars, you can only multiply # group elements *by* scalars self.assertRaises(TypeError, lambda: base.add(1)) self.assertRaises(TypeError, lambda: base.add(-1)) def test_from_bytes(self): for g in ALL_GROUPS: fr = PRG(b"0") e = g.Base self.assertElementsEqual(g.bytes_to_element(e.to_bytes()), e) e = g.Base.scalarmult(2) self.assertElementsEqual(g.bytes_to_element(e.to_bytes()), e) e = g.Base.scalarmult(g.random_scalar(fr)) self.assertElementsEqual(g.bytes_to_element(e.to_bytes()), e) self.assertFalse(groups.I1024._is_member(groups.I2048.Zero)) for g in ALL_INTEGER_GROUPS: # we must bypass the normal API to create an element that's # marked as being of the right group, but the actual number is # not in the subgroup s = groups.number_to_bytes(0, g.p) self.assertRaises(ValueError, g.bytes_to_element, s) s = groups.number_to_bytes(2, g.p) self.assertRaises(ValueError, g.bytes_to_element, s) def test_arbitrary_element(self): for g in ALL_GROUPS: gx = g.arbitrary_element(b"") self.assertElementsEqual(gx.scalarmult(-2), gx.scalarmult(2).scalarmult(-1)) gy = g.arbitrary_element(b"2") self.assertElementsNotEqual(gx, gy) def test_blinding(self): for g in ALL_GROUPS: fr = PRG(b"0") _, pubkey = random_element(g, fr) _, U = random_element(g, fr) pw = g.random_scalar(fr) # X+U*pw -U*pw == X blinding_factor = U.scalarmult(pw) blinded_pubkey = pubkey.add(blinding_factor) inverse_pw = (-pw) % g.order() inverse_blinding_factor = U.scalarmult(inverse_pw) self.assertElementsEqual(inverse_blinding_factor, U.scalarmult(-pw)) self.assertElementsEqual(U.scalarmult(-pw), U.scalarmult(pw).scalarmult(-1)) self.assertElementsEqual(inverse_blinding_factor, blinding_factor.scalarmult(-1)) unblinded_pubkey = blinded_pubkey.add(inverse_blinding_factor) self.assertElementsEqual(pubkey, unblinded_pubkey) def test_password(self): for g in ALL_GROUPS: i = g.password_to_scalar(b"") self.assertTrue(0 <= i < g.order()) def test_math_trivial(self): g = I23 e1 = g.Base.scalarmult(1) e2 = g.Base.scalarmult(2) e3 = g.Base.scalarmult(3) e4 = g.Base.scalarmult(4) e5 = g.Base.scalarmult(5) e6 = g.Base.scalarmult(6) self.assertEqual([e1._e, e2._e, e3._e, e4._e, e5._e, e6._e], [2, 4, 8, 16, 9, 18]) self.assertElementsEqual(e1.add(e1), e1.scalarmult(2)) self.assertElementsEqual(e1.scalarmult(2), e2) self.assertElementsEqual(e1.add(e2), e2.add(e1)) self.assertElementsEqual(e2.add(e3), e1.add(e4)) I23 = groups.IntegerGroup(p=23, q=11, g=2) class Parameters(unittest.TestCase): def test_params(self): for p in ALL_PARAMS: pw = b"password" sA,sB = SPAKE2_A(pw, params=p), SPAKE2_B(pw, params=p) m1A,m1B = sA.start(), sB.start() #print len(json.dumps(m1A)) kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) sA,sB = SPAKE2_A(pw, params=p), SPAKE2_B(b"passwerd", params=p) m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertNotEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) self.assertEqual(len(kB), len(sha256().digest())) def test_default_is_ed25519(self): pw = b"password" sA,sB = SPAKE2_A(pw, params=ParamsEd25519), SPAKE2_B(pw) m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/test/test_spake2.py0000644000175000017500000001663214652777131017631 0ustar00meejahmeejah import unittest from spake2 import spake2 from spake2.parameters.i1024 import Params1024 from spake2.parameters.i3072 import Params3072 from spake2.spake2 import SPAKE2_A, SPAKE2_B, SPAKE2_Symmetric from binascii import hexlify from hashlib import sha256 from .common import PRG class Basic(unittest.TestCase): def test_success(self): pw = b"password" sA,sB = SPAKE2_A(pw), SPAKE2_B(pw) m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) def test_success_id(self): pw = b"password" sA = SPAKE2_A(pw, idA=b"alice", idB=b"bob") sB = SPAKE2_B(pw, idA=b"alice", idB=b"bob") m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) def test_failure_wrong_password(self): pw = b"password" sA,sB = SPAKE2_A(pw), SPAKE2_B(b"passwerd") m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertNotEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) self.assertEqual(len(kB), len(sha256().digest())) def test_failure_wrong_id(self): pw = b"password" sA = SPAKE2_A(pw, idA=b"alice", idB=b"bob") sB = SPAKE2_B(pw, idA=b"not-alice", idB=b"bob") m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertNotEqual(hexlify(kA), hexlify(kB)) def test_failure_swapped_id(self): pw = b"password" sA = SPAKE2_A(pw, idA=b"alice", idB=b"bob") sB = SPAKE2_B(pw, idA=b"bob", idB=b"alice") m1A,m1B = sA.start(), sB.start() kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertNotEqual(hexlify(kA), hexlify(kB)) def test_reflect(self): pw = b"password" s1 = SPAKE2_A(pw) m1 = s1.start() reflected = b"B" + m1[1:] self.assertRaises(spake2.ReflectionThwarted, s1.finish, reflected) class OtherEntropy(unittest.TestCase): def test_entropy(self): fr = PRG(b"seed") pw = b"password" sA,sB = SPAKE2_A(pw, entropy_f=fr), SPAKE2_B(pw, entropy_f=fr) m1A1,m1B1 = sA.start(), sB.start() kA1,kB1 = sA.finish(m1B1), sB.finish(m1A1) self.assertEqual(hexlify(kA1), hexlify(kB1)) # run it again with the same entropy stream: all messages should be # identical fr = PRG(b"seed") sA,sB = SPAKE2_A(pw, entropy_f=fr), SPAKE2_B(pw, entropy_f=fr) m1A2,m1B2 = sA.start(), sB.start() kA2,kB2 = sA.finish(m1B2), sB.finish(m1A2) self.assertEqual(hexlify(kA2), hexlify(kB2)) self.assertEqual(m1A1, m1A2) self.assertEqual(m1B1, m1B2) self.assertEqual(kA1, kA2) self.assertEqual(kB1, kB2) class Serialize(unittest.TestCase): def test_serialize(self): pw = b"password" sA,sB = SPAKE2_A(pw), SPAKE2_B(pw) self.assertRaises(spake2.SerializedTooEarly, sA.serialize) m1A,m1B = sA.start(), sB.start() sA = SPAKE2_A.from_serialized(sA.serialize()) kA,kB = sA.finish(m1B), sB.finish(m1A) self.assertEqual(hexlify(kA), hexlify(kB)) self.assertEqual(len(kA), len(sha256().digest())) class Symmetric(unittest.TestCase): def test_success(self): pw = b"password" s1,s2 = SPAKE2_Symmetric(pw), SPAKE2_Symmetric(pw) m1,m2 = s1.start(), s2.start() k1,k2 = s1.finish(m2), s2.finish(m1) self.assertEqual(hexlify(k1), hexlify(k2)) def test_success_id(self): pw = b"password" s1 = SPAKE2_Symmetric(pw, idSymmetric=b"sym") s2 = SPAKE2_Symmetric(pw, idSymmetric=b"sym") m1,m2 = s1.start(), s2.start() k1,k2 = s1.finish(m2), s2.finish(m1) self.assertEqual(hexlify(k1), hexlify(k2)) def test_failure_wrong_password(self): s1,s2 = SPAKE2_Symmetric(b"password"), SPAKE2_Symmetric(b"wrong") m1,m2 = s1.start(), s2.start() k1,k2 = s1.finish(m2), s2.finish(m1) self.assertNotEqual(hexlify(k1), hexlify(k2)) def test_failure_wrong_id(self): pw = b"password" s1 = SPAKE2_Symmetric(pw, idSymmetric=b"sym") s2 = SPAKE2_Symmetric(pw, idSymmetric=b"not-sym") m1,m2 = s1.start(), s2.start() k1,k2 = s1.finish(m2), s2.finish(m1) self.assertNotEqual(hexlify(k1), hexlify(k2)) def test_serialize(self): pw = b"password" s1,s2 = SPAKE2_Symmetric(pw), SPAKE2_Symmetric(pw) m1,m2 = s1.start(), s2.start() s1 = SPAKE2_Symmetric.from_serialized(s1.serialize()) k1,k2 = s1.finish(m2), s2.finish(m1) self.assertEqual(hexlify(k1), hexlify(k2)) def test_reflect(self): pw = b"password" s1 = SPAKE2_Symmetric(pw) m1 = s1.start() # reflect Alice's message back to her self.assertRaises(spake2.ReflectionThwarted, s1.finish, m1) class Errors(unittest.TestCase): def test_start_twice(self): s = SPAKE2_A(b"password") s.start() self.assertRaises(spake2.OnlyCallStartOnce, s.start) def test_finish_twice(self): pw = b"password" sA,sB = SPAKE2_A(pw), SPAKE2_B(pw) sA.start() msg = sB.start() sA.finish(msg) self.assertRaises(spake2.OnlyCallFinishOnce, sA.finish, msg) def test_wrong_side(self): pw = b"password" sA1,sA2 = SPAKE2_A(pw), SPAKE2_A(pw) sA1.start() msgA = sA2.start() self.assertRaises(spake2.OffSides, sA1.finish, msgA) sB1,sB2 = SPAKE2_B(pw), SPAKE2_B(pw) sB1.start() msgB = sB2.start() self.assertRaises(spake2.OffSides, sB1.finish, msgB) self.assertRaises(spake2.OffSides, sA2.finish, b"C"+msgB) sS = SPAKE2_Symmetric(pw) sS.start() self.assertRaises(spake2.OffSides, sS.finish, msgA) sS = SPAKE2_Symmetric(pw) sS.start() self.assertRaises(spake2.OffSides, sS.finish, msgB) def test_unserialize_wrong(self): s = SPAKE2_A(b"password", params=Params1024) s.start() data = s.serialize() SPAKE2_A.from_serialized(data, params=Params1024) # this is ok self.assertRaises(spake2.WrongGroupError, SPAKE2_A.from_serialized, data) # default is P2048 self.assertRaises(spake2.WrongGroupError, SPAKE2_A.from_serialized, data, params=Params3072) self.assertRaises(spake2.WrongSideSerialized, SPAKE2_B.from_serialized, data, params=Params1024) ss = SPAKE2_Symmetric(b"password", params=Params1024) ss.start() sdata = ss.serialize() SPAKE2_Symmetric.from_serialized(sdata, params=Params1024) # ok self.assertRaises(spake2.WrongGroupError, # default is P2048 SPAKE2_Symmetric.from_serialized, sdata) self.assertRaises(spake2.WrongGroupError, SPAKE2_Symmetric.from_serialized, sdata, params=Params3072) self.assertRaises(spake2.WrongSideSerialized, SPAKE2_Symmetric.from_serialized, data, # from A params=Params1024) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722547801.0 spake2-0.9/src/spake2/test/test_utils.py0000644000175000017500000001014314652777131017573 0ustar00meejahmeejahimport unittest from spake2 import util from .common import PRG class Utils(unittest.TestCase): def test_binsize(self): def sizebb(maxval): num_bits = util.size_bits(maxval) num_bytes = util.size_bytes(maxval) return (num_bytes, num_bits) self.assertEqual(sizebb(0x0f), (1, 4)) self.assertEqual(sizebb(0x1f), (1, 5)) self.assertEqual(sizebb(0x10), (1, 5)) self.assertEqual(sizebb(0xff), (1, 8)) self.assertEqual(sizebb(0x100), (2, 9)) self.assertEqual(sizebb(0x101), (2, 9)) self.assertEqual(sizebb(0x1fe), (2, 9)) self.assertEqual(sizebb(0x1ff), (2, 9)) self.assertEqual(sizebb(2**255-19), (32, 255)) def test_number_to_bytes(self): n2b = util.number_to_bytes self.assertEqual(n2b(0x00, 0xff), b"\x00") self.assertEqual(n2b(0x01, 0xff), b"\x01") self.assertEqual(n2b(0xff, 0xff), b"\xff") self.assertEqual(n2b(0x100, 0xffff), b"\x01\x00") self.assertEqual(n2b(0x101, 0xffff), b"\x01\x01") self.assertEqual(n2b(0x102, 0xffff), b"\x01\x02") self.assertEqual(n2b(0x1fe, 0xffff), b"\x01\xfe") self.assertEqual(n2b(0x1ff, 0xffff), b"\x01\xff") self.assertEqual(n2b(0x200, 0xffff), b"\x02\x00") self.assertEqual(n2b(0xffff, 0xffff), b"\xff\xff") self.assertEqual(n2b(0x10000, 0xffffff), b"\x01\x00\x00") self.assertEqual(n2b(0x1, 0xffffffff), b"\x00\x00\x00\x01") self.assertRaises(ValueError, n2b, 0x10000, 0xff) def test_bytes_to_number(self): b2n = util.bytes_to_number self.assertEqual(b2n(b"\x00"), 0x00) self.assertEqual(b2n(b"\x01"), 0x01) self.assertEqual(b2n(b"\xff"), 0xff) self.assertEqual(b2n(b"\x01\x00"), 0x0100) self.assertEqual(b2n(b"\x01\x01"), 0x0101) self.assertEqual(b2n(b"\x01\x02"), 0x0102) self.assertEqual(b2n(b"\x01\xfe"), 0x01fe) self.assertEqual(b2n(b"\x01\xff"), 0x01ff) self.assertEqual(b2n(b"\x02\x00"), 0x0200) self.assertEqual(b2n(b"\xff\xff"), 0xffff) self.assertEqual(b2n(b"\x01\x00\x00"), 0x010000) self.assertEqual(b2n(b"\x00\x00\x00\x01"), 0x01) self.assertRaises(TypeError, b2n, 42) if type("") != type(b""): self.assertRaises(TypeError, b2n, "not bytes") def test_mask(self): gen = util.generate_mask self.assertEqual(gen(0x01), (0x01, 1)) self.assertEqual(gen(0x02), (0x03, 1)) self.assertEqual(gen(0x03), (0x03, 1)) self.assertEqual(gen(0x04), (0x07, 1)) self.assertEqual(gen(0x07), (0x07, 1)) self.assertEqual(gen(0x08), (0x0f, 1)) self.assertEqual(gen(0x09), (0x0f, 1)) self.assertEqual(gen(0x0f), (0x0f, 1)) self.assertEqual(gen(0x10), (0x1f, 1)) self.assertEqual(gen(0x7f), (0x7f, 1)) self.assertEqual(gen(0x80), (0xff, 1)) self.assertEqual(gen(0xff), (0xff, 1)) self.assertEqual(gen(0x0100), (0x01, 2)) self.assertEqual(gen(2**255-19), (0x7f, 32)) mask = util.mask_list_of_ints self.assertEqual(mask(0x03, [0xff, 0x55, 0xaa]), [0x03, 0x55, 0xaa]) self.assertEqual(mask(0xff, [0xff]), [0xff]) def test_l2n(self): l2n = util.list_of_ints_to_number self.assertEqual(l2n([0x00]), 0x00) self.assertEqual(l2n([0x01]), 0x01) self.assertEqual(l2n([0x7f]), 0x7f) self.assertEqual(l2n([0x80]), 0x80) self.assertEqual(l2n([0xff]), 0xff) self.assertEqual(l2n([0x01, 0x00]), 0x0100) def test_unbiased_randrange(self): for seed in range(1000): self.do_test_unbiased_randrange(0, 254, seed) self.do_test_unbiased_randrange(0, 255, seed) self.do_test_unbiased_randrange(0, 256, seed) self.do_test_unbiased_randrange(0, 257, seed) self.do_test_unbiased_randrange(1, 257, seed) def do_test_unbiased_randrange(self, start, stop, seed): seed_b = str(seed).encode("ascii") num = util.unbiased_randrange(start, stop, entropy_f=PRG(seed_b)) self.assertTrue(start <= num < stop, (num, seed)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/src/spake2/util.py0000644000175000017500000000504614654534712015376 0ustar00meejahmeejahimport os, binascii, math def size_bits(maxval): if hasattr(maxval, "bit_length"): # python-2.7 or 3.x return maxval.bit_length() or 1 # 2.6 return len(bin(maxval)) - 2 def size_bytes(maxval): return int(math.ceil(size_bits(maxval) / 8)) def number_to_bytes(num, maxval): if num > maxval: raise ValueError num_bytes = size_bytes(maxval) fmt_str = "%0" + str(2*num_bytes) + "x" s_hex = fmt_str % num s = binascii.unhexlify(s_hex.encode("ascii")) assert len(s) == num_bytes assert isinstance(s, type(b"")) return s def bytes_to_number(s): if not isinstance(s, type(b"")): raise TypeError return int(binascii.hexlify(s), 16) def generate_mask(maxval): num_bytes = size_bytes(maxval) num_bits = size_bits(maxval) leftover_bits = num_bits % 8 if leftover_bits: top_byte_mask_int = (0x1 << leftover_bits) - 1 else: top_byte_mask_int = 0xff assert 0 <= top_byte_mask_int <= 0xff return (top_byte_mask_int, num_bytes) def random_list_of_ints(count, entropy_f=os.urandom): # return a list of ints, each 0<=x<=255, for masking return list(iter(entropy_f(count))) def mask_list_of_ints(top_byte_mask_int, list_of_ints): return [top_byte_mask_int & list_of_ints[0]] + list_of_ints[1:] def list_of_ints_to_number(l): s = "".join(["%02x" % b for b in l]) return int(s, 16) def unbiased_randrange(start, stop, entropy_f): """Return a random integer k such that start <= k < stop, uniformly distributed across that range, like random.randrange but cryptographically bound and unbiased. r(0,p) provides a random group element of the integer group Zp. r(1,p) provides a random group element of the integer group Zp*. """ # we generate a random binary string up to 7 bits larger than we really # need, mask that down to be the right number of bits, then compare # against the range and try again if it's wrong. This will take a random # number of tries, but on average less than two # first we get 0<=number<(stop-start) maxval = stop - start top_byte_mask_int, num_bytes = generate_mask(maxval) while True: enough_bytes = random_list_of_ints(num_bytes, entropy_f) assert len(enough_bytes) == num_bytes candidate_bytes = mask_list_of_ints(top_byte_mask_int, enough_bytes) candidate_int = list_of_ints_to_number(candidate_bytes) #print ["0x%02x" % b for b in candidate_bytes], candidate_int if candidate_int < maxval: return start + candidate_int ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1727223751.7690542 spake2-0.9/src/spake2.egg-info/0000755000175000017500000000000014674653710015536 5ustar00meejahmeejah././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727223751.0 spake2-0.9/src/spake2.egg-info/PKG-INFO0000644000175000017500000000101214674653707016633 0ustar00meejahmeejahMetadata-Version: 2.1 Name: spake2 Version: 0.9 Summary: SPAKE2 password-authenticated key exchange (pure python) Home-page: https://github.com/warner/python-spake2 Author: Brian Warner Author-email: warner-pyspake2@lothar.com License: MIT Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Security :: Cryptography License-File: LICENSE Requires-Dist: cryptography ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727223751.0 spake2-0.9/src/spake2.egg-info/SOURCES.txt0000644000175000017500000000151314674653707017430 0ustar00meejahmeejah.coveragerc .travis.yml LICENSE MANIFEST.in NEWS README.md setup.cfg setup.py tox.ini versioneer.py src/spake2/__init__.py src/spake2/_version.py src/spake2/ed25519_basic.py src/spake2/ed25519_group.py src/spake2/groups.py src/spake2/params.py src/spake2/spake2.py src/spake2/util.py src/spake2.egg-info/PKG-INFO src/spake2.egg-info/SOURCES.txt src/spake2.egg-info/dependency_links.txt src/spake2.egg-info/requires.txt src/spake2.egg-info/top_level.txt src/spake2/parameters/__init__.py src/spake2/parameters/all.py src/spake2/parameters/ed25519.py src/spake2/parameters/i1024.py src/spake2/parameters/i2048.py src/spake2/parameters/i3072.py src/spake2/test/__init__.py src/spake2/test/common.py src/spake2/test/myhkdf.py src/spake2/test/test_compat.py src/spake2/test/test_group.py src/spake2/test/test_spake2.py src/spake2/test/test_utils.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727223751.0 spake2-0.9/src/spake2.egg-info/dependency_links.txt0000644000175000017500000000000114674653707021612 0ustar00meejahmeejah ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727223751.0 spake2-0.9/src/spake2.egg-info/requires.txt0000644000175000017500000000001514674653707020140 0ustar00meejahmeejahcryptography ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1727223751.0 spake2-0.9/src/spake2.egg-info/top_level.txt0000644000175000017500000000000714674653707020273 0ustar00meejahmeejahspake2 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/tox.ini0000644000175000017500000000103014654534712013373 0ustar00meejahmeejah# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py39, py310, py311, py312 [testenv] usedevelop = True deps = pytest commands = py.test {posargs:src/spake2} [testenv:coverage] deps = coverage pytest commands = coverage run -m pytest {posargs:src/spake2} [testenv:speed] commands = {envpython} setup.py speed ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722989002.0 spake2-0.9/versioneer.py0000644000175000017500000025122514654534712014630 0ustar00meejahmeejah # Version: 0.29 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/python-versioneer/python-versioneer * Brian Warner * License: Public Domain (Unlicense) * Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in setuptools-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install Versioneer provides two installation modes. The "classic" vendored mode installs a copy of versioneer into your repository. The experimental build-time dependency mode is intended to allow you to skip this step and simplify the process of upgrading. ### Vendored mode * `pip install versioneer` to somewhere in your $PATH * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is available, so you can also use `conda install -c conda-forge versioneer` * add a `[tool.versioneer]` section to your `pyproject.toml` or a `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) * Note that you will need to add `tomli; python_version < "3.11"` to your build-time dependencies if you use `pyproject.toml` * run `versioneer install --vendor` in your source tree, commit the results * verify version information with `python setup.py version` ### Build-time dependency mode * `pip install versioneer` to somewhere in your $PATH * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is available, so you can also use `conda install -c conda-forge versioneer` * add a `[tool.versioneer]` section to your `pyproject.toml` or a `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) * add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) to the `requires` key of the `build-system` table in `pyproject.toml`: ```toml [build-system] requires = ["setuptools", "versioneer[toml]"] build-backend = "setuptools.build_meta" ``` * run `versioneer install --no-vendor` in your source tree, commit the results * verify version information with `python setup.py version` ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes). The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg` and `pyproject.toml`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install --[no-]vendor` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## Similar projects * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time dependency * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of versioneer * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the "Unlicense", as described in https://unlicense.org/. [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with # pylint:disable=attribute-defined-outside-init,too-many-arguments import configparser import errno import json import os import re import subprocess import sys from pathlib import Path from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union from typing import NoReturn import functools have_tomllib = True if sys.version_info >= (3, 11): import tomllib else: try: import tomli as tomllib except ImportError: have_tomllib = False class VersioneerConfig: """Container for Versioneer configuration parameters.""" VCS: str style: str tag_prefix: str versionfile_source: str versionfile_build: Optional[str] parentdir_prefix: Optional[str] verbose: Optional[bool] def get_root() -> str: """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") if not ( os.path.exists(setup_py) or os.path.exists(pyproject_toml) or os.path.exists(versioneer_py) ): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") if not ( os.path.exists(setup_py) or os.path.exists(pyproject_toml) or os.path.exists(versioneer_py) ): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. my_path = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root def get_config_from_root(root: str) -> VersioneerConfig: """Read the project setup.cfg file to determine Versioneer config.""" # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . root_pth = Path(root) pyproject_toml = root_pth / "pyproject.toml" setup_cfg = root_pth / "setup.cfg" section: Union[Dict[str, Any], configparser.SectionProxy, None] = None if pyproject_toml.exists() and have_tomllib: try: with open(pyproject_toml, 'rb') as fobj: pp = tomllib.load(fobj) section = pp['tool']['versioneer'] except (tomllib.TOMLDecodeError, KeyError) as e: print(f"Failed to load config from {pyproject_toml}: {e}") print("Try to load it from setup.cfg") if not section: parser = configparser.ConfigParser() with open(setup_cfg) as cfg_file: parser.read_file(cfg_file) parser.get("versioneer", "VCS") # raise error if missing section = parser["versioneer"] # `cast`` really shouldn't be used, but its simplest for the # common VersioneerConfig users at the moment. We verify against # `None` values elsewhere where it matters cfg = VersioneerConfig() cfg.VCS = section['VCS'] cfg.style = section.get("style", "") cfg.versionfile_source = cast(str, section.get("versionfile_source")) cfg.versionfile_build = section.get("versionfile_build") cfg.tag_prefix = cast(str, section.get("tag_prefix")) if cfg.tag_prefix in ("''", '""', None): cfg.tag_prefix = "" cfg.parentdir_prefix = section.get("parentdir_prefix") if isinstance(section, configparser.SectionProxy): # Make sure configparser translates to bool cfg.verbose = section.getboolean("verbose") else: cfg.verbose = section.get("verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" HANDLERS.setdefault(vcs, {})[method] = f return f return decorate def run_command( commands: List[str], args: List[str], cwd: Optional[str] = None, verbose: bool = False, hide_stderr: bool = False, env: Optional[Dict[str, str]] = None, ) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs: Dict[str, Any] = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError as e: if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. # Generated by versioneer-0.29 # https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Any, Callable, Dict, List, Optional, Tuple import functools def get_keywords() -> Dict[str, str]: """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" VCS: str style: str tag_prefix: str parentdir_prefix: str versionfile_source: str verbose: bool def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command( commands: List[str], args: List[str], cwd: Optional[str] = None, verbose: bool = False, hide_stderr: bool = False, env: Optional[Dict[str, str]] = None, ) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs: Dict[str, Any] = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError as e: if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir( parentdir_prefix: str, root: str, verbose: bool, ) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords: Dict[str, str] = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords( keywords: Dict[str, str], tag_prefix: str, verbose: bool, ) -> Dict[str, Any]: """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs( tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command ) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, [ "describe", "--tags", "--dirty", "--always", "--long", "--match", f"{tag_prefix}[[:digit:]]*" ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces: Dict[str, Any]) -> str: """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces: Dict[str, Any]) -> str: """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) else: rendered += ".post0.dev%%d" %% (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions() -> Dict[str, Any]: """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords: Dict[str, str] = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords( keywords: Dict[str, str], tag_prefix: str, verbose: bool, ) -> Dict[str, Any]: """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs( tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command ) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, [ "describe", "--tags", "--dirty", "--always", "--long", "--match", f"{tag_prefix}[[:digit:]]*" ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [versionfile_source] if ipy: files.append(ipy) if "VERSIONEER_PEP518" not in globals(): try: my_path = __file__ if my_path.endswith((".pyc", ".pyo")): my_path = os.path.splitext(my_path)[0] + ".py" versioneer_file = os.path.relpath(my_path) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: with open(".gitattributes", "r") as fobj: for line in fobj: if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True break except OSError: pass if not present: with open(".gitattributes", "a+") as fobj: fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir( parentdir_prefix: str, root: str, verbose: bool, ) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.29) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename: str) -> Dict[str, Any]: """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: """Write the given version number to the given _version.py file.""" contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces: Dict[str, Any]) -> str: """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces: Dict[str, Any]) -> str: """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose: bool = False) -> Dict[str, Any]: """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version() -> str: """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): """Get the custom setuptools subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/python-versioneer/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # we add "version" to setuptools from setuptools import Command class cmd_version(Command): description = "report generated version string" user_options: List[Tuple[str, str, str]] = [] boolean_options: List[str] = [] def initialize_options(self) -> None: pass def finalize_options(self) -> None: pass def run(self) -> None: vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # pip install -e . and setuptool/editable_wheel will invoke build_py # but the build_py command is not expected to copy any files. # we override different "build_py" commands for both environments if 'build_py' in cmds: _build_py: Any = cmds['build_py'] else: from setuptools.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) if getattr(self, "editable_mode", False): # During editable installs `.py` and data files are # not copied to build_lib return # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if 'build_ext' in cmds: _build_ext: Any = cmds['build_ext'] else: from setuptools.command.build_ext import build_ext as _build_ext class cmd_build_ext(_build_ext): def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_ext.run(self) if self.inplace: # build_ext --inplace will only build extensions in # build/lib<..> dir with no _version.py to write to. # As in place builds will already have a _version.py # in the module dir, we do not need to write one. return # now locate _version.py in the new build/ directory and replace # it with an updated value if not cfg.versionfile_build: return target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) if not os.path.exists(target_versionfile): print(f"Warning: {target_versionfile} does not exist, skipping " "version update. This can happen if you are running build_ext " "without first running build_py.") return print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # type: ignore # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore except ImportError: from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore class cmd_py2exe(_py2exe): def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # sdist farms its file list building out to egg_info if 'egg_info' in cmds: _egg_info: Any = cmds['egg_info'] else: from setuptools.command.egg_info import egg_info as _egg_info class cmd_egg_info(_egg_info): def find_sources(self) -> None: # egg_info.find_sources builds the manifest list and writes it # in one shot super().find_sources() # Modify the filelist and normalize it root = get_root() cfg = get_config_from_root(root) self.filelist.append('versioneer.py') if cfg.versionfile_source: # There are rare cases where versionfile_source might not be # included by default, so we must be explicit self.filelist.append(cfg.versionfile_source) self.filelist.sort() self.filelist.remove_duplicates() # The write method is hidden in the manifest_maker instance that # generated the filelist and was thrown away # We will instead replicate their final normalization (to unicode, # and POSIX-style paths) from setuptools import unicode_utils normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') for f in self.filelist.files] manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') with open(manifest_filename, 'w') as fobj: fobj.write('\n'.join(normalized)) cmds['egg_info'] = cmd_egg_info # we override different "sdist" commands for both environments if 'sdist' in cmds: _sdist: Any = cmds['sdist'] else: from setuptools.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self) -> None: versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir: str, files: List[str]) -> None: root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ INIT_PY_SNIPPET = """ from . import {0} __version__ = {0}.get_versions()['version'] """ def do_setup() -> int: """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") maybe_ipy: Optional[str] = ipy if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except OSError: old = "" module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] snippet = INIT_PY_SNIPPET.format(module) if OLD_SNIPPET in old: print(" replacing boilerplate in %s" % ipy) with open(ipy, "w") as f: f.write(old.replace(OLD_SNIPPET, snippet)) elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) maybe_ipy = None # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(cfg.versionfile_source, maybe_ipy) return 0 def scan_setup_py() -> int: """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors def setup_command() -> NoReturn: """Set up Versioneer and exit with appropriate error code.""" errors = do_setup() errors += scan_setup_py() sys.exit(1 if errors else 0) if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": setup_command()