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