-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_password_hash.py
executable file
·100 lines (79 loc) · 2.75 KB
/
generate_password_hash.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""Avaiable password schemes: BCRYPT, SSHA512, SSHA, MD5, NTLM."""
import os
import sys
from subprocess import Popen, PIPE
from base64 import b64encode
# Do not prefix password scheme name in password hash.
HASHES_WITHOUT_PREFIXED_PASSWORD_SCHEME = ['NTLM', 'MD5']
def generate_bcrypt_password(p):
try:
import bcrypt
except:
return generate_ssha_password(p)
return '{CRYPT}' + bcrypt.hashpw(p, bcrypt.gensalt())
def generate_ssha512_password(p):
"""Generate salted SHA512 password with prefix '{SSHA512}'.
Return SSHA instead if python is older than 2.5 (not supported in module hashlib)."""
p = str(p).strip()
try:
from hashlib import sha512
salt = os.urandom(8)
pw = sha512(p)
pw.update(salt)
return '{SSHA512}' + b64encode(pw.digest() + salt)
except ImportError, e:
print e
# Use SSHA password instead if python is older than 2.5.
return generate_ssha_password(p)
def generate_ssha_password(p):
p = str(p).strip()
salt = os.urandom(8)
try:
from hashlib import sha1
pw = sha1(p)
except ImportError:
import sha
pw = sha.new(p)
pw.update(salt)
return "{SSHA}" + b64encode(pw.digest() + salt)
def generate_md5_password(p):
p = str(p).strip()
pp = Popen(['openssl', 'passwd', '-1', p], stdout=PIPE)
pw = pp.communicate()[0]
if 'MD5' in HASHES_WITHOUT_PREFIXED_PASSWORD_SCHEME:
return pw
else:
return '{CRYPT}' + pw
def generate_password_with_doveadmpw(scheme, plain_password):
"""Generate password hash with `doveadm pw` command.
Return SSHA instead if no 'doveadm' command found or other error raised."""
# scheme: CRAM-MD5, NTLM
scheme = scheme.upper()
p = str(plain_password).strip()
try:
pp = Popen(['doveadm', 'pw', '-s', scheme, '-p', p],
stdout=PIPE)
pw = pp.communicate()[0]
if scheme in HASHES_WITHOUT_PREFIXED_PASSWORD_SCHEME:
pw = pw.lstrip('{' + scheme + '}')
return pw
except:
return generate_ssha_password(p)
if __name__ == '__main__':
if len(sys.argv) < 3:
sys.exit('Usage:\n\t# python ./generate_password_hash.py <scheme> <password>\n')
scheme = sys.argv[1].upper()
password = sys.argv[2]
if scheme == 'BCRYPT':
print generate_bcrypt_password(password)
elif scheme == 'SSHA512':
print generate_ssha512_password(password)
elif scheme == 'SSHA':
print generate_ssha_password(password)
elif scheme == 'MD5':
print generate_md5_password(password)
elif scheme == 'NTLM':
print generate_password_with_doveadmpw('NTLM', password)
else:
# Plain
print generate_ssha_password(password)