本文整理汇总了Python中secrets.token_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python secrets.token_bytes方法的具体用法?Python secrets.token_bytes怎么用?Python secrets.token_bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类secrets
的用法示例。
在下文中一共展示了secrets.token_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_secret_with_hash
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def generate_secret_with_hash() -> (bytes, bytes):
'''
Generating secret and related ripemd160 hash.
Returns:
tuple: secret, secret hash
Example:
>>> from clove.utils.hashing import generate_secret_with_hash
>>> secret, secret_hash = generate_secret_with_hash()
>>> secret.hex()
'95a968aa18866ffe6ed9ad39a06e27a90e55699734007173bfdd3daa4bab661d'
'''
secret = secrets.token_bytes(32)
secret_hash = hashlib.new('ripemd160', secret).digest()
return secret, secret_hash
示例2: send_browse_request
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def send_browse_request(self, search_criteria, key, challenge):
stream = StreamOut(self.settings)
stream.add(search_criteria)
buffer = stream.get()
stream = StreamOut(self.settings)
stream.u8(0) #Packet type
stream.u32(len(buffer))
stream.write(buffer)
if self.settings.get("pia.lan_version") != 0:
self.nonce_counter += 1
stream.u8(self.settings.get("pia.lan_version"))
stream.bool(self.settings.get("pia.crypto_enabled"))
stream.u64(self.nonce_counter)
stream.write(key)
if self.settings.get("pia.crypto_enabled"):
challenge = self.generate_challenge(key, challenge)
else:
challenge = secrets.token_bytes(16 + 256)
stream.write(challenge)
self.s.send(stream.get(), self.broadcast)
示例3: encrypt
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def encrypt(self, key, settings):
ticket_key = secrets.token_bytes(16)
stream = streams.StreamOut(settings)
stream.datetime(self.expiration)
stream.pid(self.source_pid)
if len(self.session_key) != settings.get("kerberos.key_size"):
raise ValueError("Incorrect session_key length")
stream.write(self.session_key)
ticket_body = stream.get()
final_key = hashlib.md5(key + ticket_key).digest()
kerberos = KerberosEncryption(final_key)
encrypted = kerberos.encrypt(ticket_body)
stream = streams.StreamOut(settings)
stream.buffer(ticket_key)
stream.buffer(encrypted)
return stream.get()
示例4: send_packet
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def send_packet(self, opcode, payload=b""):
data = bytes([0x80 | opcode])
mask = 0 if self.server_mode else 0x80
length = len(payload)
if length < 126:
data += bytes([mask | length])
elif length <= 0xFFFF:
data += struct.pack(">BH", mask | 0x7E, length)
else:
data += struct.pack(">BQ", mask | 0x7F, length)
if self.server_mode:
data += payload
else:
mask = secrets.token_bytes(4)
data += mask + self.apply_mask(payload, mask)
self.sock.send(data)
示例5: generate_ticket
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def generate_ticket(self, source, target):
settings = self.settings
user_key = derive_key(source)
server_key = derive_key(target)
session_key = secrets.token_bytes(settings.get("kerberos.key_size"))
internal = kerberos.ServerTicket()
internal.expiration = common.DateTime.fromtimestamp(time.time() + 120)
internal.source_pid = source.pid
internal.session_key = session_key
ticket = kerberos.ClientTicket()
ticket.session_key = session_key
ticket.target_pid = target.pid
ticket.internal = internal.encrypt(server_key, settings)
return ticket.encrypt(user_key, settings)
示例6: encrypt_outer
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def encrypt_outer(msg, pubkey):
kf = secrets.token_bytes(HASH_SIZE)
com = commit(kf, msg)
send_key = serialization.load_der_public_key(
pubkey,
backend=default_backend(),
)
ctxt = send_key.encrypt(
msg + kf,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
)
)
return (ctxt, com)
示例7: _initialize_ping_task
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def _initialize_ping_task(self):
async def ping():
while not self._pipeline_task.done():
msg = Message("ping", Ping(bytes32(token_bytes(32))))
self.push_message(
OutboundMessage(NodeType.FARMER, msg, Delivery.BROADCAST)
)
self.push_message(
OutboundMessage(NodeType.TIMELORD, msg, Delivery.BROADCAST)
)
self.push_message(
OutboundMessage(NodeType.FULL_NODE, msg, Delivery.BROADCAST)
)
self.push_message(
OutboundMessage(NodeType.HARVESTER, msg, Delivery.BROADCAST)
)
self.push_message(
OutboundMessage(NodeType.WALLET, msg, Delivery.BROADCAST)
)
await asyncio.sleep(self._ping_interval)
return asyncio.create_task(ping())
示例8: add_private_key_not_extended
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
def add_private_key_not_extended(self, key_not_extended: PrivateKey):
"""
Creates a new key, and takes only the prefix information (chain code, version, etc).
This is used to migrate pool_sks from keys.yaml, which are not extended. Then adds
the key to the keychain.
"""
key_bytes = bytes(key_not_extended)
new_extended_bytes = bytearray(
bytes(ExtendedPrivateKey.from_seed(token_bytes(32)))
)
final_extended_bytes = bytes(new_extended_bytes[: -len(key_bytes)] + key_bytes)
key = ExtendedPrivateKey.from_bytes(final_extended_bytes)
assert len(final_extended_bytes) == len(new_extended_bytes)
assert key.get_private_key() == key_not_extended
self.add_private_key(key)
示例9: create_payload
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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
示例10: reorg_from_index_to_new_index
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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}")
示例11: test_request_respond_transaction
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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)
示例12: test_respond_transaction_fail
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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
)
示例13: add_group
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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)
示例14: load_secret
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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]
示例15: test_token_defaults
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_bytes [as 别名]
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)