forked from scottt/scottt-bin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt
executable file
·75 lines (60 loc) · 2.14 KB
/
crypt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python
import sys
import os
import crypt as crypt_module
import random
import string
import optparse
def program_name():
return os.path.basename(sys.argv[0])
main_function_list = []
def main_function(func):
global main_function_list
main_function_list.append(func)
return func
def main(args):
def to_command_name(s):
return s.replace('_', '-')
name_to_function = dict( (to_command_name(x.__name__), x)
for x in main_function_list )
return name_to_function[program_name()](args)
def salt_gen(length):
salt_candidates = string.letters + string.digits + './'
return ''.join( random.choice(salt_candidates) for x in xrange(8) )
def crypt_main(args, salt_len, salt_prefix):
global crypt_options
op = optparse.OptionParser(usage='usage: %prog [ OPTIONS ]\n'
'input is read from the "PASSWORD" environment variable', option_list = [
optparse.Option('--salt', default=None),
])
(options, args) = op.parse_args(args)
pure_text = os.environ.get('PASSWORD')
if args or (pure_text is None):
op.print_usage()
sys.exit(2)
if options.salt is not None and len(options.salt) != salt_len:
sys.stderr.write('%s: salt length must be %d not %d\n' % (program_name(),
salt_len, len(options.salt)))
sys.exit(2)
if options.salt is None:
salt = salt_gen(salt_len)
else:
salt = options.salt
cipher_text = crypt_module.crypt(pure_text, salt_prefix + salt)
sys.stdout.write(cipher_text + '\n')
@main_function
def crypt(args):
return crypt_main(args, salt_len=2, salt_prefix='')
@main_function
def md5crypt(args):
# For "$1$" as salt prefix, see Glibc Notes in
# http://man7.org/linux/man-pages/man3/crypt.3.html
return crypt_main(args, salt_len=8, salt_prefix='$1$')
@main_function
def sha256crypt(args):
return crypt_main(args, salt_len=16, salt_prefix='$5$')
@main_function
def sha512crypt(args):
return crypt_main(args, salt_len=16, salt_prefix='$6$')
if __name__ == '__main__':
main(sys.argv[1:])