1 from base64 import b64decode, b64encode
2 from hashlib import pbkdf2_hmac, md5
5 def password_is_correct(password_plain, password_db):
6 """Returns true if a plain text password corresponds to the hash of the password as stored in the MediaWiki db.
8 :param password_plain: plain text password as string, e.g. 'abc'
9 :param password_db: complete password line as string as stored in the database,
10 e.g. ':pbkdf2:sha256:10000:128:EXgVGhc2mAs710feKvkiaw==:J5fYth9pg/R2d0F8bSsYfTR8SBpTBNIcdv/DgJ0tOPC' +
11 '1rtajl2Dr0RLqOozLb8O0XpDhtv4a3JJd/M0b58WebfNWAcdJBJI9nNeC0EYYD7OCYZGVAaRhiYtK4m53KZBBL6x/k2j4' +
12 'RjHPT1NmgV8Fr1DPqBNOlOHxUIh5z5oslM4='
14 if not password_db.startswith(':'):
15 raise ValueError("Password entry in the database does have an unexpected format (does not start with ':').")
16 pwd_parts = password_db[1:].split(':')
17 pwd_type = pwd_parts[0]
20 # example: password_db == ':B:d25b2886:41e46c952790b1b442aac4f24f7ea7a8'
21 # pwd_parts == ['B', 'd25b2886', '41e46c952790b1b442aac4f24f7ea7a8']
22 if len(pwd_parts) != 3:
23 raise ValueError("Password entry in the database does have an unexpected format (too few ':').")
24 salt, pwd_md5 = tuple(pwd_parts[1:3]) # salt = 'd25b2886'; pwd_md5 = '41e46c952790b1b442aac4f24f7ea7a8'
25 # log.info("user: '%s'; md5 of salt+' '+entered_pwd: '%s'; md5-part of DB-pwd: %s"
26 # % (username, md5(salt + '-' + md5(password)), pwd_md5))
27 salt_and_plain = salt + '-' + md5(password_plain.encode()).hexdigest()
28 return md5(salt_and_plain.encode()).hexdigest() == pwd_md5
29 elif pwd_type == 'pbkdf2':
30 if len(pwd_parts) != 6:
31 raise ValueError("Password entry in the database does have an unexpected format (too few ':').")
32 _, algorithm, rounds, num_bit, salt, pwd_hash = pwd_parts
33 salt = b64decode(salt)
34 hashcode = pbkdf2_hmac(algorithm, password_plain.encode(), salt, int(rounds), int(num_bit))
35 hashcode = b64encode(hashcode).decode()
36 return hashcode == pwd_hash
38 raise ValueError("Unknown password type")