Python secrets.compare_digest() Examples

The following are 15 code examples of secrets.compare_digest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module secrets , or try the search function .
Example #1
Source File: flask_ext.py    From quart with MIT License 6 votes vote down vote up
def login():
    if request.method == 'GET':
        return '''
               <form method='POST'>
                <input type='text' name='username' id='username' placeholder='username'></input>
                <input type='password' name='password' id='password' placeholder='password'></input>
                <input type='submit' name='submit'></input>
               </form>
               '''

    username = (await request.form)['username']
    password = (await request.form)['password']
    if username in users and compare_digest(password, users[username]['password']):
        user = User()
        user.id = username
        flask_login.login_user(user)
        return redirect(url_for('protected'))

    return 'Bad login' 
Example #2
Source File: api.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
def validate_token(self, token, user_id=None):
		try:
			token_user_id, secret = self.decode_token(token)
		except:  # XXX
			secrets.compare_digest(token, token)
			return False

		if user_id is None:
			# allow auth with just a secret
			user_id = token_user_id

		db_secret = await self.bot.pool.fetchval(self.queries.existing_token(), user_id)
		if db_secret is None:
			secrets.compare_digest(token, token)
			return False

		db_token = self.encode_token(user_id, db_secret)
		return secrets.compare_digest(token, db_token) and user_id 
Example #3
Source File: mnemonic.py    From eth-account with MIT License 5 votes vote down vote up
def is_mnemonic_valid(self, mnemonic):
        words = normalize_string(mnemonic).split(" ")
        num_words = len(words)

        if num_words not in VALID_WORD_COUNTS:
            return False

        try:
            indices = tuple(self.wordlist.index(w) for w in words)
        except ValueError:
            return False

        encoded_seed = bitarray()
        for idx in indices:
            # Build bitarray from tightly packing indices (which are 11-bits integers)
            encoded_seed.extend(int2ba(idx, length=11))

        entropy_size = 4 * num_words // 3

        # Checksum the raw entropy bits
        checksum = bitarray()
        checksum.frombytes(sha256(encoded_seed[:entropy_size * 8].tobytes()))
        computed_checksum = checksum[:len(encoded_seed) - entropy_size * 8].tobytes()

        # Extract the stored checksum bits
        stored_checksum = encoded_seed[entropy_size * 8:].tobytes()

        # Check that the stored matches the relevant slice of the actual checksum
        # NOTE: Use secrets.compare_digest for protection again timing attacks
        return secrets.compare_digest(stored_checksum, computed_checksum) 
Example #4
Source File: flask_ext.py    From quart with MIT License 5 votes vote down vote up
def request_loader(request):
    username = request.form.get('username')
    password = request.form.get('password', '')
    if username not in users:
        return

    user = User()
    user.id = username
    user.is_authenticated = compare_digest(password, users[username]['password'])
    return user 
Example #5
Source File: special.py    From datasette with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        token = request.args.get("token") or ""
        if not self.ds._root_token:
            raise Forbidden("Root token has already been used")
        if secrets.compare_digest(token, self.ds._root_token):
            self.ds._root_token = None
            response = Response.redirect("/")
            response.set_cookie(
                "ds_actor", self.ds.sign({"a": {"id": "root"}}, "actor")
            )
            return response
        else:
            raise Forbidden("Invalid token") 
Example #6
Source File: tutorial007.py    From fastapi with MIT License 5 votes vote down vote up
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = secrets.compare_digest(credentials.username, "stanleyjobson")
    correct_password = secrets.compare_digest(credentials.password, "swordfish")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username 
Example #7
Source File: receiver.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _verify_token(self, request):
        if not self.token:
            return True
        actor_token = request.headers.get('actor-token')
        if not actor_token:
            return False
        return secrets.compare_digest(actor_token, self.token) 
Example #8
Source File: hook.py    From zeus with Apache License 2.0 5 votes vote down vote up
def is_valid_signature(self, signature: str) -> bool:
        return compare_digest(self.get_signature(), signature) 
Example #9
Source File: middleware.py    From aerial_wildlife_detection with MIT License 5 votes vote down vote up
def _compare_tokens(self, tokenA, tokenB):
        if tokenA is None or tokenB is None:
            return False
        return secrets.compare_digest(tokenA, tokenB) 
Example #10
Source File: handshake.py    From trinity with MIT License 5 votes vote down vote up
def is_response_packet(self, packet: Packet) -> bool:
        return (
            isinstance(packet, WhoAreYouPacket) and
            secrets.compare_digest(packet.token, self.initiating_packet.auth_tag)
        ) 
Example #11
Source File: pubsub.py    From modernpython with MIT License 5 votes vote down vote up
def check_user(user: User, password: str) -> bool:
    hashpass, salt = user_info[user].hashed_password
    target_hash_pass = hash_password(password, salt)[0]
    sleep(random.expovariate(10))
    return secrets.compare_digest(hashpass, target_hash_pass) 
Example #12
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_equal(self):
        # Test compare_digest functionality with equal (byte/text) strings.
        for s in ("a", "bcd", "xyz123"):
            a = s*100
            b = s*100
            self.assertTrue(secrets.compare_digest(a, b))
            self.assertTrue(secrets.compare_digest(a.encode('utf-8'), b.encode('utf-8'))) 
Example #13
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_unequal(self):
        # Test compare_digest functionality with unequal (byte/text) strings.
        self.assertFalse(secrets.compare_digest("abc", "abcd"))
        self.assertFalse(secrets.compare_digest(b"abc", b"abcd"))
        for s in ("x", "mn", "a1b2c3"):
            a = s*100 + "q"
            b = s*100 + "k"
            self.assertFalse(secrets.compare_digest(a, b))
            self.assertFalse(secrets.compare_digest(a.encode('utf-8'), b.encode('utf-8'))) 
Example #14
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_bad_types(self):
        # Test that compare_digest raises with mixed types.
        a = 'abcde'
        b = a.encode('utf-8')
        assert isinstance(a, str)
        assert isinstance(b, bytes)
        self.assertRaises(TypeError, secrets.compare_digest, a, b)
        self.assertRaises(TypeError, secrets.compare_digest, b, a) 
Example #15
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_bool(self):
        # Test that compare_digest returns a bool.
        self.assertIsInstance(secrets.compare_digest("abc", "abc"), bool)
        self.assertIsInstance(secrets.compare_digest("abc", "xyz"), bool)