seg/trabalho2/server.py

85 lines
2.6 KiB
Python
Raw Permalink Normal View History

2023-09-11 20:30:47 +00:00
from hashlib import sha256
2023-09-12 14:21:31 +00:00
import string
2023-09-11 20:30:47 +00:00
import localtoken
2023-09-12 14:21:31 +00:00
import random
import os
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
def register_user():
user = input('Digite o usuário: ')
seed_password = sha256(input('Digite a senha: ').encode('utf-8')).hexdigest()
salt = ''.join(random.choice(string.ascii_letters) for i in range(16))
2023-09-12 21:09:54 +00:00
hashed_salt = sha256(salt.encode('utf-8')).hexdigest()
2023-09-06 20:01:35 +00:00
2023-09-12 21:09:54 +00:00
line = f'{user},{seed_password},{hashed_salt}\n'
2023-09-12 14:21:31 +00:00
with open('server.dat', 'a', newline='') as setup:
setup.write(line)
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
print(f'Usuário registrado com sucesso! Salt: [{salt}]')
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
def validate_token():
user = input('Digite o usuário: ')
token = input('Digite o token: ')
password = ''
salt = ''
with open('server.dat', 'r', newline='') as setup:
for line in setup:
if len(line) == 0:
continue
line = line.replace('\n', '')
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
if line.split(',')[0] == user:
password = line.split(',')[1]
salt = line.split(',')[2]
break
2023-09-11 20:30:47 +00:00
else:
2023-09-12 14:21:31 +00:00
print('Usuário incorreto!')
return
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
used_index = -1
used_timestamp = ''
with open('used_tokens.dat', 'r', newline='') as used_tokens:
for used_token in reversed(list(used_tokens)):
used_token = used_token.replace('\n', '')
if used_token.split(',')[0] == user:
used_index = int(used_token.split(',')[1])
used_timestamp = used_token.split(',')[2]
break
2023-09-11 20:30:47 +00:00
2023-09-12 14:21:31 +00:00
password = localtoken.get_salted_password(password, salt)
valid, index = localtoken.validate_token(password, token)
if valid:
2023-09-12 21:09:54 +00:00
if index >= used_index and used_timestamp == localtoken.get_timestamp():
2023-09-12 14:21:31 +00:00
print('Chave inválida (invalidada)!')
else:
print('Chave válida!')
with open('used_tokens.dat', 'a', newline='') as used_tokens:
line = f'{user},{index},{localtoken.get_timestamp()}'
used_tokens.write(line + '\n')
else:
print('Chave inválida!')
def main():
while True:
print('Selecione uma opção:')
print('1 - Registrar usuário')
print('2 - Validar token')
print('0 - Sair')
option = input('Digite a opção: ')
if option == '1':
register_user()
elif option == '2':
validate_token()
elif option == '0':
exit()
2023-09-11 20:30:47 +00:00
if __name__ == '__main__':
2023-09-12 14:21:31 +00:00
if not os.path.exists('server.dat'):
open('server.dat', 'w').close()
if not os.path.exists('used_tokens.dat'):
open('used_tokens.dat', 'w').close()
2023-09-11 20:30:47 +00:00
main()