usr_mgr.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. '''
  2. This file implements user management program. The user name and
  3. its password is saved in csv file.
  4. '''
  5. import random
  6. from hashlib import sha1
  7. import csv
  8. class PasswordHash(object):
  9. def __init__(self, password_):
  10. self.salt = "".join(chr(random.randint(33, 127)) for x in range(64))
  11. self.saltedpw = sha1((password_ + self.salt).encode()).hexdigest()
  12. def check_password(self, password_):
  13. """checks if the password is correct"""
  14. return self.saltedpw == sha1((password_ + self.salt).encode()).hexdigest()
  15. # Note: a secure application would never store passwords in plaintext in the source code
  16. def check_username(name):
  17. csvfile = open('passwd.csv')
  18. ret = 0
  19. reader = csv.reader(csvfile)
  20. for row in reader:
  21. if name == row[0]:
  22. ret = 1
  23. break
  24. csvfile.close()
  25. return ret
  26. def save_info(name,pw,salt):
  27. csvfile = open('passwd.csv', 'a')
  28. writer = csv.writer(csvfile)
  29. writer.writerow([name, pw, salt])
  30. csvfile.close()
  31. def register():
  32. flag = True
  33. # create the file if it doesn't exist
  34. csvfile = open('passwd.csv', "w")
  35. csvfile.close()
  36. while flag :
  37. username = input("username:")
  38. passwd = input("passwd:")
  39. if check_username(username):
  40. print("the usename already exist!")
  41. else :
  42. pwhash = PasswordHash(passwd)
  43. save_info(username,pwhash.saltedpw, pwhash.salt)
  44. print("register success!")
  45. flag = False
  46. register()