当前位置: 首页>>代码示例>>Python>>正文


Python hotp.HOTP类代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.twofactor.hotp.HOTP的典型用法代码示例。如果您正苦于以下问题:Python HOTP类的具体用法?Python HOTP怎么用?Python HOTP使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HOTP类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_hotp_value

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
开发者ID:DroidX86,项目名称:CloudSec,代码行数:28,代码来源:ags.py

示例2: test_invalid_verify

    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)
开发者ID:B-Rich,项目名称:cryptography,代码行数:8,代码来源:test_hotp.py

示例3: test_verify

    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
开发者ID:B-Rich,项目名称:cryptography,代码行数:8,代码来源:test_hotp.py

示例4: test_generate

    def test_generate(self, backend, params):
        secret = params["secret"]
        counter = int(params["counter"])
        hotp_value = params["hotp"]

        hotp = HOTP(secret, 6, SHA1(), backend)

        assert hotp.generate(counter) == hotp_value
开发者ID:B-Rich,项目名称:cryptography,代码行数:8,代码来源:test_hotp.py

示例5: test_truncate

    def test_truncate(self, backend, params):
        secret = params["secret"]
        counter = int(params["counter"])
        truncated = params["truncated"]

        hotp = HOTP(secret, 6, SHA1(), backend)

        assert hotp._dynamic_truncate(counter) == int(truncated.decode(), 16)
开发者ID:B-Rich,项目名称:cryptography,代码行数:8,代码来源:test_hotp.py

示例6: test_get_provisioning_uri

    def test_get_provisioning_uri(self, backend):
        secret = b"12345678901234567890"
        hotp = HOTP(secret, 6, SHA1(), backend)

        assert hotp.get_provisioning_uri("Alice Smith", 1, None) == (
            "otpauth://hotp/Alice%20Smith?digits=6&secret=GEZDGNBV"
            "GY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&counter=1")

        assert hotp.get_provisioning_uri("Alice Smith", 1, 'Foo') == (
            "otpauth://hotp/Foo:Alice%20Smith?digits=6&secret=GEZD"
            "GNBVGY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&issuer=Foo"
            "&counter=1")
开发者ID:Ayrx,项目名称:cryptography,代码行数:12,代码来源:test_hotp.py

示例7: send_aic

def send_aic(sessionid, role, bindkey, pubkey):
	"""
	Send an AIC to the ags, returns success value

	sessionid -- Anonymized Session ID for user
	role -- Role as retrieved from database
	bindkey -- As generated during login
	pubkey -- Users stored public key
	context -- Users login context
	"""
	# AIC construct
	aic = {"sessionid":sessionid, "role":role, "bindkey":bindkey, "pubkey":pubkey}
	message = json.dumps(aic)
	logger.info("Genrated AIC: %s", message)
	# Secure the payload
	payload = transport_security.construct_message(message, srcprivkey=app_privatekey, destpubkey=ags_publickey)
	# Calculate the current HOTP token from file
	with open(ags_secretfile, 'r') as f:
		agsdict = json.loads(f.read())
		counter = agsdict['Counter']
		tfapass = agsdict['2FAKey']
	hotp = HOTP(bytes(tfapass, 'utf-8'), 6, hashes.SHA1(), backend=default_backend())
	tfaval = hotp.generate(counter).decode('utf-8')
	# Do the reques to the AGS
	#XXX: Change to https for deployment
	url = "http://{}:{}/ags/authorized?token={}".format(ags_address, ags_port, tfaval)
	logger.info("Adding AIC to AGS: %s", url)
	try:
		resp = requests.put(url, json=payload)
	except requests.Timeout:
		logger.warning("AGS connection timeout")
		return None
	except requests.ConnectionError:
		logger.warning("AGS connection error")
		return None
	logger.info("AGS AIC PUT status code: %s", resp.status_code)
	# A 200 OK response means the request was successful
	if resp.status_code == 200:
		# Update the HOTP counter value
		counter += 1
		agsdict['Counter'] = counter
		with open(ags_secretfile, 'w') as f:
			f.write(json.dumps(agsdict))
		logger.info("AGS HOTP counter was incremented to %s", counter)
		# Return the validity as returned by the AGS
		return resp.json()['validity']
	else:
		logger.warning("AGS rejected AIC")
		return None
开发者ID:DroidX86,项目名称:CloudSec,代码行数:49,代码来源:auth.py

示例8: retrieve_keys

def retrieve_keys(db, attribute):
	"""
	Retrieve keys from the KS; This involves querying the KS with an authentication token
	Then decrypting and returning the encrypted payload

	db -- Databse whose keys to retrieve
	attribute -- The attribute whose encryption key to retrieve
	"""
	# Load the HOTP secret and counter from the secret file of the Key Server
	with open(ks_secretfile, 'r') as f:
		ksdict = json.loads(f.read())
		counter = ksdict['Counter']
		tfapass = ksdict['2FAKey']
	# Calculate the HOTP token value
	hotp = HOTP(bytes(tfapass, 'utf-8'), 6, hashes.SHA1(), backend=default_backend())
	tfaval = hotp.generate(counter).decode('utf-8')
	# Do the request to the key server
	#XXX: Chnage to https for deployment
	url = "http://{}:{}/key/{}/{}?token={}".format(ks_address, ks_port, db, attribute, tfaval)
	logger.info("Trying to access key from KS: %s", url)
	# Do the request
	try:
		resp = requests.get(url)
	except requests.exceptions.Timeout:
		logger.warning("KS request timeout")
		return None
	except requests.exceptions.ConnectionError:
		logger.warning("KS connection refused")
		return None
	logger.info("KS response code: %s", resp.status_code)
	if resp.status_code == 200:	# Got 200 means KS incremented the counter
		counter += 1	# Increment our own counter
		# Save the updated secret
		ksdict['Counter'] = counter
		with open(ks_secretfile, 'w') as f:
			f.write(json.dumps(ksdict))
		logger.info("KS HOTP counter was incremented to %s", counter)
		# Get the transport secure message
		secured_message = resp.json()
		key = transport_security.deconstruct_message(secured_message, destprivkey=app_privatekey, srcpubkey=ks_publickey)
		# Check if decryption was successful
		if not key:
			logger.warning("Secured message from KS was not decrypted properly")
			return None
		return key
	else:
		# KS did not return the key
		logger.warning("KS replied negatively. Something is wrong.")
		return None
开发者ID:DroidX86,项目名称:CloudSec,代码行数:49,代码来源:ags.py

示例9: __init__

    def __init__(self, key, length, algorithm, time_step, backend, enforce_key_length=True):
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.", _Reasons.BACKEND_MISSING_INTERFACE
            )

        self._time_step = time_step
        self._hotp = HOTP(key, length, algorithm, backend, enforce_key_length)
开发者ID:CHENSHUFANG,项目名称:cryptography,代码行数:8,代码来源:totp.py

示例10: TOTP

class TOTP(object):
    def __init__(self, key, length, algorithm, time_step, backend):
        if not isinstance(backend, HMACBackend):
            raise UnsupportedInterface("Backend object does not implement HMACBackend")

        self._time_step = time_step
        self._hotp = HOTP(key, length, algorithm, backend)

    def generate(self, time):
        counter = int(time / self._time_step)
        return self._hotp.generate(counter)

    def verify(self, totp, time):
        if not constant_time.bytes_eq(self.generate(time), totp):
            raise InvalidToken("Supplied TOTP value does not match")
开发者ID:jgiannuzzi,项目名称:cryptography,代码行数:15,代码来源:totp.py

示例11: TOTP

class TOTP(object):
    def __init__(self, key, length, algorithm, time_step, backend, enforce_key_length=True):
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.", _Reasons.BACKEND_MISSING_INTERFACE
            )

        self._time_step = time_step
        self._hotp = HOTP(key, length, algorithm, backend, enforce_key_length)

    def generate(self, time):
        counter = int(time / self._time_step)
        return self._hotp.generate(counter)

    def verify(self, totp, time):
        if not constant_time.bytes_eq(self.generate(time), totp):
            raise InvalidToken("Supplied TOTP value does not match.")

    def get_provisioning_uri(self, account_name, issuer):
        return _generate_uri(self._hotp, "totp", account_name, issuer, [("period", int(self._time_step))])
开发者ID:CHENSHUFANG,项目名称:cryptography,代码行数:20,代码来源:totp.py

示例12: input

import webbrowser

from cryptography.hazmat.backends import default_backend
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: '), encoding='utf-8')
        hotp.verify(hotp_value, counter)
        print('You are authenticated!\n')
    except InvalidToken:
        print('You shall not pass!\n')
        continue
开发者ID:GaragemHacker,项目名称:two-factor,代码行数:31,代码来源:hotp.py

示例13: Password

""" 
    Implementación de un validador de Tokens HOTP 

    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")
开发者ID:luisgf,项目名称:pyvigo-cryptography,代码行数:30,代码来源:hotp.py

示例14: test_buffer_protocol

 def test_buffer_protocol(self, backend):
     key = bytearray(b"a long key with lots of entropy goes here")
     hotp = HOTP(key, 6, SHA1(), backend)
     assert hotp.generate(10) == b"559978"
开发者ID:pyca,项目名称:cryptography,代码行数:4,代码来源:test_hotp.py

示例15: __init__

    def __init__(self, key, length, algorithm, time_step, backend):
        if not isinstance(backend, HMACBackend):
            raise UnsupportedInterface("Backend object does not implement HMACBackend")

        self._time_step = time_step
        self._hotp = HOTP(key, length, algorithm, backend)
开发者ID:jgiannuzzi,项目名称:cryptography,代码行数:6,代码来源:totp.py


注:本文中的cryptography.hazmat.primitives.twofactor.hotp.HOTP类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。