def test_verify_sha256(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) totp.verify(totp_value, time)
def test_invalid_verify(self, backend): secret = b"12345678901234567890" time = 59 totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) with pytest.raises(InvalidToken): totp.verify(b"12345678", time)
def test_invalid_verify(self, backend): secret = b"12345678901234567890" time = 59 totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) with pytest.raises(InvalidToken): totp.verify(b"12345678", time)
def test_verify_sha512(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA512(), 30, backend) assert totp.verify(totp_value, time) is None
def test_verify_sha256(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) assert totp.verify(totp_value, time) is None
def check_qrcode_credential(request): if request.method == 'POST': if not Method.objects.get(name='QRCode').status: return JsonResponse(create_msg_to_send(create_status_msg(400, 'QRCode authentication disabled!'), RASP_RSAPUB_KEY)) msg = json.loads(decrypt_msg(request.POST, RASP_ECCPUB_KEY)) msg = json.loads(msg) email = msg['identity'] if User.objects.filter(username=email).exists(): user = User.objects.get(username=email) else: return JsonResponse(create_msg_to_send(create_status_msg(400, 'User does not exist!'), RASP_RSAPUB_KEY)) # TODO: Permission validation (and perm.end_time > timezone.now()) perm = Permission.objects.get(user=user) if perm.state and perm.start_time < timezone.now(): credential = Credential.objects.get(user=user) if credential is not None and credential.status == 'valid': key = bytes.fromhex(credential.data) totp = TOTP(key, 8, SHA256(), 30, backend=default_backend()) try: totp.verify(msg['password'].encode(), time.time()) except InvalidToken: return JsonResponse(create_msg_to_send(create_status_msg(400, 'Authentication Failed!'), RASP_RSAPUB_KEY)) logs = Log.objects.select_related().filter(user=user).all().order_by('time_stamp').reverse() if logs: if logs[0].log_type == 'leave': log = Log(user=user, log_type='entry', time_stamp=timezone.now()) log.save() last_access = {'name': user.last_name, 'img': user.profile.photo.url} send_last_access(last_access) else: log = Log(user=user, log_type='leave', time_stamp=timezone.now()) log.save() else: log = Log(user=user, log_type='entry', time_stamp=timezone.now()) log.save() last_access = {'name': user.last_name, 'img': user.profile.photo.url} send_last_access(last_access) return JsonResponse(create_msg_to_send(create_status_msg(200, 'Authentication Successful', user.last_name.split()[0]), RASP_RSAPUB_KEY)) else: return JsonResponse(create_msg_to_send(create_status_msg(400, 'No permission!'), RASP_RSAPUB_KEY)) else: return JsonResponse(create_msg_to_send(create_status_msg(405, 'Only POST method is allowed!'), RASP_RSAPUB_KEY))
def verify_totp_code(secret, code): """ Validate a Google authenticator compatible TOTP code Args: secret: 16 character base32 secret code: 8 digit code that expires in 30 seconds Return: True if validation successful """ if isinstance(secret, unicode): secret = secret.encode('utf-8') if isinstance(code, unicode): code = code.encode('utf-8') try: key = base64.b32decode(secret) totp = TOTP(key, 8, SHA1(), 30, backend=default_backend(), enforce_key_length=False) time_value = int(time.time()) totp.verify(code, time_value) return True except (ValueError, TypeError, InvalidToken): pass return None
""" Implementación de un sistema que valida tokens TOTP. Atención: Revisa cuidadosemente la hora del validador/Cliente. La mayoria de problemas con los tokens TOTP vienen por desfases temporales entre cliente y servidor RFC-6238 Time-based One-time Password (TOTP) """ import time import os from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.twofactor.totp import TOTP, InvalidToken from cryptography.hazmat.primitives.hashes import SHA1 key = b'abcdefghij' totp = TOTP(key, 6, SHA1(), 30, backend=default_backend()) token = input("Token?: ").encode() try: totp.verify(token, time.time()) print("Token Válido") except InvalidToken: print("Token Inválido")
from cryptography.hazmat.primitives.twofactor import InvalidToken import pyqrcode key = os.urandom(16) counter = 1 time_value = time.time() issuer = 'GruPyPR' account_name = input('Your name: ') totp = TOTP(key, 6, SHA1(), 30, backend=default_backend()) uri = totp.get_provisioning_uri(account_name, issuer) url = pyqrcode.create(uri) print('Scan this!\n') url.svg('totp.svg', scale=8) webbrowser.open('totp.svg') while True: try: totp_value = bytes(input('Two factor password: '******'utf-8') totp.verify(totp_value, time.time()) print('You are authenticated!\n') except InvalidToken: print('You shall not pass!') continue except KeyboardInterrupt: sys.exit(0)
def totpVerify(secret, token): totp = TOTP(base64.b32decode(secret), 6, SHA1(), 30, crypto_backend, enforce_key_length=False) totp.verify(token.encode(), time.time())
def verify_totp_code(user, code): totp = TOTP(bytes(user.secret), 6, SHA1(), 30, backend=default_backend()) return totp.verify(force_bytes(code), time.time())