snf-passtohash.py 2.35 KB
Newer Older
Nikos Skalkotos's avatar
Nikos Skalkotos committed
1
#!/usr/bin/env python
2
3
4
5
6
7
8

# Copyright (C) 2011 GRNET S.A. 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
Nikos Skalkotos's avatar
Nikos Skalkotos committed
9
#
10
11
12
13
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
Nikos Skalkotos's avatar
Nikos Skalkotos committed
14
#
15
16
17
18
19
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

20
"""Generate a hash from a given password
Nikos Skalkotos's avatar
Nikos Skalkotos committed
21

22
This program takes a password as an argument and
Nikos Skalkotos's avatar
Nikos Skalkotos committed
23
returns to standard output a hash followed by a newline.
24
To do this, it generates a random salt internally.
Nikos Skalkotos's avatar
Nikos Skalkotos committed
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
76
77
78
79
80
81
82
83

"""

import sys
import crypt 

from string import ascii_letters, digits
from random import choice
from os.path import basename
from optparse import OptionParser


# This dictionary maps the hashing algorithm method
# with its <ID> as documented in:
# http://www.akkadia.org/drepper/SHA-crypt.txt
HASH_ID_FROM_METHOD = {
    'md5': '1',
    'blowfish': '2a',
    'sun-md5': 'md5',
    'sha256': '5',
    'sha512': '6'
}

def random_salt(length=8):
    pool = ascii_letters + digits + "/" + "."
    return ''.join(choice(pool) for i in range(length))


def parse_arguments(input_args):
    usage = "usage: %prog [-h] [-m encrypt-method] <password>"
    parser = OptionParser(usage=usage)
    parser.add_option("-m", "--encrypt-method",
			dest="encrypt_method",
			type='choice',
			default="sha512",
			choices=HASH_ID_FROM_METHOD.keys(),
			help="encrypt password with ENCRYPT_METHOD [%default] \
			(supported: " + ", ".join(HASH_ID_FROM_METHOD.keys()) +")",
    )

    (opts, args) = parser.parse_args(input_args)

    if len(args) != 1:
	parser.error('password is missing')

    return (args[0], opts.encrypt_method)


def main():
    (password, method) = parse_arguments(sys.argv[1:])
    salt = random_salt()
    hash = crypt.crypt(password, "$"+HASH_ID_FROM_METHOD[method]+"$"+salt)
    sys.stdout.write("%s\n" % (hash))
    return 0

if __name__ == "__main__":
        sys.exit(main())

# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :