root / snf-image-helper / snf-passtohash.py @ 6a95db10
History | View | Annotate | Download (1.7 kB)
1 |
#!/usr/bin/env python
|
---|---|
2 |
#
|
3 |
# Copyright (c) 2011 Greek Research and Technology Network
|
4 |
#
|
5 |
"""Generate a hash from a given password
|
6 |
|
7 |
This program takes a password as an argument and
|
8 |
returns to standard output a hash followed by a newline.
|
9 |
To do this, it generates a random salt internally.
|
10 |
|
11 |
"""
|
12 |
|
13 |
import sys |
14 |
import crypt |
15 |
|
16 |
from string import ascii_letters, digits |
17 |
from random import choice |
18 |
from os.path import basename |
19 |
from optparse import OptionParser |
20 |
|
21 |
|
22 |
# This dictionary maps the hashing algorithm method
|
23 |
# with its <ID> as documented in:
|
24 |
# http://www.akkadia.org/drepper/SHA-crypt.txt
|
25 |
HASH_ID_FROM_METHOD = { |
26 |
'md5': '1', |
27 |
'blowfish': '2a', |
28 |
'sun-md5': 'md5', |
29 |
'sha256': '5', |
30 |
'sha512': '6' |
31 |
} |
32 |
|
33 |
def random_salt(length=8): |
34 |
pool = ascii_letters + digits + "/" + "." |
35 |
return ''.join(choice(pool) for i in range(length)) |
36 |
|
37 |
|
38 |
def parse_arguments(input_args): |
39 |
usage = "usage: %prog [-h] [-m encrypt-method] <password>"
|
40 |
parser = OptionParser(usage=usage) |
41 |
parser.add_option("-m", "--encrypt-method", |
42 |
dest="encrypt_method",
|
43 |
type='choice',
|
44 |
default="sha512",
|
45 |
choices=HASH_ID_FROM_METHOD.keys(), |
46 |
help="encrypt password with ENCRYPT_METHOD [%default] \
|
47 |
(supported: " + ", ".join(HASH_ID_FROM_METHOD.keys()) +")", |
48 |
) |
49 |
|
50 |
(opts, args) = parser.parse_args(input_args) |
51 |
|
52 |
if len(args) != 1: |
53 |
parser.error('password is missing')
|
54 |
|
55 |
return (args[0], opts.encrypt_method) |
56 |
|
57 |
|
58 |
def main(): |
59 |
(password, method) = parse_arguments(sys.argv[1:])
|
60 |
salt = random_salt() |
61 |
hash = crypt.crypt(password, "$"+HASH_ID_FROM_METHOD[method]+"$"+salt) |
62 |
sys.stdout.write("%s\n" % (hash)) |
63 |
return 0 |
64 |
|
65 |
if __name__ == "__main__": |
66 |
sys.exit(main()) |
67 |
|
68 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|