seg/trabalho2/server.py

85 lines
2.6 KiB
Python

from hashlib import sha256
import string
import localtoken
import random
import os
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))
hashed_salt = sha256(salt.encode('utf-8')).hexdigest()
line = f'{user},{seed_password},{hashed_salt}\n'
with open('server.dat', 'a', newline='') as setup:
setup.write(line)
print(f'Usuário registrado com sucesso! Salt: [{salt}]')
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', '')
if line.split(',')[0] == user:
password = line.split(',')[1]
salt = line.split(',')[2]
break
else:
print('Usuário incorreto!')
return
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
password = localtoken.get_salted_password(password, salt)
valid, index = localtoken.validate_token(password, token)
if valid:
if index >= used_index and used_timestamp == localtoken.get_timestamp():
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()
if __name__ == '__main__':
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()
main()