Coverage for src/lightmlrestapi/args/encrypt_helper.py: 84%
43 statements
« prev ^ index » next coverage.py v6.4.1, created at 2022-06-06 07:16 +0200
« prev ^ index » next coverage.py v6.4.1, created at 2022-06-06 07:16 +0200
1"""
2@file
3@brief Helper about encryption.
4"""
5import os
6import hashlib
7from io import StringIO
8import pandas
11def encrypt_password(pwd, algo="sha224"):
12 """
13 Encrypts one password.
15 @param pwd string
16 @param algo algorithm used to hash passwords
17 @return encrypted password
18 """
19 if algo == "sha224":
20 return hashlib.sha224(pwd.encode('ascii')).hexdigest()
21 else:
22 raise NotImplementedError(
23 "Algorithm '{0}' is not implemented.".format(algo))
26def encrypt_passwords(users, algo="sha224"):
27 """
28 Encrypts users passwords.
30 @param users dataframe or...
31 @param algo algorithm used to hash passwords
32 @return password are replaced by the hashed passwords
33 """
34 if isinstance(users, list):
35 res = []
36 for login, pwd in users:
37 pwd = encrypt_password(pwd, algo=algo)
38 res.append((login, pwd))
39 return res
40 elif hasattr(users, "values"):
41 df = users.copy()
42 col = df.columns[1]
43 df[col] = df[col].apply(lambda pwd: encrypt_password(pwd, algo=algo))
44 return df
45 else:
46 raise TypeError("Unexpected type '{0}'".format(type(users)))
49def load_passwords(source):
50 """
51 Loads the encrypted passwords from a filename, a dataframe,
52 a list of tuple.
54 @param source filename, dataframe
55 @return dictionary ``{user: encrypted_pwd}``
56 """
57 if isinstance(source, str):
58 if "\n" in source or ',' in source:
59 st = StringIO(source)
60 df = pandas.read_csv(st, encoding="utf-8", header=None)
61 elif os.path.exists(source):
62 df = pandas.read_csv(source, encoding="utf-8", header=None)
63 else:
64 raise ValueError("Unexpected string '{0}'".format(source))
65 elif isinstance(source, dict):
66 return source
67 elif hasattr(source, "values"):
68 df = source
69 elif isinstance(source, list):
70 res = {}
71 for a, b in source:
72 res[a] = b
73 return res
74 else:
75 raise TypeError("Unable to interpret type '{0}'".format(type(source)))
77 # dataframe
78 res = {}
79 for i in range(df.shape[0]):
80 res[df.iloc[i, 0]] = df.iloc[i, 1]
81 return res