]> git.phdru.name Git - m_lib.git/blob - m_lib/mcrypt.py
Fix raw_input for Py3 compatibility
[m_lib.git] / m_lib / mcrypt.py
1 #! /usr/bin/env python
2
3 #
4 # useful function(s) for module crypt
5 #
6
7
8 from __future__ import print_function
9 import random, crypt
10
11
12 saltchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz0123456789./"
13 len_salt = len(saltchars)
14
15 def gen_salt():
16    """
17       There are some difference among modern unicies. BSD/OS, for example,
18       uses MD5 hash, and ignores salt completely. FreeBSD uses 3 different
19       versions of crypt() - with standard salt, with extended 9-byte salt,
20       and MD5 (again, ignoring salt at all).
21       This function generates salt for standard "Broken DES"-based crypt().
22    """
23    r1 = random.randint(0, len_salt-1)
24    r2 = random.randint(0, len_salt-1)
25    return "%s%s" % (saltchars[r1], saltchars[r2])
26
27
28 def test():
29    try:
30       raw_input
31    except NameError:  # Python 3
32       raw_input = input
33
34    passwd = raw_input("Enter password: ")
35    salt = gen_salt()
36    encrypted = crypt.crypt(passwd, salt)
37
38    pwd_file = open("test.pwd", 'w')
39    pwd_file.write("%s:%s" % ("user", encrypted))
40    pwd_file.close()
41    print("Password file written")
42
43    pwd_file = open("test.pwd", 'r')
44    username, encrypted = pwd_file.readline()[:-1].split(':')
45    pwd_file.close()
46
47    if crypt.crypt(encrypted, encrypted):
48       print("Password verified Ok")
49    else:
50       print("BAD password")
51
52 if __name__ == "__main__":
53    test()