· 9 years ago · Oct 05, 2016, 08:14 AM
1import base64
2from Crypto.Cipher import AES
3from Crypto import Random
4
5secret_key = "abcdefghijklmnop" # not the real one =)
6
7#real version of this would do a database lookup
8#another user might be "admin" or "user2"
9def validate_credentials(user, password):
10 if user == "user1" and password == "asdf":
11 return True
12 else:
13 return False
14
15def pad(partial_block):
16 pad_length = AES.block_size - len(partial_block) % AES.block_size
17 if pad_length == 0:
18 pad_length = AES.block_size
19 return partial_block + chr(pad_length) * pad_length
20
21def unpad(decrypted_data):
22 pad_length = ord(decrypted_data[-1])
23 return decrypted_data[:-pad_length]
24
25# login authenticates the user with their password.
26#
27# Upon success, it creates an authentication token intended for the user
28# to pass with subsequent requests that require authentication.
29def login(user, password):
30 if not validate_credentials(user, password):
31 return ""
32
33 iv = Random.new().read(AES.block_size)
34 cipher = AES.new(secret_key, AES.MODE_CBC, iv )
35
36 encrypted_user = cipher.encrypt(pad(user))
37 return base64.b64encode(iv + encrypted_user)
38
39# get_user is used to extract the authenticated user name from a valid token
40def get_user(auth_token):
41 auth_token = base64.b64decode(auth_token)
42
43 iv = auth_token[:AES.block_size]
44 cipher = AES.new(secret_key, AES.MODE_CBC, iv )
45
46 decrypted_user = cipher.decrypt(auth_token[AES.block_size:])
47 return unpad(decrypted_user)
48
49def main():
50
51 token = raw_input("Do you have a token? (y/n)\n")
52
53 if token == "y":
54 ciphertext = raw_input("token?\n")
55
56 user = get_user(ciphertext)
57
58 print "You are logged in as", user
59 else:
60 user = raw_input("user?\n")
61 password = raw_input("password?\n")
62
63 token = login(user, password)
64
65 if not token:
66 print "Wrong credentials\n"
67 else:
68 print "Success. here's your token:"
69 print token
70
71if __name__ == "__main__":
72 main()