Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""LICENSE 

2Copyright 2019 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of puffotter. 

5 

6puffotter is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11puffotter is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with puffotter. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20import bcrypt 

21import random 

22import string 

23 

24 

25def generate_random(length: int) -> str: 

26 """ 

27 Generates a random byte string consisting of alphanumeric characters 

28 Thanks @ Albert (https://stackoverflow.com/users/281021/albert) 

29 https://stackoverflow.com/questions/2257441 

30 :param length: The length of the string to generate 

31 :return: The generated random byte string 

32 """ 

33 return bytes( 

34 "".join(random.choice(string.ascii_uppercase + string.digits) 

35 for _ in range(length)), 

36 "utf-8" 

37 ).decode("utf-8") 

38 

39 

40def generate_hash(password: str) -> str: 

41 """ 

42 Salts and hashes a password to generate a hash for storage in a database 

43 :param password: The password to hash 

44 :return: The hash of the password 

45 """ 

46 password_bytes = bytes(password, "utf-8") 

47 return bcrypt.hashpw(password_bytes, bcrypt.gensalt()).decode("utf-8") 

48 

49 

50def verify_password(password: str, hashed: str): 

51 """ 

52 Verifies that a password matches a given hash 

53 :param password: The password to verify 

54 :param hashed: The hash to verify the password against 

55 :return: True if the password matches, otherwise False 

56 """ 

57 password_bytes = bytes(password, "utf-8") 

58 hashed_bytes = bytes(hashed, "utf-8") 

59 

60 try: 

61 return bcrypt.checkpw(password_bytes, hashed_bytes) 

62 except ValueError: 

63 return False