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