Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import base64
- from Crypto.Cipher import AES
- from Crypto import Random
- secret_key = "abcdefghijklmnop" # not the real one =)
- #real version of this would do a database lookup
- #another user might be "admin" or "user2"
- def validate_credentials(user, password):
- if user == "user1" and password == "asdf":
- return True
- else:
- return False
- def pad(partial_block):
- pad_length = AES.block_size - len(partial_block) % AES.block_size
- if pad_length == 0:
- pad_length = AES.block_size
- return partial_block + chr(pad_length) * pad_length
- def unpad(decrypted_data):
- pad_length = ord(decrypted_data[-1])
- return decrypted_data[:-pad_length]
- # login authenticates the user with their password.
- #
- # Upon success, it creates an authentication token intended for the user
- # to pass with subsequent requests that require authentication.
- def login(user, password):
- if not validate_credentials(user, password):
- return ""
- iv = Random.new().read(AES.block_size)
- cipher = AES.new(secret_key, AES.MODE_CBC, iv )
- encrypted_user = cipher.encrypt(pad(user))
- return base64.b64encode(iv + encrypted_user)
- # get_user is used to extract the authenticated user name from a valid token
- def get_user(auth_token):
- auth_token = base64.b64decode(auth_token)
- iv = auth_token[:AES.block_size]
- cipher = AES.new(secret_key, AES.MODE_CBC, iv )
- decrypted_user = cipher.decrypt(auth_token[AES.block_size:])
- return unpad(decrypted_user)
- def main():
- token = raw_input("Do you have a token? (y/n)\n")
- if token == "y":
- ciphertext = raw_input("token?\n")
- user = get_user(ciphertext)
- print "You are logged in as", user
- else:
- user = raw_input("user?\n")
- password = raw_input("password?\n")
- token = login(user, password)
- if not token:
- print "Wrong credentials\n"
- else:
- print "Success. here's your token:"
- print token
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment