Python secrets.token_bytes() Examples

The following are 30 code examples of secrets.token_bytes(). 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: crypto.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def bytes(count):
    return secrets.token_bytes(count) 
Example #2
Source File: conftest.py    From trinity with MIT License 5 votes vote down vote up
def node_key():
    key_bytes = secrets.token_bytes(32)
    return PrivateKey(key_bytes) 
Example #3
Source File: block_hash.py    From trinity with MIT License 5 votes vote down vote up
def _create(cls,
                model_class: Type[bytes],
                *args: Any,
                **kwargs: Any) -> Hash32:
        return Hash32(model_class(secrets.token_bytes(32))) 
Example #4
Source File: websocket.py    From TwitchIO with MIT License 5 votes vote down vote up
def generate_jitter():
        # Generates a random number between around 1 and 10
        jitter = 0

        while jitter == 11 or jitter == 0:
            bites = secrets.token_bytes(2)
            number = itertools.accumulate(bites)
            jitter = int(sum(number) / 2 ** 6)

        return jitter 
Example #5
Source File: webapp.py    From modernpython with MIT License 5 votes vote down vote up
def check_credentials() -> None:
    user = request.forms.get('user', '')
    password = request.forms.get('password', '')
    if not pubsub.check_user(user, password):
        return show_main_page()
    token = secrets.token_bytes(32)
    logged_in_users[token] = user
    response.set_cookie('token', token, max_age=60, secret=secret)
    return show_main_page(user) 
Example #6
Source File: pubsub.py    From modernpython with MIT License 5 votes vote down vote up
def hash_password(password: str, salt: Optional[bytes] = None) -> HashAndSalt:
    pepper = b'alchemists discovered that gold came from earth air fire and water'
    salt = salt or secrets.token_bytes(16)
    return hashlib.pbkdf2_hmac('sha512', password.encode(), salt+pepper, 100_000), salt 
Example #7
Source File: 5_secret_storage.py    From pykeybasebot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_secret(self, team, namespace) -> bytes:
        if team not in self.secrets or namespace not in self.secrets[team]:
            secret = secrets.token_bytes(self.SECRET_NUM_BYTES)
            try:
                # we don't expect self.SECRET_KEY's revision > 0
                await self.kvstore.put(
                    namespace,
                    self.SECRET_KEY,
                    bytes_to_str(secret),
                    revision=1,
                    team=team,
                )
            except RevisionError:
                res: keybase1.KVGetResult = await self.kvstore.get(
                    namespace, self.SECRET_KEY, team=team
                )
                secret = str_to_bytes(res.entry_value)
            if team not in self.secrets:
                self.secrets[team] = {}
            self.secrets[team][namespace] = secret
        return self.secrets[team][namespace] 
Example #8
Source File: omshell.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_omapi_key():
    """Generate a HMAC-MD5 key.

    :return: The shared key suitable for OMAPI access.
    :type: string
    """
    encoded = base64.encodebytes(secrets.token_bytes(64))
    return encoded.decode("ascii").replace("\n", "") 
Example #9
Source File: key_derive.py    From QuLab with MIT License 5 votes vote down vote up
def encryptPassword(password):
    if isinstance(password, bytes):
        key_material = password
    else:
        key_material = str(password).encode('utf-8')

    salt = secrets.token_bytes(SALT_SIZE)
    kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                     length=KEY_SIZE,
                     salt=salt,
                     iterations=100000,
                     backend=default_backend())
    key = kdf.derive(key_material)
    return salt + key 
Example #10
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_token_defaults(self):
        # Test that token_* functions handle default size correctly.
        for func in (secrets.token_bytes, secrets.token_hex,
                     secrets.token_urlsafe):
            with self.subTest(func=func):
                name = func.__name__
                try:
                    func()
                except TypeError:
                    self.fail("%s cannot be called with no argument" % name)
                try:
                    func(None)
                except TypeError:
                    self.fail("%s cannot be called with None" % name)
        size = secrets.DEFAULT_ENTROPY
        self.assertEqual(len(secrets.token_bytes(None)), size)
        self.assertEqual(len(secrets.token_hex(None)), 2*size) 
Example #11
Source File: test_secrets.py    From android_universal with MIT License 5 votes vote down vote up
def test_token_bytes(self):
        # Test token_bytes.
        for n in (1, 8, 17, 100):
            with self.subTest(n=n):
                self.assertIsInstance(secrets.token_bytes(n), bytes)
                self.assertEqual(len(secrets.token_bytes(n)), n) 
Example #12
Source File: utils.py    From pyfy with MIT License 5 votes vote down vote up
def _create_secret(bytes_length=32):  # pragma: no cover
    return secrets.base64.standard_b64encode(secrets.token_bytes(bytes_length)).decode(
        "utf-8"
    ) 
Example #13
Source File: routing_table_manager.py    From trinity with MIT License 5 votes vote down vote up
def run(self) -> None:
        async for _ in every(ROUTING_TABLE_LOOKUP_INTERVAL):
            target = NodeID(secrets.token_bytes(32))
            await self.lookup(target) 
Example #14
Source File: poc.py    From poc_CVE-2018-1002105 with MIT License 5 votes vote down vote up
def request_stage_2(target, namespace, pod, container, command):

    stage_2 = ""

    command = f"command={'&command='.join(command.split(' '))}"

    with open('stage_2', 'r') as stage_2_fd:
        stage_2 = stage_2_fd.read()

    key = base64.b64encode(token_bytes(20)).decode('utf-8')

    return stage_2.format(namespace, pod, container, command,
                          target, key).encode('utf-8') 
Example #15
Source File: commands.py    From snet-cli with MIT License 5 votes vote down vote up
def add_group(self):
        metadata_file = self.args.metadata_file

        try:
            with open(metadata_file, 'r') as f:
                org_metadata = OrganizationMetadata.from_json(json.load(f))
        except Exception as e:
            print(
                "Organization metadata json file not found ,Please check --metadata-file path ")
            raise e

        payment_storage_client = PaymentStorageClient(self.args.payment_channel_connection_timeout,
                                                      self.args.payment_channel_request_timeout, self.args.endpoints)
        payment = Payment(self.args.payment_address, self.args.payment_expiration_threshold,
                          self.args.payment_channel_storage_type, payment_storage_client)
        group_id = base64.b64encode(secrets.token_bytes(32))

        group = Group(self.args.group_name, group_id.decode("ascii"), payment)
        org_metadata.add_group(group)
        org_metadata.save_pretty(metadata_file) 
Example #16
Source File: create_cert.py    From pytest-tornado with Apache License 2.0 5 votes vote down vote up
def randomBytes(length):
	"""
	Return _length_ random bytes.

	:rtype: bytes
	"""
	if secrets:
		return secrets.token_bytes(512)
	else:
		return os.urandom(512) 
Example #17
Source File: runtime.py    From mpyc with MIT License 5 votes vote down vote up
def threshold(self, t):
        self._threshold = t
        # generate new PRSS keys
        self.prfs.cache_clear()
        keys = {}
        m = len(self.parties)
        for subset in itertools.combinations(range(m), m - t):
            if self.pid == min(subset):
                keys[subset] = secrets.token_bytes(16)  # 128-bit key
        self._prss_keys = keys
        # caching (m choose t):
        self._bincoef = math.factorial(m) // math.factorial(t) // math.factorial(m - t) 
Example #18
Source File: hook.py    From zeus with Apache License 2.0 5 votes vote down vote up
def generate_token(cls) -> bytes:
        return token_bytes(64) 
Example #19
Source File: api.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_token(self, user_id):
		secret = base64.b64encode(secrets.token_bytes())
		return self.encode_token(user_id, secret) 
Example #20
Source File: api.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def new_token(self, user_id):
		secret = secrets.token_bytes()
		await self.bot.pool.execute(self.queries.new_token(), user_id, secret)
		return self.encode_token(user_id, secret) 
Example #21
Source File: crypto.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def rand_bytes(n_bytes=TOKEN_NUM_BYTES) -> bytes:
    if n_bytes <= 0:
        raise ValueError("0 and negative argument not allowed")
    return secrets.token_bytes(n_bytes) 
Example #22
Source File: streamer.py    From nfstream with GNU General Public License v3.0 5 votes vote down vote up
def to_csv(self, sep="|", path=None, ip_anonymization=False):
        if path is None:
            output_path = str(self._source) + '.csv'
        else:
            output_path = path
        if os.path.exists(output_path):
            sys.exit("Output file exists: {}. Please specify a valid file path.".format(output_path))
        else:
            total_flows = 0
            crypto_key = secrets.token_bytes(16)
            with open(output_path, 'ab') as f:
                for flow in self:
                    try:
                        if total_flows == 0:  # header creation
                            header = sep.join([str(i) for i in flow.keys()]) + "\n"
                            src_ip_index = flow.keys().index("src_ip")
                            dst_ip_index = flow.keys().index("dst_ip")
                            f.write(header.encode('utf-8'))
                        values = flow.values()
                        if ip_anonymization:
                            values[src_ip_index] = int.from_bytes(siphash_64(crypto_key, values[src_ip_index].encode()),
                                                                  sys.byteorder)
                            values[dst_ip_index] = int.from_bytes(siphash_64(crypto_key, values[dst_ip_index].encode()),
                                                                  sys.byteorder)
                        to_export = sep.join([str(i) for i in values]) + "\n"
                        f.write(to_export.encode('utf-8'))
                        total_flows = total_flows + 1
                    except KeyboardInterup:
                        if not self._stopped:
                            self._stopped = True
                            self.cache.stopped = True
                return total_flows 
Example #23
Source File: unbreakable_encryption.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 5 votes vote down vote up
def random_key(length: int) -> int:
    # generate length random bytes
    tb: bytes = token_bytes(length)
    # convert those bytes into a bit string and return it
    return int.from_bytes(tb, "big") 
Example #24
Source File: handshake.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_challenge_req(self) -> bytes:
        if not self.state == "stalled":
            raise HandshakeError("Invalid state.")

        self.challenge = token_bytes(self.challenge_size)
        self.state = "challenge"

        return handshake_challenge_serializer.dumps(
            {
                "handshake": "challenge",
                "challenge": self.challenge,
                "supported_api_versions": self.SUPPORTED_API_VERSIONS,
            }
        ) 
Example #25
Source File: test_wallet.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def test_wallet_coinbase_reorg(self, wallet_node):
        num_blocks = 10
        full_nodes, wallets = wallet_node
        full_node_1, server_1 = full_nodes[0]
        wallet_node, server_2 = wallets[0]
        wallet = wallet_node.wallet_state_manager.main_wallet
        ph = await wallet.get_new_puzzlehash()

        await server_2.start_client(PeerInfo("localhost", uint16(server_1._port)), None)
        for i in range(1, num_blocks):
            await full_node_1.farm_new_block(FarmNewBlockProtocol(ph))

        await asyncio.sleep(3)
        funds = sum(
            [
                calculate_base_fee(uint32(i)) + calculate_block_reward(uint32(i))
                for i in range(1, num_blocks - 2)
            ]
        )
        assert await wallet.get_confirmed_balance() == funds

        await full_node_1.reorg_from_index_to_new_index(
            ReorgProtocol(uint32(5), uint32(num_blocks + 3), token_bytes())
        )
        await asyncio.sleep(3)

        funds = sum(
            [
                calculate_base_fee(uint32(i)) + calculate_block_reward(uint32(i))
                for i in range(1, 5)
            ]
        )

        assert await wallet.get_confirmed_balance() == funds 
Example #26
Source File: test_full_node.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def test_respond_transaction_fail(self, two_nodes, wallet_blocks):
        full_node_1, full_node_2, server_1, server_2 = two_nodes
        wallet_a, wallet_receiver, blocks = wallet_blocks

        tx_id = token_bytes(32)
        request_transaction = fnp.RequestTransaction(tx_id)
        msgs = [x async for x in full_node_1.request_transaction(request_transaction)]
        assert len(msgs) == 1
        assert msgs[0].message.data == fnp.RejectTransactionRequest(tx_id)

        receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()

        # Invalid transaction does not propagate
        spend_bundle = wallet_a.generate_signed_transaction(
            100000000000000, receiver_puzzlehash, blocks[3].header.data.coinbase,
        )
        assert spend_bundle is not None
        respond_transaction = fnp.RespondTransaction(spend_bundle)
        assert (
            len([x async for x in full_node_1.respond_transaction(respond_transaction)])
            == 0
        ) 
Example #27
Source File: test_full_node.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def test_request_respond_transaction(self, two_nodes, wallet_blocks):
        full_node_1, full_node_2, server_1, server_2 = two_nodes
        wallet_a, wallet_receiver, blocks = wallet_blocks

        tx_id = token_bytes(32)
        request_transaction = fnp.RequestTransaction(tx_id)
        msgs = [x async for x in full_node_1.request_transaction(request_transaction)]
        assert len(msgs) == 1
        assert msgs[0].message.data == fnp.RejectTransactionRequest(tx_id)

        receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
        spend_bundle = wallet_a.generate_signed_transaction(
            100, receiver_puzzlehash, blocks[2].header.data.coinbase,
        )
        assert spend_bundle is not None
        respond_transaction = fnp.RespondTransaction(spend_bundle)
        prop = [x async for x in full_node_1.respond_transaction(respond_transaction)]
        assert len(prop) == 1
        assert isinstance(prop[0].message.data, fnp.NewTransaction)

        request_transaction = fnp.RequestTransaction(spend_bundle.get_hash())
        msgs = [x async for x in full_node_1.request_transaction(request_transaction)]
        assert len(msgs) == 1
        assert msgs[0].message.data == fnp.RespondTransaction(spend_bundle) 
Example #28
Source File: full_node_simulator.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def reorg_from_index_to_new_index(self, request: ReorgProtocol):
        new_index = request.new_index
        old_index = request.old_index
        coinbase_ph = request.puzzle_hash
        top_tip = self.get_tip()

        current_blocks = await self.get_current_blocks(top_tip)
        block_count = new_index - old_index

        more_blocks = bt.get_consecutive_blocks(
            self.constants,
            block_count,
            current_blocks[:old_index],
            10,
            seed=token_bytes(),
            reward_puzzlehash=coinbase_ph,
            transaction_data_at_height={},
        )
        assert self.server is not None
        for block in more_blocks:
            async for msg in self.respond_block(full_node_protocol.RespondBlock(block)):
                self.server.push_message(msg)
                self.log.info(f"New message: {msg}") 
Example #29
Source File: full_node_simulator.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def farm_new_block(self, request: FarmNewBlockProtocol):
        self.log.info("Farming new block!")
        top_tip = self.get_tip()
        if top_tip is None or self.server is None:
            return

        current_block = await self.get_current_blocks(top_tip)
        bundle: Optional[
            SpendBundle
        ] = await self.mempool_manager.create_bundle_for_tip(top_tip)

        dict_h = {}
        fees = 0
        if bundle is not None:
            program = best_solution_program(bundle)
            dict_h[top_tip.height + 1] = (program, bundle.aggregated_signature)
            fees = bundle.fees()

        more_blocks = bt.get_consecutive_blocks(
            self.constants,
            1,
            current_block,
            10,
            reward_puzzlehash=request.puzzle_hash,
            transaction_data_at_height=dict_h,
            seed=token_bytes(),
            fees=uint64(fees),
        )
        new_lca = more_blocks[-1]

        assert self.server is not None
        async for msg in self.respond_block(full_node_protocol.RespondBlock(new_lca)):
            self.server.push_message(msg) 
Example #30
Source File: ws_message.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def create_payload(
    command: str, data: Dict[str, Any], origin: str, destination: str, string=True
):
    response = {
        "command": command,
        "ack": False,
        "data": data,
        "request_id": token_bytes().hex(),
        "destination": destination,
        "origin": origin,
    }

    if string:
        json_str = dict_to_json_str(response)
        return json_str
    else:
        return response