def test_verify(self, backend, params): secret = params["secret"] counter = int(params["counter"]) hotp_value = params["hotp"] hotp = HOTP(secret, 6, SHA1(), backend) hotp.verify(hotp_value, counter)
def check_hotp_value(hotp_token): """ Verify the HOTP token from the AS """ logger.info("Loading 2FA secret from %s", auth_secretfile) # Load the shared secret and counter from file with open(auth_secretfile, 'r') as f: content = json.loads(f.read()) secret = content['2FAKey'] counter = content['Counter'] logger.info("Loaded 2FA secret") hotp = HOTP(bytes(secret, 'utf-8'), 6, hashes.SHA1(), backend=default_backend()) logger.info("Trying to verify HOTP token") try: # Try to verify the token hotp.verify(hotp=bytes(hotp_token, 'utf-8'), counter=counter) # Verification failure would have raised an InvalidToken exception here logger.info("HOTP token successfully authenticated") # Save the updated secret to file counter += 1 # Increment the counter content['Counter'] = counter logger.info("HOTP counter updated to: %s", counter) with open(auth_secretfile, 'w') as f: # Write to file f.write(json.dumps(content)) return True except InvalidToken: logger.warning("HOTP token was not authenticated") return False
def verify_hotp_code(secret, code, counter): """ Validate a Google authenticator compatible HOTP code Args: secret: 16 character base32 secret code: 6 digit code that expires in 30 seconds counter: matching integer value Return: Counter value if validation successful or None """ if isinstance(secret, unicode): secret = secret.encode('utf-8') if isinstance(code, unicode): code = code.encode('utf-8') try: key = base64.b32decode(secret) hotp = HOTP(key, 6, SHA1(), backend=default_backend(), enforce_key_length=False) for count in range(counter, counter + 3): try: hotp.verify(code, count) return count except InvalidToken: pass except (ValueError, TypeError): pass return None
def test_invalid_verify(self, backend): secret = b"12345678901234567890" counter = 0 hotp = HOTP(secret, 6, SHA1(), backend) with pytest.raises(InvalidToken): hotp.verify(b"123456", counter)
def test_verify(self, backend, params): secret = params["secret"] counter = int(params["counter"]) hotp_value = params["hotp"] hotp = HOTP(secret, 6, SHA1(), backend) assert hotp.verify(hotp_value, counter) is None
from cryptography.hazmat.primitives.twofactor.hotp import HOTP from cryptography.hazmat.primitives.hashes import SHA1 from cryptography.hazmat.primitives.twofactor import InvalidToken import pyqrcode key = os.urandom(16) counter = 1 issuer = 'GruPyPR' account_name = input('Your name: ') hotp = HOTP(key, 6, SHA1(), backend=default_backend()) uri = hotp.get_provisioning_uri(account_name, counter, issuer) url = pyqrcode.create(uri) print('Scan this!\n') url.svg('hotp.svg', scale=8) webbrowser.open('hotp.svg') while True: try: hotp_value = bytes(input('Two factor password: '******'utf-8') hotp.verify(hotp_value, counter) print('You are authenticated!\n') except InvalidToken: print('You shall not pass!\n') continue except KeyboardInterrupt: sys.exit(0)
RFC-4226 HMAC-Based One-time Password (HOTP) """ import os import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.twofactor.hotp import HOTP, InvalidToken from cryptography.hazmat.primitives.hashes import SHA1 key = b'abcdefghij' hotp = HOTP(key, 6, SHA1(), backend=default_backend()) token = input("Introduce Token: ").encode('utf-8') valido = False for counter in range(0, 100): try: hotp.verify(token, counter) valido = True except InvalidToken: pass if valido: print("Token Válido") else: print("Token Inválido")
def primitive(): # Initialize the errors variable to empty string. We will have the error messages # in that variable, if any. errors = '' if request.method == "GET": # If the request is GET, render the form template. return render_template("index.html", errors=errors) if 'aesForm' in request.form: # The request is POST with some data, get POST data and validate it. # The form data is available in request.form dictionary. Stripping it to remove # leading and trailing whitespaces aesPlainText = request.form['aesPlainText'].strip() # Check if all the fields are non-empty and raise an error otherwise if not aesPlainText: errors = "Please enter all the fields." if not errors: # If there are no errors, create a dictionary containing all the entered # data and pass it to the template to be displayed a1 = "Symmetric Encryption\n" a2 = "This application will use DES Symmetric Encryption to encrypt and decrypt text\n" plainText = "Text to encrypt: " getInput = aesPlainText backend = default_backend() cfb_Key = os.urandom(16) aes_Key = os.urandom(32) #secretMessage = str.encode(input(plainText)) secretMessage = str.encode(getInput) cipher = Cipher(algorithms.AES(aes_Key), modes.CFB(cfb_Key), backend=backend) encryptor = cipher.encryptor() encryptedText = encryptor.update( secretMessage) + encryptor.finalize() decryptor = cipher.decryptor() decryptedText = decryptor.update( encryptedText) + decryptor.finalize() dataAes = { 'aes_Key': aes_Key, 'cfb_Key': cfb_Key, 'encryptedText': encryptedText, 'decryptedText': decryptedText } # Since the form data is valid, render the success template return render_template("prim/aes.html", dataAes=dataAes) # Render the form template with the error messages return render_template("index.html", errors=errors) if 'desForm' in request.form: # The request is POST with some data, get POST data and validate it. # The form data is available in request.form dictionary. Stripping it to remove desPlainText = request.form['desPlainText'].strip() #desBitKey = request.form['desBitKey'].strip() #desMode = request.form['desMode'].strip() # Check if all the fields are non-empty and raise an error otherwise if not desPlainText: errors = "Please enter all the fields." if not errors: # If there are no errors, create a dictionary containing all the entered # data and pass it to the template to be displayed plaintext = desPlainText mode = "CBC" key = "12345678" #key and plain text desKey = des(key, mode, "\0\0\0\0\0\0\0\0") #print ("Key : %r" % k.getKey()) #print ("Plaintext : %r" % plaintext) #desKey = k # Encrypted message desEnc = desKey.encrypt(plaintext, [], PAD_PKCS5) #print ("Encrypted: %r" % d) desEncMessage = desEnc # Decrypted message desDec = desKey.decrypt(desEncMessage, [], PAD_PKCS5) #print ("Decrypted Plaintext: %r" % d) desDecMessage = desDec dataDes = { 'desPlainText': desPlainText, 'desKey': desKey, 'desEncMessage': desEncMessage, 'desDecMessage': desDecMessage } # Since the form data is valid, render the success template return render_template("prim/des.html", dataDes=dataDes) # Render the form template with the error messages return render_template("index.html", errors=errors) if 'hmacForm' in request.form: # The request is POST with some data, get POST data and validate it. # The form data is available in request.form dictionary. Stripping it to remove hmacPlainText = request.form['hmacPlainText'].strip() # Check if all the fields are non-empty and raise an error otherwise if not hmacPlainText: errors = "Please enter all the fields." if not errors: # If there are no errors, create a dictionary containing all the entered # data and pass it to the template to be displayed shared_key = os.urandom(16) # Create a HMAC object digest = hmac.HMAC(shared_key, hashes.SHA256(), backend=default_backend()) # enter the message has input to be hased in bytes plaintext = str.encode(hmacPlainText) digest.update(plaintext) # Finalized and produce the HMAC that will be attached to the message hash_code = digest.finalize() print("message", hmacPlainText) print("hash_code", hash_code) print("random Key:", shared_key) dataHmac = { 'hmacPlainText': hmacPlainText, 'hash_code': hash_code, 'shared_key': shared_key } # Since the form data is valid, render the success template return render_template("prim/hmac.html", dataHmac=dataHmac) # Render the form template with the error messages return render_template("index.html", errors=errors) if 'diffForm' in request.form: # The request is POST with some data, get POST data and validate it. # The form data is available in request.form dictionary. Stripping it to remove diifPlainText = request.form['diifPlainText'].strip() diffPub1 = request.form['diffPub1'].strip() diffPub2 = request.form['diffPub2'].strip() # Check if all the fields are non-empty and raise an error otherwise if not diifPlainText or not diffPub1 or not diffPub2: errors = "Please enter all the fields." if not errors: # If there are no errors, create a dictionary containing all the entered # data and pass it to the template to be displayed Xa = int(diffPub1) Xb = int(diffPub2) diifPlainText = int(diifPlainText) check_num = 0 prK = 2 a = prK #Compute Public Key for first user Ya = (a**Xa) % diifPlainText #Compute Public Key for second user Yb = (a**Xb) % diifPlainText #Compute shared key Ka = (Yb**Xa) % diifPlainText Kb = (Ya**Xb) % diifPlainText #Shared key should be same value for both users print("primitive_root: prK and prQ") print("1 shared key is", Ka) print("2 shared key is", Kb, "\n") print("1 and 2 secret shared key is", Ka, "\n") print("primitive_root", prK) print("a_pupKey", Ya) print("a_sharedKey", Ka) print("b_pupKey", Yb) print("b_sharedKey:", Kb) dataDiff = { 'prime': diifPlainText, 'primitive_root': prK, 'a_pupKey': Ya, 'a_sharedKey': Ka, 'b_pupKey': Yb, 'b_sharedKey': Kb } # Since the form data is valid, render the success template return render_template("prim/diff.html", dataDiff=dataDiff) # Render the form template with the error messages return render_template("index.html", errors=errors) if '2faForm' in request.form: # The request is POST with some data, get POST data and validate it. # The form data is available in request.form dictionary. Stripping it to remove #diifPlainText = request.form['diifPlainText'].strip() # Check if all the fields are non-empty and raise an error otherwise #if not diifPlainText or not diffPub1 or not diffPub2: #errors = "Please enter all the fields." if not errors: # If there are no errors, create a dictionary containing all the entered # data and pass it to the template to be displayed #Key is a secret key which is being randomly generated bytes key2Fa = os.urandom(20) #HOTP is an HMAC one-time password algorithm. #Length parameter is controls the length of the generated password which must be >=6 and <=8; Is using SHA1() hash function to encrypt hotp = HOTP(key2Fa, 6, SHA1(), backend=default_backend()) #Hotp.generate, generates the random 6 digit token hotp_value = hotp.generate(0) hotp.verify(hotp_value, 0) print("hashed_value: ", hotp_value) print("generated key: ", key2Fa) data2Fa = {'hotp_value': hotp_value, 'key2Fa': key2Fa} # Since the form data is valid, render the success template return render_template("prim/2fa.html", data2Fa=data2Fa) # Render the form template with the error messages return render_template("index.html", errors=errors)