Guest User

Untitled

a guest
Feb 1st, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. import hashlib
  2. import secrets
  3. import os, sys
  4. import getpass
  5.  
  6. HASHTYPE = "sha256"
  7. HASHITERS = 1000
  8.  
  9. SECTS = (64, 32, 32)
  10. SECTLEN = sum(SECTS)
  11. #assert sum(SECTS) == SECTLEN, "Invalid division of sections." # implied in defenition
  12.  
  13. file = os.path.expanduser("~/.pswd.db")
  14.  
  15. def write(rows=[]):
  16. with open(file, "wb") as f:
  17. for row in rows:
  18. for col in row:
  19. f.write(col)
  20.  
  21. def add(uname, pswd):
  22. #data = hashlib.md5(uname.encode("utf-8")).digest() # 16 byte MD5 uname hash
  23. data = uname.encode("utf-8")[:SECTS[0]].ljust(SECTS[0], b"\x00") # 32 byte UTF8 name, null-padded
  24.  
  25. salt = secrets.token_bytes(SECTS[2])
  26. pswdhash = hashlib.pbkdf2_hmac(HASHTYPE, pswd.encode("utf-8"), salt, HASHITERS)
  27. data += pswdhash + salt
  28.  
  29. assert len(data) == SECTLEN, "Invalid data section length."
  30.  
  31. with open(file, mode="ab") as f:
  32. f.write(data)
  33.  
  34. def read():
  35. with open(file, mode="rb") as f:
  36. raw = f.read()
  37. if len(raw) % SECTLEN != 0:
  38. print("WARNING: password file has invalid length; discarding end", file=sys.stderr)
  39. rows = []
  40. for x in range(0, len(raw), SECTLEN):
  41. row = []
  42. c = 0
  43. for s in SECTS:
  44. row.append(raw[x+c:x+c+s])
  45. c += s
  46. rows.append(row)
  47. write(rows)
  48. return rows
  49.  
  50. fails = 0
  51. success = False
  52. while fails < 5 and not success:
  53. user = input("Username: ")
  54.  
  55. #if hashlib.md5(user.encode("utf-8")).digest() in map(lambda x: x[0], read()):
  56. if user.encode("utf-8")[:SECTS[0]].ljust(SECTS[0], b"\x00") in map(lambda x: x[0], read()):
  57. # user is in database
  58. #index = list(map(lambda x: x[0], read())).index(hashlib.md5(user.encode("utf-8")).digest())
  59. index = list(map(lambda x: x[0], read())).index(user.encode("utf-8")[:SECTS[0]].ljust(SECTS[0], b"\x00"))
  60. userhash, pswdhash, salt = read()[index]
  61.  
  62. pswd = getpass.getpass("Password: ")
  63. if hashlib.pbkdf2_hmac(HASHTYPE, pswd.encode("utf-8"), salt, HASHITERS) == pswdhash:
  64. success = True
  65. else:
  66. print("Incorrect password.")
  67. fails += 1
  68.  
  69. else:
  70. yn = input("Unrecognised username. Would you like to create an account? (y/n) ")
  71. if yn.lower()[0] == "y":
  72. pswd1 = getpass.getpass("Password: ")
  73. pswd2 = getpass.getpass("Confirm: ")
  74. if pswd1 != pswd2:
  75. print("Non-matching passwords. Aborting.")
  76. else:
  77. add(user, pswd1)
  78. else:
  79. print("Aborting.")
  80.  
  81. if success:
  82. print(f"Welcome, {user}!")
  83. # more program here
  84. else:
  85. print("Locked out.")
Add Comment
Please, Sign In to add comment