本文整理汇总了Python中os.urandom方法的典型用法代码示例。如果您正苦于以下问题:Python os.urandom方法的具体用法?Python os.urandom怎么用?Python os.urandom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.urandom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: seed_bootaction_status
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def seed_bootaction_status(self, blank_state, yaml_orchestrator,
input_files):
"""Add a task and boot action to the database for testing."""
input_file = input_files.join("fullsite.yaml")
design_ref = "file://%s" % input_file
test_task = yaml_orchestrator.create_task(
action=hd_fields.OrchestratorAction.Noop, design_ref=design_ref)
id_key = os.urandom(32)
action_id = ulid2.generate_binary_ulid()
blank_state.post_boot_action('compute01', test_task.get_id(), id_key,
action_id, 'helloworld')
ba = dict(
nodename='compute01',
task_id=test_task.get_id(),
identity_key=id_key.hex(),
action_id=ulid2.encode_ulid_base32(action_id))
return ba
示例2: test_bootaction_render_design_ref
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def test_bootaction_render_design_ref(self, input_files, deckhand_ingester,
setup):
"""Test the bootaction render routine provides expected output."""
input_file = input_files.join("deckhand_fullsite.yaml")
design_state = DrydockState()
design_ref = "file://%s" % str(input_file)
design_status, design_data = deckhand_ingester.ingest_data(
design_state=design_state, design_ref=design_ref)
ba = design_data.get_bootaction('helloworld')
action_id = ulid2.generate_binary_ulid()
action_key = os.urandom(32)
assets = ba.render_assets('compute01', design_data, action_id,
action_key, design_ref)
assert 'deckhand_fullsite.yaml' in assets[2].rendered_bytes.decode(
'utf-8')
示例3: test_bootaction_render_key
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def test_bootaction_render_key(self, input_files, deckhand_ingester,
setup):
"""Test that a bootaction can render the correct action_id and
action_key needed by the signalling API."""
input_file = input_files.join("deckhand_fullsite.yaml")
design_state = DrydockState()
design_ref = "file://%s" % str(input_file)
design_status, design_data = deckhand_ingester.ingest_data(
design_state=design_state, design_ref=design_ref)
ba = design_data.get_bootaction('helloworld')
action_id = ulid2.generate_binary_ulid()
action_key = os.urandom(32)
assets = ba.render_assets('compute01', design_data, action_id,
action_key, design_ref)
assert action_key.hex() in assets[2].rendered_bytes.decode('utf-8')
assert ulid2.ulid_to_base32(
action_id) in assets[2].rendered_bytes.decode('utf-8')
示例4: create
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def create(args):
vpc = ensure_vpc()
if args.security_groups is None:
args.security_groups = [__name__]
ensure_security_group(__name__, vpc, tcp_ingress=[dict(port=socket.getservbyname("nfs"),
source_security_group_name=__name__)])
creation_token = base64.b64encode(bytearray(os.urandom(24))).decode()
args.tags.append("Name=" + args.name)
create_file_system_args = dict(CreationToken=creation_token,
PerformanceMode=args.performance_mode,
ThroughputMode=args.throughput_mode,
Tags=encode_tags(args.tags))
if args.throughput_mode == "provisioned":
create_file_system_args.update(ProvisionedThroughputInMibps=args.provisioned_throughput_in_mibps)
fs = clients.efs.create_file_system(**create_file_system_args)
waiter = make_waiter(clients.efs.describe_file_systems, "FileSystems[].LifeCycleState", "available", "pathAny")
waiter.wait(FileSystemId=fs["FileSystemId"])
security_groups = [resolve_security_group(g, vpc).id for g in args.security_groups]
for subnet in vpc.subnets.all():
clients.efs.create_mount_target(FileSystemId=fs["FileSystemId"],
SubnetId=subnet.id,
SecurityGroups=security_groups)
return fs
示例5: test_BinaryFuzz_fuzz_data
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def test_BinaryFuzz_fuzz_data(self):
f = BinaryFuzz.BinaryFileFuzzer()
test_size = 1000
test_data = os.urandom(test_size)
for fuzz_type in range(BinaryFuzz.BINFUZZ_N+1):
if fuzz_type >= BinaryFuzz.BINFUZZ_N:
fuzz_type = None
with self.assertRaises(TypeError):
f.fuzz_data(test_data, "1")
fuzz_count, fuzz_data = f.fuzz_data(test_data, 0, fuzz_type=fuzz_type) # no fuzzing
self.assertEqual(fuzz_count, 0, "Data was fuzzed")
fuzz_count, fuzz_data = f.fuzz_data(test_data, -1, fuzz_type=fuzz_type)
self.assertEqual(fuzz_count, 1)
self.assertNotEqual(test_data, fuzz_data, "Data was not fuzzed (may happen randomly)")
fuzz_count, fuzz_data = f.fuzz_data(test_data, test_size/100, fuzz_type=fuzz_type)
self.assertAlmostEqual(fuzz_count, test_size/10, delta=10)
self.assertNotEqual(test_data, fuzz_data, "Data was not fuzzed")
示例6: step
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def step(self, amt=8):
if self.scroll:
new_bytes = [i for i in bytearray(
os.urandom(self.rand_bytes_rows))]
for y in range(self.rand_bytes_rows):
self.bytes[y].pop(0)
self.bytes[y].append(new_bytes[y])
else:
self.__genBytes()
for y in range(self.height):
for x in range(self.width):
b = self.bytes[y // 8][x]
bit = bool(b & (1 << (y % 8)))
color = self.palette(int(bit))
self.layout.set(self.width - x - 1, y, color)
示例7: test_io_and_many_files
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def test_io_and_many_files(self):
import os
from time import time
start = time()
for i in range(10000): # 顺便测试能不能承受大量文件
obj = os.urandom(16 * 1024)
self.cache.put_obj(i, obj, info_dict={"bin": obj})
for i in range(10000):
info = self.cache.get_info(i)
obj = self.cache.get_obj(i)
self.assertEqual(info['bin'], obj)
print("test_io_and_many_files IO total time:", time() - start)
# test clean delete
all_cache_file_path = [v[0] for v in self.cache.items_dict.values()]
start = time()
del self.cache
print("test_io_and_many_files DELETE ALL total time:", time() - start)
for path in all_cache_file_path:
self.assertFalse(os.path.exists(path), msg=path)
示例8: _get_key
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def _get_key():
if this.key:
return this.key
secret = getpass.getpass()
try:
salt = config().get('Security', 'salt')
except NoOptionError:
salt = base64.urlsafe_b64encode(os.urandom(16))
config().set('Security', 'salt', salt)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
this.key = base64.urlsafe_b64encode(kdf.derive(secret))
return this.key
示例9: _encrypt
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def _encrypt(self, b_data, session):
header = SMB2TransformHeader()
header['original_message_size'] = len(b_data)
header['session_id'] = session.session_id
encryption_key = session.encryption_key
if self.dialect >= Dialects.SMB_3_1_1:
cipher = self.cipher_id
else:
cipher = Ciphers.get_cipher(Ciphers.AES_128_CCM)
if cipher == aead.AESGCM:
nonce = os.urandom(12)
header['nonce'] = nonce + (b"\x00" * 4)
else:
nonce = os.urandom(11)
header['nonce'] = nonce + (b"\x00" * 5)
cipher_text = cipher(encryption_key).encrypt(nonce, b_data, header.pack()[20:])
signature = cipher_text[-16:]
enc_message = cipher_text[:-16]
header['signature'] = signature
header['data'] = enc_message
return header
示例10: create
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def create(self, extra_entropy=''):
r"""
Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.
:param extra_entropy: Add extra randomness to whatever randomness your OS can provide
:type extra_entropy: str or bytes or int
:returns: an object with private key and convenience methods
.. code-block:: python
>>> from eth_account import Account
>>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
>>> acct.address
'0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
>>> acct.key
HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8')
# These methods are also available: sign_message(), sign_transaction(), encrypt()
# They correspond to the same-named methods in Account.*
# but without the private key argument
"""
extra_key_bytes = text_if_str(to_bytes, extra_entropy)
key_bytes = keccak(os.urandom(32) + extra_key_bytes)
return self.from_key(key_bytes)
示例11: testApproximateSizes
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def testApproximateSizes(self):
db = self.db_class(self.db_path, create_if_missing=True)
self.assertEqual([0, 0, 0],
db.approximateDiskSizes(("a", "z"), ("0", "9"), ("A", "Z")))
batch = leveldb.WriteBatch()
for i in xrange(100):
batch.put("c%d" % i, os.urandom(4096))
db.write(batch, sync=True)
db.close()
db = self.db_class(self.db_path)
sizes = db.approximateDiskSizes(("0", "9"), ("A", "Z"), ("a", "z"))
self.assertEqual(sizes[0], 0)
self.assertEqual(sizes[1], 0)
self.assertTrue(sizes[2] >= 4096 * 100)
for i in xrange(10):
db.put("3%d" % i, os.urandom(10))
db.close()
db = self.db_class(self.db_path)
sizes = db.approximateDiskSizes(("A", "Z"), ("a", "z"), ("0", "9"))
self.assertEqual(sizes[0], 0)
self.assertTrue(sizes[1] >= 4096 * 100)
self.assertTrue(sizes[2] < 4096 * 100)
self.assertTrue(sizes[2] >= 10 * 10)
db.close()
示例12: makeFile
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def makeFile():
"""
Membuat file hasil brute force
"""
dirname = os.path.dirname(SETTING.OUTPUT)
if not dirname:
dirname = DEFAULT.OUTPUT_DIRECTORY
elif not os.path.isdir(os.path.realpath(dirname)):
warnMsg = "No such directory %s (using default %s)"
warnMsg %= (repr(dirname), repr(DEFAULT.OUTPUT_DIRECTORY))
logger.warn(warnMsg)
dirname = DEFAULT.OUTPUT_DIRECTORY
dirname = os.path.realpath(dirname)
filename = os.path.basename(SETTING.OUTPUT)
if not filename:
filename = DEFAULT.FILENAME
else:
filename = filename.split(".", 1)[0]
filename = filename + "-" + os.urandom(4).encode("hex") + "." + DEFAULT.FILE_EXTENSION
filepath = os.path.join(dirname, filename)
fp = open(filepath, "w")
return fp
示例13: encrypt_message_data
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def encrypt_message_data(self, data):
"""
Encrypts the given message data using the current authorization key
following MTProto 2.0 guidelines core.telegram.org/mtproto/description.
"""
data = struct.pack('<qq', self.salt, self.id) + data
padding = os.urandom(-(len(data) + 12) % 16 + 12)
# Being substr(what, offset, length); x = 0 for client
# "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)"
msg_key_large = sha256(
self.auth_key.key[88:88 + 32] + data + padding).digest()
# "msg_key = substr (msg_key_large, 8, 16)"
msg_key = msg_key_large[8:24]
aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, True)
key_id = struct.pack('<Q', self.auth_key.key_id)
return (key_id + msg_key +
AES.encrypt_ige(data + padding, aes_key, aes_iv))
示例14: init_header
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def init_header(packet_codec):
# Obfuscated messages secrets cannot start with any of these
keywords = (b'PVrG', b'GET ', b'POST', b'\xee\xee\xee\xee')
while True:
random = os.urandom(64)
if (random[0] != 0xef and
random[:4] not in keywords and
random[4:8] != b'\0\0\0\0'):
break
random = bytearray(random)
random_reversed = random[55:7:-1] # Reversed (8, len=48)
# Encryption has "continuous buffer" enabled
encrypt_key = bytes(random[8:40])
encrypt_iv = bytes(random[40:56])
decrypt_key = bytes(random_reversed[:32])
decrypt_iv = bytes(random_reversed[32:48])
encryptor = AESModeCTR(encrypt_key, encrypt_iv)
decryptor = AESModeCTR(decrypt_key, decrypt_iv)
random[56:60] = packet_codec.obfuscate_tag
random[56:64] = encryptor.encrypt(bytes(random))[56:64]
return (random, encryptor, decryptor)
示例15: qute_settings
# 需要导入模块: import os [as 别名]
# 或者: from os import urandom [as 别名]
def qute_settings(url: QUrl) -> _HandlerRet:
"""Handler for qute://settings. View/change qute configuration."""
global csrf_token
if url.path() == '/set':
if url.password() != csrf_token:
message.error("Invalid CSRF token for qute://settings!")
raise RequestDeniedError("Invalid CSRF token!")
return _qute_settings_set(url)
# Requests to qute://settings/set should only be allowed from
# qute://settings. As an additional security precaution, we generate a CSRF
# token to use here.
if secrets:
csrf_token = secrets.token_urlsafe()
else:
# On Python < 3.6, from secrets.py
token = base64.urlsafe_b64encode(os.urandom(32))
csrf_token = token.rstrip(b'=').decode('ascii')
src = jinja.render('settings.html', title='settings',
configdata=configdata,
confget=config.instance.get_str,
csrf_token=csrf_token)
return 'text/html', src