yescrypt 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of yescrypt might be problematic. Click here for more details.

@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: yescrypt
3
+ Version: 1.0.0
4
+ Summary: Pure-Python yescrypt password hashing
5
+ Author: @example
6
+ Classifier: Intended Audience :: Developers
7
+ Classifier: Programming Language :: Python :: 2
8
+ Classifier: Programming Language :: Python :: 2.6
9
+ Classifier: Programming Language :: Python :: 2.7
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=2.6, !=3.0.*, !=3.1.*, !=3.2.*
13
+ Description-Content-Type: text/markdown
14
+ Dynamic: requires-python
15
+
16
+ # yescrypt
17
+
18
+ Pure-Python yescrypt password hashing. It uses only the standard library and runs on Python 2.6 and on Python 3.
19
+
20
+ It creates and verifies `$y$` hash strings compatible with libxcrypt, the crypt library used by many Linux distributions for `ENCRYPT_METHOD YESCRYPT`. Hashes made here can be checked by libcrypt, and the reverse also works.
21
+
22
+ ## Installation
23
+
24
+ ```
25
+ python setup.py install
26
+ ```
27
+
28
+ Or use the package directly by putting the `yescrypt/` directory on `PYTHONPATH`.
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ import yescrypt
34
+
35
+ hashed = yescrypt.hash_password('correct horse battery staple')
36
+ # '$y$j9T$<salt>$<43-character digest>'
37
+
38
+ yescrypt.verify('correct horse battery staple', hashed) # True
39
+ yescrypt.verify('wrong', hashed) # False
40
+ ```
41
+
42
+ ### `hash_password(password, salt=None, N=4096, r=32, p=1, t=0)`
43
+
44
+ Returns a hash string. `password` may be text (encoded as UTF-8) or bytes.
45
+
46
+ * `salt`: bytes or text, 1 to 64 bytes long. If omitted, 16 random bytes come from `os.urandom`.
47
+ * `N`: CPU/memory cost, a power of 2 greater than `p`. The default is 4096.
48
+ * `r`: block size. The default is 32. Working memory is about 128 × r × N bytes, which is 16 MiB for the defaults.
49
+ * `p`: parallelism. The default is 1.
50
+ * `t`: extra time cost. The default is 0.
51
+
52
+ Raises `ValueError` for invalid parameters or salt length, and `TypeError` for a password that isn't text or bytes.
53
+
54
+ ### `verify(password, hashed)`
55
+
56
+ Returns `True` if `password` produces `hashed`, otherwise `False`. The hash can be text or bytes. A malformed or unsupported hash string also returns `False` and does not raise an exception. The comparison runs in constant time.
57
+
58
+ ## Supported settings
59
+
60
+ * The default RW flavor (`$y$j...`), which is the one libxcrypt produces.
61
+ * Any valid `N`, `r`, `p` and `t`. The pre-hash pass that libxcrypt uses for large `N` is included.
62
+
63
+ Not supported, and rejected with `ValueError` or `False` from `verify`:
64
+
65
+ * The ROM and NROM modes.
66
+ * Hash upgrade (`g` greater than 0).
67
+ * Other flavors, including plain scrypt.
68
+
69
+ ## Performance
70
+
71
+ This is pure Python, so it is slow compared with the C implementation. The default settings take several seconds for each hash. Verification costs the same as hashing, because it recomputes the hash with the parameters stored in the string. For a login system, a native libcrypt binding is a better choice.
72
+
73
+ ## Testing
74
+
75
+ ```
76
+ python tests/test_yescrypt.py
77
+ ```
78
+
79
+ The default run takes about a minute and a quarter. To also run the two large-parameter vectors (about one minute more), set `YESCRYPT_SLOW_TESTS=1`.
80
+
81
+ The test vectors were generated once with the system libcrypt. The test suite does not use libcrypt. The scripts in `tests/` that call libcrypt (`gen_vectors.py`, `probe_settings.py`, `gen_extra.py`, `check_vectors.py`) are development helpers and are not needed to use the library.
82
+
83
+ ## Layout
84
+
85
+ ```
86
+ yescrypt/
87
+ __init__.py hash_password() and verify()
88
+ _core.py yescrypt RW calculation (port of yescrypt-ref.c)
89
+ _encoding.py base64 and $y$ setting encoding
90
+ _compat.py text/bytes, constant-time compare, HMAC and PBKDF2
91
+ tests/ unit tests and development helpers
92
+ ```
93
+
@@ -0,0 +1,78 @@
1
+ # yescrypt
2
+
3
+ Pure-Python yescrypt password hashing. It uses only the standard library and runs on Python 2.6 and on Python 3.
4
+
5
+ It creates and verifies `$y$` hash strings compatible with libxcrypt, the crypt library used by many Linux distributions for `ENCRYPT_METHOD YESCRYPT`. Hashes made here can be checked by libcrypt, and the reverse also works.
6
+
7
+ ## Installation
8
+
9
+ ```
10
+ python setup.py install
11
+ ```
12
+
13
+ Or use the package directly by putting the `yescrypt/` directory on `PYTHONPATH`.
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ import yescrypt
19
+
20
+ hashed = yescrypt.hash_password('correct horse battery staple')
21
+ # '$y$j9T$<salt>$<43-character digest>'
22
+
23
+ yescrypt.verify('correct horse battery staple', hashed) # True
24
+ yescrypt.verify('wrong', hashed) # False
25
+ ```
26
+
27
+ ### `hash_password(password, salt=None, N=4096, r=32, p=1, t=0)`
28
+
29
+ Returns a hash string. `password` may be text (encoded as UTF-8) or bytes.
30
+
31
+ * `salt`: bytes or text, 1 to 64 bytes long. If omitted, 16 random bytes come from `os.urandom`.
32
+ * `N`: CPU/memory cost, a power of 2 greater than `p`. The default is 4096.
33
+ * `r`: block size. The default is 32. Working memory is about 128 × r × N bytes, which is 16 MiB for the defaults.
34
+ * `p`: parallelism. The default is 1.
35
+ * `t`: extra time cost. The default is 0.
36
+
37
+ Raises `ValueError` for invalid parameters or salt length, and `TypeError` for a password that isn't text or bytes.
38
+
39
+ ### `verify(password, hashed)`
40
+
41
+ Returns `True` if `password` produces `hashed`, otherwise `False`. The hash can be text or bytes. A malformed or unsupported hash string also returns `False` and does not raise an exception. The comparison runs in constant time.
42
+
43
+ ## Supported settings
44
+
45
+ * The default RW flavor (`$y$j...`), which is the one libxcrypt produces.
46
+ * Any valid `N`, `r`, `p` and `t`. The pre-hash pass that libxcrypt uses for large `N` is included.
47
+
48
+ Not supported, and rejected with `ValueError` or `False` from `verify`:
49
+
50
+ * The ROM and NROM modes.
51
+ * Hash upgrade (`g` greater than 0).
52
+ * Other flavors, including plain scrypt.
53
+
54
+ ## Performance
55
+
56
+ This is pure Python, so it is slow compared with the C implementation. The default settings take several seconds for each hash. Verification costs the same as hashing, because it recomputes the hash with the parameters stored in the string. For a login system, a native libcrypt binding is a better choice.
57
+
58
+ ## Testing
59
+
60
+ ```
61
+ python tests/test_yescrypt.py
62
+ ```
63
+
64
+ The default run takes about a minute and a quarter. To also run the two large-parameter vectors (about one minute more), set `YESCRYPT_SLOW_TESTS=1`.
65
+
66
+ The test vectors were generated once with the system libcrypt. The test suite does not use libcrypt. The scripts in `tests/` that call libcrypt (`gen_vectors.py`, `probe_settings.py`, `gen_extra.py`, `check_vectors.py`) are development helpers and are not needed to use the library.
67
+
68
+ ## Layout
69
+
70
+ ```
71
+ yescrypt/
72
+ __init__.py hash_password() and verify()
73
+ _core.py yescrypt RW calculation (port of yescrypt-ref.c)
74
+ _encoding.py base64 and $y$ setting encoding
75
+ _compat.py text/bytes, constant-time compare, HMAC and PBKDF2
76
+ tests/ unit tests and development helpers
77
+ ```
78
+
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "yescrypt"
7
+ dynamic = ["version"]
8
+ description = "Pure-Python yescrypt password hashing"
9
+ readme = "README.md"
10
+ requires-python = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*"
11
+ authors = [{ name = "@example" }]
12
+ classifiers = [
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 2",
15
+ "Programming Language :: Python :: 2.6",
16
+ "Programming Language :: Python :: 2.7",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Security :: Cryptography",
19
+ ]
20
+
21
+ [tool.setuptools]
22
+ packages = ["yescrypt"]
23
+
24
+ [tool.setuptools.dynamic]
25
+ version = { attr = "yescrypt.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ # Packaging script for the yescrypt library. Works on Python 2.6+ and 3.x.
2
+ import os
3
+ import re
4
+
5
+ try:
6
+ from setuptools import setup
7
+ except ImportError:
8
+ from distutils.core import setup
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+
12
+
13
+ def read(name):
14
+ with open(os.path.join(HERE, name)) as handle:
15
+ return handle.read()
16
+
17
+
18
+ def get_version():
19
+ init = read(os.path.join('yescrypt', '__init__.py'))
20
+ match = re.search(r"__version__\s*=\s*'([^']+)'", init)
21
+ if not match:
22
+ raise RuntimeError('cannot find __version__ in yescrypt/__init__.py')
23
+ return match.group(1)
24
+
25
+
26
+ setup(
27
+ name='yescrypt',
28
+ version=get_version(),
29
+ author='github.com/arlsr',
30
+ description='Pure-Python yescrypt password hashing',
31
+ long_description=read('README.md'),
32
+ long_description_content_type='text/markdown',
33
+ packages=['yescrypt'],
34
+ python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*',
35
+ classifiers=[
36
+ 'Intended Audience :: Developers',
37
+ 'Programming Language :: Python :: 2',
38
+ 'Programming Language :: Python :: 2.6',
39
+ 'Programming Language :: Python :: 2.7',
40
+ 'Programming Language :: Python :: 3',
41
+ 'Topic :: Security :: Cryptography',
42
+ ],
43
+ )
@@ -0,0 +1,124 @@
1
+ # Tests for the pure-Python yescrypt library. Compatible with Python 2.6+.
2
+ # Vectors were generated once with the system libcrypt (libxcrypt).
3
+ import os
4
+ import sys
5
+ import unittest
6
+
7
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
8
+
9
+ import yescrypt
10
+ from yescrypt._encoding import parse_setting
11
+
12
+ PW = b'password'
13
+
14
+ FAST = [
15
+ (b'', '$y$j15$k2XAnEHBqQ1Ct2aMXFKNa/$2hFkUnubSTMrZlDd9WyeIaBM4bAfedKYXf3QsUnyNg8'),
16
+ (b'pw', '$y$j25$k.$pgJ.enHOW1lcQ8hwhgZnt0IBIZE4L5C9HRU6.2Pl5L.'),
17
+ (b'p\xc3\xa4ssw\xc3\xb6rd', '$y$j35..$k2XAnEHBqQ1Ct2aMXFKNa/$WXMO4DZDKAOntI6lQJ8ZUjowgmq855lBhqpVUfq1fu5'),
18
+ (PW, '$y$j31/.$k2XAnEHBqQ1Ct2aMXFKNa/$Bhaw9RZ4Q2/fUhNkvLYwLOcyG4oxYaV72E6bWFtVo01'),
19
+ (PW, '$y$j450./$k2XAnEHBqQ1Ct2aMXFKNaR4OddqOgpaP$.jYMC4D.oj7X.wTApg3uZQBEu/AObCdetbmNYNQgh55'),
20
+ (PW, '$y$j75.0$k2XAnEHBqQ1Ct2aMXFKNaR4OddqOgpaPj/LQmB5RpNrRsZbS/7oE2JYF5VIG8h2HBtoHE3ZIHFJJKR3KNd3Al.$mM0sg967lTjYX0bRjqQPg0FjD2M1aTJrF8Iq3W1h2eA'),
21
+ (b'x' * 100, '$y$j5./0$k2XAnEHBqQ1Ct2aMXFKNa/$hN30JTfLqKB27wtbWDxYr/0xACia4ITFy/oELeLleUD'),
22
+ (PW, '$y$j5T$saltsaltsaltsalt$cxF.3g293y3.Z8R8fZ99hyyBXMGY12HNeVpq7Tc0wvB'),
23
+ (PW, '$y$j6T$saltsaltsaltsalt$ZkYNa4dMAGjTtSc/Nj9S7hSsd2b2510VVcY6Tlbwyp1'),
24
+ (PW, '$y$j8T$saltsaltsaltsalt$3AmdJlblcRLUZGcfZ1G1y.qsYNkOwS96sZWcNOPhzb4'),
25
+ # Default parameters (N=4096, r=32); this one uses the pre-hash pass.
26
+ (PW, '$y$j9T$saltsaltsaltsalt$Uxvkjnhdr/2B6SINV1mXACdXVbd5kc899ms5aqhxMQD'),
27
+ ]
28
+
29
+ SLOW = [
30
+ (PW, '$y$jB5$k2XAnEHBqQ1Ct2aMXFKNa/$b8M2OKdrEtcuXhRlOhtW9E.nWff0M547no98Y6aaBZ6'),
31
+ (PW, '$y$jAT..$k2XAnEHBqQ1Ct2aMXFKNa/$4k8DQ0eh.e10fs3KjedrZ8BiqqbKH/l3PE.MFy7TgvD'),
32
+ ]
33
+
34
+
35
+ def _head(hashed):
36
+ return hashed.rpartition('$')[0]
37
+
38
+
39
+ def _recompute(password, hashed):
40
+ salt = parse_setting(_head(hashed))['salt']
41
+ p = parse_setting(_head(hashed))
42
+ return yescrypt.hash_password(password, salt=salt, N=p['N'], r=p['r'],
43
+ p=p['p'], t=p['t'])
44
+
45
+
46
+ class VectorTests(unittest.TestCase):
47
+ def test_hash_matches_libcrypt(self):
48
+ for password, hashed in FAST:
49
+ self.assertEqual(_recompute(password, hashed), hashed)
50
+
51
+ def test_verify_accepts_correct_password(self):
52
+ for password, hashed in FAST[:4] + FAST[-1:]:
53
+ self.assertTrue(yescrypt.verify(password, hashed))
54
+
55
+ def test_verify_rejects_wrong_password(self):
56
+ for password, hashed in FAST[:4]:
57
+ self.assertFalse(yescrypt.verify(password + b'x', hashed))
58
+
59
+ def test_verify_accepts_bytes_hash(self):
60
+ password, hashed = FAST[0]
61
+ self.assertTrue(yescrypt.verify(password, hashed.encode('ascii')))
62
+
63
+ def test_text_and_bytes_passwords_agree(self):
64
+ password, hashed = FAST[2]
65
+ self.assertTrue(yescrypt.verify(password.decode('utf-8'), hashed))
66
+
67
+
68
+ if os.environ.get('YESCRYPT_SLOW_TESTS'):
69
+ class SlowVectorTests(unittest.TestCase):
70
+ def test_large_parameters(self):
71
+ for password, hashed in SLOW:
72
+ self.assertEqual(_recompute(password, hashed), hashed)
73
+
74
+
75
+ class MalformedTests(unittest.TestCase):
76
+ def test_verify_returns_false_for_bad_hashes(self):
77
+ bad = [
78
+ '',
79
+ 'not a hash',
80
+ '$y$',
81
+ '$y$j9T$saltsaltsaltsalt',
82
+ '$y$j9T$saltsaltsaltsalt$',
83
+ '$y$a9T$saltsaltsaltsalt$abc',
84
+ '$y$j15$k2XAnEHBqQ1Ct2aMXFKNa/$short',
85
+ '$y$j15$k2XAnEHBqQ1Ct2aMXFKNa/$' + '!' * 43,
86
+ '$2b$12$abcdefghijklmnopqrstuuabcdefghijklmnopqrstuvwxyz01234',
87
+ b'$y$j15$\xff\xfe$abc',
88
+ ]
89
+ for hashed in bad:
90
+ self.assertFalse(yescrypt.verify(PW, hashed))
91
+
92
+
93
+ class ParameterTests(unittest.TestCase):
94
+ def test_invalid_parameters_raise_valueerror(self):
95
+ calls = [
96
+ dict(N=1), dict(N=3), dict(N=16, r=0), dict(N=16, p=0),
97
+ dict(N=16, t=-1), dict(N=2, p=2), dict(N=16, salt=b''),
98
+ dict(N=16, salt=b'x' * 65),
99
+ ]
100
+ for kwargs in calls:
101
+ self.assertRaises(ValueError, yescrypt.hash_password, PW, **kwargs)
102
+
103
+ def test_invalid_password_type_raises_typeerror(self):
104
+ self.assertRaises(TypeError, yescrypt.hash_password, 123, N=16, r=1)
105
+
106
+
107
+ class RoundTripTests(unittest.TestCase):
108
+ def test_roundtrip_and_random_salt(self):
109
+ h1 = yescrypt.hash_password(PW, N=16, r=1)
110
+ h2 = yescrypt.hash_password(PW, N=16, r=1)
111
+ self.assertTrue(h1.startswith('$y$j'))
112
+ self.assertEqual(len(h1.rpartition('$')[2]), 43)
113
+ self.assertTrue(h1 != h2)
114
+ self.assertTrue(yescrypt.verify(PW, h1))
115
+ self.assertFalse(yescrypt.verify(b'other', h1))
116
+
117
+ def test_roundtrip_with_p_and_t(self):
118
+ h = yescrypt.hash_password(u'caf\u00e9', N=64, r=2, p=2, t=1)
119
+ self.assertTrue(yescrypt.verify(u'caf\u00e9', h))
120
+ self.assertFalse(yescrypt.verify(u'cafe', h))
121
+
122
+
123
+ if __name__ == '__main__':
124
+ unittest.main()
@@ -0,0 +1,51 @@
1
+ # yescrypt password hashing, pure Python.
2
+
3
+ import os
4
+
5
+ from ._compat import constant_time_equal, text_type, to_bytes
6
+ from ._core import yescrypt_rw
7
+ from ._encoding import encode_bytes, format_setting, parse_setting
8
+
9
+ __version__ = '1.0.0'
10
+ __author__ = 'github.com/arlsr'
11
+ __all__ = ['hash_password', 'verify']
12
+
13
+
14
+ def _check_params(N, r, p, t):
15
+ if N < 2 or N & (N - 1):
16
+ raise ValueError('N must be a power of 2 greater than 1')
17
+ if r < 1 or p < 1 or t < 0:
18
+ raise ValueError('r and p must be at least 1, t must not be negative')
19
+ if N // p <= 1:
20
+ raise ValueError('N must be greater than p')
21
+ if r * p >= (1 << 30):
22
+ raise ValueError('r * p is too large')
23
+
24
+
25
+ def hash_password(password, salt=None, N=4096, r=32, p=1, t=0):
26
+ """Return a '$y$...' yescrypt hash string for password."""
27
+ if salt is None:
28
+ salt = os.urandom(16)
29
+ salt = to_bytes(salt)
30
+ if not 1 <= len(salt) <= 64:
31
+ raise ValueError('salt must be 1 to 64 bytes')
32
+ _check_params(N, r, p, t)
33
+ setting = format_setting(N, r, p, t, salt)
34
+ digest = yescrypt_rw(to_bytes(password), salt, N, r, p, t)
35
+ return setting + '$' + encode_bytes(digest)
36
+
37
+
38
+ def verify(password, hashed):
39
+ """Return True if password matches the yescrypt hash string hashed."""
40
+ try:
41
+ if not isinstance(hashed, text_type):
42
+ hashed = hashed.decode('ascii')
43
+ head, _, _ = hashed.rpartition('$')
44
+ params = parse_setting(head)
45
+ _check_params(params['N'], params['r'], params['p'], params['t'])
46
+ digest = yescrypt_rw(to_bytes(password), params['salt'],
47
+ params['N'], params['r'], params['p'], params['t'])
48
+ candidate = head + '$' + encode_bytes(digest)
49
+ except (ValueError, UnicodeError):
50
+ return False
51
+ return constant_time_equal(candidate, hashed)
@@ -0,0 +1,67 @@
1
+ """Compatibility helpers for Python 2.6 through Python 3.x."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import struct
6
+
7
+ try:
8
+ text_type = unicode # noqa: F821 (Python 2)
9
+ except NameError:
10
+ text_type = str
11
+
12
+
13
+ def to_bytes(value):
14
+ """Return value as bytes. Text is encoded as UTF-8."""
15
+ if isinstance(value, text_type):
16
+ return value.encode('utf-8')
17
+ if isinstance(value, (bytes, bytearray)):
18
+ return bytes(value)
19
+ raise TypeError('expected text or bytes, got %s' % type(value).__name__)
20
+
21
+
22
+ def constant_time_equal(a, b):
23
+ """Compare two byte strings without returning early on the first mismatch."""
24
+ a = bytearray(to_bytes(a))
25
+ b = bytearray(to_bytes(b))
26
+ if len(a) != len(b):
27
+ return False
28
+ diff = 0
29
+ for x, y in zip(a, b):
30
+ diff |= x ^ y
31
+ return diff == 0
32
+
33
+
34
+ def sha256_digest(data):
35
+ """Return SHA-256 digest of data as bytes."""
36
+ return hashlib.sha256(data).digest()
37
+
38
+
39
+ def hmac_sha256(key, message):
40
+ """Return HMAC-SHA256 digest as bytes."""
41
+ return hmac.new(key, message, hashlib.sha256).digest()
42
+
43
+
44
+ def pbkdf2_sha256(password, salt, iterations, dklen):
45
+ """PBKDF2-HMAC-SHA256. Uses hashlib when available (2.7.8+, 3.4+)."""
46
+ pbkdf2 = getattr(hashlib, 'pbkdf2_hmac', None)
47
+ if pbkdf2 is not None:
48
+ return pbkdf2('sha256', password, salt, iterations, dklen)
49
+ return _pbkdf2_fallback(password, salt, iterations, dklen)
50
+
51
+
52
+ def _pbkdf2_fallback(password, salt, iterations, dklen):
53
+ hlen = hashlib.sha256().digest_size
54
+ blocks = []
55
+ block_index = 1
56
+ total = 0
57
+ while total < dklen:
58
+ u = hmac_sha256(password, salt + struct.pack('>I', block_index))
59
+ acc = bytearray(u)
60
+ for _ in range(iterations - 1):
61
+ u = hmac_sha256(password, u)
62
+ for i in range(hlen):
63
+ acc[i] ^= bytearray(u)[i]
64
+ blocks.append(bytes(acc))
65
+ total += hlen
66
+ block_index += 1
67
+ return b''.join(blocks)[:dklen]
@@ -0,0 +1,256 @@
1
+ # This file is a Python port of yescrypt-ref.c from yescrypt 1.0.3, which
2
+ # carries this license:
3
+ #
4
+ # Copyright 2009 Colin Percival
5
+ # Copyright 2013-2018 Alexander Peslyak
6
+ # All rights reserved.
7
+ #
8
+ # Redistribution and use in source and binary forms, with or without
9
+ # modification, are permitted provided that the following conditions
10
+ # are met:
11
+ # 1. Redistributions of source code must retain the above copyright
12
+ # notice, this list of conditions and the following disclaimer.
13
+ # 2. Redistributions in binary form must reproduce the above copyright
14
+ # notice, this list of conditions and the following disclaimer in the
15
+ # documentation and/or other materials provided with the distribution.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23
+ # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24
+ # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26
+ # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27
+ # SUCH DAMAGE.
28
+
29
+ """Pure-Python port of the yescrypt reference (yescrypt-ref.c, 1.0.3).
30
+
31
+ Only the RW flavor with the default pwxform settings is implemented, which
32
+ is what the 'j' flavor in '$y$' strings selects. Words are kept as Python
33
+ ints in the same layout the C code uses, so the port can be checked step by
34
+ step against it.
35
+ """
36
+
37
+ import struct
38
+
39
+ from ._compat import hmac_sha256, pbkdf2_sha256, sha256_digest
40
+
41
+ M = 0xFFFFFFFF
42
+
43
+ # Salsa20 quarter-round schedule: (dst, src1, src2, rotation).
44
+ # Each step is x[dst] ^= rotl32((x[src1] + x[src2]) mod 2^32, rotation).
45
+ _SALSA_OPS = (
46
+ (4, 0, 12, 7), (8, 4, 0, 9), (12, 8, 4, 13), (0, 12, 8, 18),
47
+ (9, 5, 1, 7), (13, 9, 5, 9), (1, 13, 9, 13), (5, 1, 13, 18),
48
+ (14, 10, 6, 7), (2, 14, 10, 9), (6, 2, 14, 13), (10, 6, 2, 18),
49
+ (3, 15, 11, 7), (7, 3, 15, 9), (11, 7, 3, 13), (15, 11, 7, 18),
50
+ (1, 0, 3, 7), (2, 1, 0, 9), (3, 2, 1, 13), (0, 3, 2, 18),
51
+ (6, 5, 4, 7), (7, 6, 5, 9), (4, 7, 6, 13), (5, 4, 7, 18),
52
+ (11, 10, 9, 7), (8, 11, 10, 9), (9, 8, 11, 13), (10, 9, 8, 18),
53
+ (12, 15, 14, 7), (13, 12, 15, 9), (14, 13, 12, 13), (15, 14, 13, 18),
54
+ )
55
+
56
+
57
+ def _rotl(v, b):
58
+ return ((v << b) | (v >> (32 - b))) & M
59
+
60
+
61
+ def _salsa20(B, off, rounds):
62
+ """Salsa20 core applied in place to the 16 words B[off:off+16]."""
63
+ x = [0] * 16
64
+ for i in range(16):
65
+ x[(i * 5) % 16] = B[off + i]
66
+ for _ in range(0, rounds, 2):
67
+ for d, a, b, s in _SALSA_OPS:
68
+ x[d] ^= _rotl((x[a] + x[b]) & M, s)
69
+ for i in range(16):
70
+ B[off + i] = (B[off + i] + x[(i * 5) % 16]) & M
71
+
72
+
73
+ def _blockmix_salsa8(B, Y, r):
74
+ """BlockMix with Salsa20/8 over 2r blocks of 16 words, in place."""
75
+ X = B[(2 * r - 1) * 16:2 * r * 16]
76
+ for i in range(2 * r):
77
+ for k in range(16):
78
+ X[k] ^= B[i * 16 + k]
79
+ _salsa20(X, 0, 8)
80
+ Y[i * 16:(i + 1) * 16] = X
81
+ for i in range(r):
82
+ B[i * 16:(i + 1) * 16] = Y[2 * i * 16:(2 * i + 1) * 16]
83
+ for i in range(r):
84
+ B[(i + r) * 16:(i + r + 1) * 16] = Y[(2 * i + 1) * 16:(2 * i + 2) * 16]
85
+
86
+
87
+ def _pwxform(X, S, ctx):
88
+ """pwxform over 16 words X (4 lanes x 2 pairs x 2 halves), in place.
89
+
90
+ S is the flat list of S-box words. ctx = [s0, s1, s2, w] holds word
91
+ offsets of the three 512-pair S-boxes and the write cursor w (in pairs).
92
+ """
93
+ s0, s1, s2, w = ctx
94
+ for i in range(6):
95
+ for j in range(4):
96
+ xl = X[j * 4]
97
+ xh = X[j * 4 + 1]
98
+ p0 = s0 + ((xl & 0xFF0) >> 2)
99
+ p1 = s1 + ((xh & 0xFF0) >> 2)
100
+ for k in range(2):
101
+ q0 = p0 + 2 * k
102
+ q1 = p1 + 2 * k
103
+ v0 = (S[q0 + 1] << 32) + S[q0]
104
+ v1 = (S[q1 + 1] << 32) + S[q1]
105
+ xl = X[j * 4 + k * 2]
106
+ xh = X[j * 4 + k * 2 + 1]
107
+ x = (xh * xl + v0) & 0xFFFFFFFFFFFFFFFF
108
+ x ^= v1
109
+ X[j * 4 + k * 2] = x & M
110
+ X[j * 4 + k * 2 + 1] = x >> 32
111
+ if i != 0 and i != 5:
112
+ S[s2 + 2 * w] = x & M
113
+ S[s2 + 2 * w + 1] = x >> 32
114
+ w += 1
115
+ ctx[0], ctx[1], ctx[2] = s2, s0, s1
116
+ ctx[3] = w & 511
117
+
118
+
119
+ def _blockmix_pwxform(B, Y, S, ctx, r):
120
+ """BlockMix with pwxform and Salsa20/2 over 2r blocks, in place."""
121
+ r1 = 2 * r
122
+ Y[0:16] = B[(r1 - 1) * 16:r1 * 16]
123
+ for i in range(r1):
124
+ for k in range(16):
125
+ Y[k] ^= B[i * 16 + k]
126
+ _pwxform(Y, S, ctx)
127
+ B[i * 16:(i + 1) * 16] = Y[0:16]
128
+ _salsa20(B, (r1 - 1) * 16, 2)
129
+
130
+
131
+ def _integerify(B, r):
132
+ base = (2 * r - 1) * 16
133
+ return (B[base + 13] << 32) + B[base]
134
+
135
+
136
+ def _p2floor(x):
137
+ while True:
138
+ y = x & (x - 1)
139
+ if not y:
140
+ return x
141
+ x = y
142
+
143
+
144
+ def _wrap(x, i):
145
+ n = _p2floor(i)
146
+ return (x & (n - 1)) + (i - n)
147
+
148
+
149
+ def _load_block_order(B, X, count):
150
+ for k in range(count):
151
+ for i in range(16):
152
+ X[k * 16 + i] = B[k * 16 + (i * 5) % 16]
153
+
154
+
155
+ def _store_block_order(B, X, count):
156
+ for k in range(count):
157
+ for i in range(16):
158
+ B[k * 16 + (i * 5) % 16] = X[k * 16 + i]
159
+
160
+
161
+ def _smix1(B, r, N, rw, V, voff, X, Y, S, ctx):
162
+ s = 32 * r
163
+ _load_block_order(B, X, 2 * r)
164
+ for i in range(N):
165
+ base = voff + i * s
166
+ V[base:base + s] = X[0:s]
167
+ if rw and i > 1:
168
+ j = _wrap(_integerify(X, r), i)
169
+ vb = voff + j * s
170
+ for t in range(s):
171
+ X[t] ^= V[vb + t]
172
+ if ctx is not None:
173
+ _blockmix_pwxform(X, Y, S, ctx, r)
174
+ else:
175
+ _blockmix_salsa8(X, Y, r)
176
+ _store_block_order(B, X, 2 * r)
177
+
178
+
179
+ def _smix2(B, r, N, Nloop, rw, V, voff, X, Y, S, ctx):
180
+ s = 32 * r
181
+ _load_block_order(B, X, 2 * r)
182
+ for _ in range(Nloop):
183
+ j = _integerify(X, r) & (N - 1)
184
+ vb = voff + j * s
185
+ for t in range(s):
186
+ X[t] ^= V[vb + t]
187
+ if rw:
188
+ V[vb:vb + s] = X[0:s]
189
+ if ctx is not None:
190
+ _blockmix_pwxform(X, Y, S, ctx, r)
191
+ else:
192
+ _blockmix_salsa8(X, Y, r)
193
+ _store_block_order(B, X, 2 * r)
194
+
195
+
196
+ def _smix(B, r, N, p, t, passwd, V, X, Y):
197
+ s = 32 * r
198
+ Nchunk = N // p
199
+ Nloop_all = Nchunk
200
+ if t <= 1:
201
+ if t:
202
+ Nloop_all *= 2
203
+ Nloop_all = (Nloop_all + 2) // 3
204
+ else:
205
+ Nloop_all *= t - 1
206
+ Nloop_rw = Nloop_all // p
207
+ Nchunk &= ~1
208
+ Nloop_all = (Nloop_all + 1) & ~1
209
+ Nloop_rw = (Nloop_rw + 1) & ~1
210
+ Slists = [[0] * 3072 for _ in range(p)]
211
+ ctxs = [[2048, 1024, 0, 0] for _ in range(p)]
212
+ for i in range(p):
213
+ Vchunk = i * Nchunk
214
+ Np = Nchunk if i < p - 1 else N - Vchunk
215
+ Bp = B[i * s:(i + 1) * s]
216
+ S = Slists[i]
217
+ ctx = ctxs[i]
218
+ _smix1(Bp, 1, 96, False, S, 0, X, Y, None, None)
219
+ if i == 0:
220
+ key = struct.pack('<16I', *Bp[(2 * r - 1) * 16:2 * r * 16])
221
+ passwd = hmac_sha256(key, passwd)
222
+ _smix1(Bp, r, Np, True, V, Vchunk * s, X, Y, S, ctx)
223
+ _smix2(Bp, r, _p2floor(Np), Nloop_rw, True, V, Vchunk * s, X, Y, S, ctx)
224
+ B[i * s:(i + 1) * s] = Bp
225
+ for i in range(p):
226
+ Bp = B[i * s:(i + 1) * s]
227
+ _smix2(Bp, r, N, Nloop_all - Nloop_rw, False, V, 0, X, Y, Slists[i], ctxs[i])
228
+ B[i * s:(i + 1) * s] = Bp
229
+ return passwd
230
+
231
+
232
+ def yescrypt_rw(passwd, salt, N, r, p, t):
233
+ # Default 'j' flavor: RW with pwxform, 32-byte output.
234
+ # Large parameters first run a smaller pre-hash pass (yescrypt_kdf).
235
+ if N // p >= 0x100 and (N // p) * r >= 0x20000:
236
+ passwd = _kdf_body(passwd, salt, N >> 6, r, p, 0, True)
237
+ return _kdf_body(passwd, salt, N, r, p, t, False)
238
+
239
+
240
+ def _kdf_body(passwd, salt, N, r, p, t, prehash):
241
+ key = b'yescrypt-prehash' if prehash else b'yescrypt'
242
+ passwd = hmac_sha256(key, passwd)
243
+ n = 32 * r * p
244
+ B = list(struct.unpack('<%dI' % n, pbkdf2_sha256(passwd, salt, 1, 128 * r * p)))
245
+ passwd = struct.pack('<8I', *B[0:8])
246
+ V = [0] * (32 * r * N)
247
+ X = [0] * (32 * r)
248
+ Y = [0] * (32 * r)
249
+ passwd = _smix(B, r, N, p, t, passwd, V, X, Y)
250
+ dk = pbkdf2_sha256(passwd, struct.pack('<%dI' % n, *B), 1, 32)
251
+ if prehash:
252
+ return dk
253
+ client_key = hmac_sha256(dk, b'Client Key')
254
+ return sha256_digest(client_key)
255
+
256
+
@@ -0,0 +1,146 @@
1
+ # yescrypt setting and hash encoding, ported from yescrypt-common.c (1.0.3).
2
+
3
+ ITOA64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
4
+ ATOI64 = dict((c, i) for i, c in enumerate(ITOA64))
5
+
6
+ # Flavor character 'j' decodes to 47, which maps to RW flags 0xB6
7
+ # (ROUNDS_6 | GATHER_4 | SIMPLE_2 | SBOX_12K | RW).
8
+ DEFAULT_FLAVOR = 47
9
+
10
+
11
+ def encode_uint(value, minv):
12
+ """Variable-length base64 integer, as used for N, r, p, t in settings."""
13
+ if value < minv:
14
+ raise ValueError('value below minimum')
15
+ value -= minv
16
+ start, end, chars, bits = 0, 47, 1, 0
17
+ while True:
18
+ count = (end + 1 - start) << bits
19
+ if value < count:
20
+ break
21
+ if start >= 63:
22
+ raise ValueError('value too large')
23
+ start = end + 1
24
+ end = start + (62 - end) // 2
25
+ value -= count
26
+ chars += 1
27
+ bits += 6
28
+ out = [ITOA64[start + (value >> bits)]]
29
+ for _ in range(chars - 1):
30
+ bits -= 6
31
+ out.append(ITOA64[(value >> bits) & 0x3f])
32
+ return ''.join(out)
33
+
34
+
35
+ def decode_uint(s, pos, minv):
36
+ """Read one variable-length integer from s at pos. Returns (value, newpos)."""
37
+ start, end, chars, bits = 0, 47, 1, 0
38
+ c = _atoi(s, pos)
39
+ pos += 1
40
+ val = minv
41
+ while c > end:
42
+ val += (end + 1 - start) << bits
43
+ start = end + 1
44
+ end = start + (62 - end) // 2
45
+ chars += 1
46
+ bits += 6
47
+ val += (c - start) << bits
48
+ for _ in range(chars - 1):
49
+ c = _atoi(s, pos)
50
+ pos += 1
51
+ bits -= 6
52
+ val += c << bits
53
+ return val, pos
54
+
55
+
56
+ def _atoi(s, pos):
57
+ if pos >= len(s):
58
+ raise ValueError('truncated setting')
59
+ c = ATOI64.get(s[pos], 64)
60
+ if c > 63:
61
+ raise ValueError('invalid character in setting')
62
+ return c
63
+
64
+
65
+ def encode_bytes(data):
66
+ """Encode bytes as yescrypt base64 (little-endian bit stream, 6 bits per char)."""
67
+ out = []
68
+ acc = 0
69
+ bits = 0
70
+ for b in bytearray(data):
71
+ acc |= b << bits
72
+ bits += 8
73
+ while bits >= 6:
74
+ out.append(ITOA64[acc & 0x3f])
75
+ acc >>= 6
76
+ bits -= 6
77
+ if bits:
78
+ out.append(ITOA64[acc & 0x3f])
79
+ return ''.join(out)
80
+
81
+
82
+ def decode_bytes(s):
83
+ """Decode yescrypt base64 text to bytes. Trailing pad bits are ignored."""
84
+ out = bytearray()
85
+ acc = 0
86
+ bits = 0
87
+ for ch in s:
88
+ v = ATOI64.get(ch, 64)
89
+ if v > 63:
90
+ raise ValueError('invalid base64 character')
91
+ acc |= v << bits
92
+ bits += 6
93
+ while bits >= 8:
94
+ out.append(acc & 0xff)
95
+ acc >>= 8
96
+ bits -= 8
97
+ return bytes(out)
98
+
99
+
100
+ def parse_setting(setting):
101
+ """Parse '$y$<params>$<salt>' into a dict with N, r, p, t and salt bytes."""
102
+ if not setting.startswith('$y$'):
103
+ raise ValueError('not a yescrypt setting')
104
+ flavor, pos = decode_uint(setting, 3, 0)
105
+ if flavor != DEFAULT_FLAVOR:
106
+ raise ValueError('unsupported yescrypt flavor')
107
+ n_log2, pos = decode_uint(setting, pos, 1)
108
+ if n_log2 > 63:
109
+ raise ValueError('N out of range')
110
+ r, pos = decode_uint(setting, pos, 1)
111
+ p, t = 1, 0
112
+ if setting[pos:pos + 1] != '$':
113
+ have, pos = decode_uint(setting, pos, 1)
114
+ if have & ~3:
115
+ raise ValueError('unsupported yescrypt parameters')
116
+ if have & 1:
117
+ p, pos = decode_uint(setting, pos, 2)
118
+ if have & 2:
119
+ t, pos = decode_uint(setting, pos, 1)
120
+ if setting[pos:pos + 1] != '$':
121
+ raise ValueError('malformed yescrypt setting')
122
+ salt = decode_bytes(setting[pos + 1:])
123
+ return {'N': 1 << n_log2, 'r': r, 'p': p, 't': t, 'salt': salt}
124
+
125
+
126
+ def format_setting(N, r, p, t, salt):
127
+ """Build '$y$<params>$<salt>' for the default flavor."""
128
+ n_log2 = N.bit_length() - 1 if hasattr(N, 'bit_length') else _log2(N)
129
+ have = (1 if p != 1 else 0) | (2 if t else 0)
130
+ out = ['$y$', ITOA64[DEFAULT_FLAVOR], encode_uint(n_log2, 1), encode_uint(r, 1)]
131
+ if have:
132
+ out.append(encode_uint(have, 1))
133
+ if p != 1:
134
+ out.append(encode_uint(p, 2))
135
+ if t:
136
+ out.append(encode_uint(t, 1))
137
+ out.append('$')
138
+ out.append(encode_bytes(salt))
139
+ return ''.join(out)
140
+
141
+
142
+ def _log2(N):
143
+ n = 0
144
+ while (1 << (n + 1)) <= N:
145
+ n += 1
146
+ return n
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: yescrypt
3
+ Version: 1.0.0
4
+ Summary: Pure-Python yescrypt password hashing
5
+ Author: @example
6
+ Classifier: Intended Audience :: Developers
7
+ Classifier: Programming Language :: Python :: 2
8
+ Classifier: Programming Language :: Python :: 2.6
9
+ Classifier: Programming Language :: Python :: 2.7
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=2.6, !=3.0.*, !=3.1.*, !=3.2.*
13
+ Description-Content-Type: text/markdown
14
+ Dynamic: requires-python
15
+
16
+ # yescrypt
17
+
18
+ Pure-Python yescrypt password hashing. It uses only the standard library and runs on Python 2.6 and on Python 3.
19
+
20
+ It creates and verifies `$y$` hash strings compatible with libxcrypt, the crypt library used by many Linux distributions for `ENCRYPT_METHOD YESCRYPT`. Hashes made here can be checked by libcrypt, and the reverse also works.
21
+
22
+ ## Installation
23
+
24
+ ```
25
+ python setup.py install
26
+ ```
27
+
28
+ Or use the package directly by putting the `yescrypt/` directory on `PYTHONPATH`.
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ import yescrypt
34
+
35
+ hashed = yescrypt.hash_password('correct horse battery staple')
36
+ # '$y$j9T$<salt>$<43-character digest>'
37
+
38
+ yescrypt.verify('correct horse battery staple', hashed) # True
39
+ yescrypt.verify('wrong', hashed) # False
40
+ ```
41
+
42
+ ### `hash_password(password, salt=None, N=4096, r=32, p=1, t=0)`
43
+
44
+ Returns a hash string. `password` may be text (encoded as UTF-8) or bytes.
45
+
46
+ * `salt`: bytes or text, 1 to 64 bytes long. If omitted, 16 random bytes come from `os.urandom`.
47
+ * `N`: CPU/memory cost, a power of 2 greater than `p`. The default is 4096.
48
+ * `r`: block size. The default is 32. Working memory is about 128 × r × N bytes, which is 16 MiB for the defaults.
49
+ * `p`: parallelism. The default is 1.
50
+ * `t`: extra time cost. The default is 0.
51
+
52
+ Raises `ValueError` for invalid parameters or salt length, and `TypeError` for a password that isn't text or bytes.
53
+
54
+ ### `verify(password, hashed)`
55
+
56
+ Returns `True` if `password` produces `hashed`, otherwise `False`. The hash can be text or bytes. A malformed or unsupported hash string also returns `False` and does not raise an exception. The comparison runs in constant time.
57
+
58
+ ## Supported settings
59
+
60
+ * The default RW flavor (`$y$j...`), which is the one libxcrypt produces.
61
+ * Any valid `N`, `r`, `p` and `t`. The pre-hash pass that libxcrypt uses for large `N` is included.
62
+
63
+ Not supported, and rejected with `ValueError` or `False` from `verify`:
64
+
65
+ * The ROM and NROM modes.
66
+ * Hash upgrade (`g` greater than 0).
67
+ * Other flavors, including plain scrypt.
68
+
69
+ ## Performance
70
+
71
+ This is pure Python, so it is slow compared with the C implementation. The default settings take several seconds for each hash. Verification costs the same as hashing, because it recomputes the hash with the parameters stored in the string. For a login system, a native libcrypt binding is a better choice.
72
+
73
+ ## Testing
74
+
75
+ ```
76
+ python tests/test_yescrypt.py
77
+ ```
78
+
79
+ The default run takes about a minute and a quarter. To also run the two large-parameter vectors (about one minute more), set `YESCRYPT_SLOW_TESTS=1`.
80
+
81
+ The test vectors were generated once with the system libcrypt. The test suite does not use libcrypt. The scripts in `tests/` that call libcrypt (`gen_vectors.py`, `probe_settings.py`, `gen_extra.py`, `check_vectors.py`) are development helpers and are not needed to use the library.
82
+
83
+ ## Layout
84
+
85
+ ```
86
+ yescrypt/
87
+ __init__.py hash_password() and verify()
88
+ _core.py yescrypt RW calculation (port of yescrypt-ref.c)
89
+ _encoding.py base64 and $y$ setting encoding
90
+ _compat.py text/bytes, constant-time compare, HMAC and PBKDF2
91
+ tests/ unit tests and development helpers
92
+ ```
93
+
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ setup.py
4
+ tests/test_yescrypt.py
5
+ yescrypt/__init__.py
6
+ yescrypt/_compat.py
7
+ yescrypt/_core.py
8
+ yescrypt/_encoding.py
9
+ yescrypt.egg-info/PKG-INFO
10
+ yescrypt.egg-info/SOURCES.txt
11
+ yescrypt.egg-info/dependency_links.txt
12
+ yescrypt.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ yescrypt