finalizando trab 2
This commit is contained in:
+72
-21
@@ -1,34 +1,85 @@
|
||||
from hashlib import sha256
|
||||
import string
|
||||
import localtoken
|
||||
import random
|
||||
import os
|
||||
|
||||
'''
|
||||
Quando acessado usa o mesmo algoritmo gerador de senhas anterior. Mas em instância separada.
|
||||
A lista de senha gerada será a mesma nas duas partes, apesar de estarem em aplicativos separados e sem comunicação.
|
||||
Verifica o usuário e se senha digitada esta na lista gerada e não foi usada e nem invalidada.
|
||||
nesta caso apresenta “Chave válida”.
|
||||
Atenção:
|
||||
As senhas devem ter validade de no máximo um minuto e só podem ser usadas uma única vez.
|
||||
Senhas são geradas a partir de outras senhas, e se for usada uma chave todas as chaves geradas pela mesma devem ser invalidadas.
|
||||
Se o cliente digitar uma senha válida o servidor aceita, caso contrario retorna mensagem de erro.
|
||||
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))
|
||||
salt = sha256(salt.encode('utf-8')).hexdigest()
|
||||
|
||||
'''
|
||||
line = f'{user},{seed_password},{salt}\n'
|
||||
with open('server.dat', 'a', newline='') as setup:
|
||||
setup.write(line)
|
||||
|
||||
SALT = ''
|
||||
PASSWORD = ''
|
||||
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 used_index <= 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():
|
||||
print('Servidor!')
|
||||
SALT = sha256(input('Digite o salt: ').encode('utf-8')).hexdigest()
|
||||
PASSWORD = sha256(input('Digite a senha: ').encode('utf-8')).hexdigest()
|
||||
|
||||
while True:
|
||||
token = input('Digite o token: ')
|
||||
if localtoken.generate_token(PASSWORD, SALT)[:8] == token[:8]:
|
||||
print('Chave válida!')
|
||||
else:
|
||||
print('Chave inválida!')
|
||||
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()
|
||||
Reference in New Issue
Block a user