ยปCore Development>Code coverage>Lib/crypt.py

Python code coverage for Lib/crypt.py

#countcontent
1n/a"""Wrapper to the POSIX crypt library call and associated functionality."""
2n/a
3n/aimport _crypt
4n/aimport string as _string
5n/afrom random import SystemRandom as _SystemRandom
6n/afrom collections import namedtuple as _namedtuple
7n/a
8n/a
9n/a_saltchars = _string.ascii_letters + _string.digits + './'
10n/a_sr = _SystemRandom()
11n/a
12n/a
13n/aclass _Method(_namedtuple('_Method', 'name ident salt_chars total_size')):
14n/a
15n/a """Class representing a salt method per the Modular Crypt Format or the
16n/a legacy 2-character crypt method."""
17n/a
18n/a def __repr__(self):
19n/a return '<crypt.METHOD_{}>'.format(self.name)
20n/a
21n/a
22n/adef mksalt(method=None):
23n/a """Generate a salt for the specified method.
24n/a
25n/a If not specified, the strongest available method will be used.
26n/a
27n/a """
28n/a if method is None:
29n/a method = methods[0]
30n/a s = '${}$'.format(method.ident) if method.ident else ''
31n/a s += ''.join(_sr.choice(_saltchars) for char in range(method.salt_chars))
32n/a return s
33n/a
34n/a
35n/adef crypt(word, salt=None):
36n/a """Return a string representing the one-way hash of a password, with a salt
37n/a prepended.
38n/a
39n/a If ``salt`` is not specified or is ``None``, the strongest
40n/a available method will be selected and a salt generated. Otherwise,
41n/a ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
42n/a returned by ``crypt.mksalt()``.
43n/a
44n/a """
45n/a if salt is None or isinstance(salt, _Method):
46n/a salt = mksalt(salt)
47n/a return _crypt.crypt(word, salt)
48n/a
49n/a
50n/a# available salting/crypto methods
51n/aMETHOD_CRYPT = _Method('CRYPT', None, 2, 13)
52n/aMETHOD_MD5 = _Method('MD5', '1', 8, 34)
53n/aMETHOD_SHA256 = _Method('SHA256', '5', 16, 63)
54n/aMETHOD_SHA512 = _Method('SHA512', '6', 16, 106)
55n/a
56n/amethods = []
57n/afor _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5, METHOD_CRYPT):
58n/a _result = crypt('', _method)
59n/a if _result and len(_result) == _method.total_size:
60n/a methods.append(_method)
61n/adel _result, _method