本文整理匯總了Python中secrets.randbelow方法的典型用法代碼示例。如果您正苦於以下問題:Python secrets.randbelow方法的具體用法?Python secrets.randbelow怎麽用?Python secrets.randbelow使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類secrets
的用法示例。
在下文中一共展示了secrets.randbelow方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: make_seed
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def make_seed(self, prefix=SEED_PREFIX, num_bits=132):
# increase num_bits in order to obtain a uniform distribution for the last word
bpw = math.log(len(self.words), 2)
# rounding
n = int(math.ceil(num_bits/bpw) * bpw)
entropy = 1
while 0 < entropy < pow(2, n - bpw):
# try again if seed would not contain enough words
entropy = randbelow(pow(2, n))
nonce = 0
while True:
nonce += 1
i = entropy + nonce
seed = self.mnemonic_encode(i)
if i != self.mnemonic_decode(seed):
raise Exception('Cannot extract same entropy from mnemonic!')
if is_new_seed(seed, prefix):
break
return seed
示例2: gen_keys
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def gen_keys(
prvkey: PrvKey = None,
network: Optional[str] = None,
compressed: Optional[bool] = None,
) -> Tuple[bytes, bytes]:
"""Return a private/public key pair.
The private key is a WIF, the public key is a base58 P2PKH address.
"""
if prvkey is None:
if network is None:
network = "mainnet"
ec = NETWORKS[network]["curve"]
# q in the range [1, ec.n-1]
q = 1 + secrets.randbelow(ec.n - 1)
wif = wif_from_prvkey(q, network, compressed)
else:
wif = wif_from_prvkey(prvkey, network, compressed)
address = p2pkh(wif)
return wif, address
示例3: test_borromean
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def test_borromean(self):
nring = 4 # FIXME randomize; minimum number of rings?
ring_sizes = [1 + secrets.randbelow(7) for _ in range(nring)]
sign_key_idx = [secrets.randbelow(size) for size in ring_sizes]
pubk_rings: Dict[int, List[Point]] = defaultdict(list)
sign_keys: List[int] = []
for i in range(nring):
for j in range(ring_sizes[i]):
priv_key, pub_key = dsa.gen_keys()
pubk_rings[i].append(pub_key)
if j == sign_key_idx[i]:
sign_keys.append(priv_key)
msg = "Borromean ring signature"
sig = borromean.sign(
msg, list(range(1, 5)), sign_key_idx, sign_keys, pubk_rings
)
borromean.assert_as_valid(msg.encode(), sig[0], sig[1], pubk_rings)
self.assertTrue(borromean.verify(msg, sig[0], sig[1], pubk_rings))
self.assertFalse(borromean.verify(0, sig[0], sig[1], pubk_rings))
示例4: test_aff_jac_conversions
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def test_aff_jac_conversions():
for ec in all_curves.values():
# just a random point, not INF
q = 1 + secrets.randbelow(ec.n - 1)
Q = _mult_aff(q, ec.G, ec)
QJ = _jac_from_aff(Q)
assert Q == ec._aff_from_jac(QJ)
x_Q = ec._x_aff_from_jac(QJ)
assert Q[0] == x_Q
assert INF == ec._aff_from_jac(_jac_from_aff(INF))
# relevant for BIP340-Schnorr signature verification
assert not ec.has_square_y(INF)
with pytest.raises(ValueError, match="infinity point has no x-coordinate"):
ec._x_aff_from_jac(INFJ)
with pytest.raises(TypeError, match="not a point"):
ec.has_square_y("notapoint")
示例5: test_add
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def test_add():
for ec in all_curves.values():
# just a random point, not INF
q = 1 + secrets.randbelow(ec.n - 1)
Q = _mult_aff(q, ec.G, ec)
QJ = _jac_from_aff(Q)
# add Q and G
R = ec._add_aff(Q, ec.G)
RJ = ec._add_jac(QJ, ec.GJ)
assert R == ec._aff_from_jac(RJ)
# double Q
R = ec._add_aff(Q, Q)
RJ = ec._add_jac(QJ, QJ)
assert R == ec._aff_from_jac(RJ)
示例6: test_negate
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def test_negate():
for ec in all_curves.values():
# just a random point, not INF
q = 1 + secrets.randbelow(ec.n - 1)
Q = _mult_aff(q, ec.G, ec)
minus_Q = ec.negate(Q)
assert ec.add(Q, minus_Q) == INF
# Jacobian coordinates
QJ = _jac_from_aff(Q)
minus_QJ = ec.negate(QJ)
assert ec._add_jac(QJ, minus_QJ) == INFJ
# negate of INF is INF
minus_INF = ec.negate(INF)
assert minus_INF == INF
# negate of INFJ is INFJ
minus_INFJ = ec.negate(INFJ)
assert minus_INFJ == INFJ
with pytest.raises(TypeError, match="not a point"):
ec.negate("notapoint")
示例7: gen_keys
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def gen_keys(prvkey: PrvKey = None, ec: Curve = secp256k1) -> Tuple[int, int]:
"Return a BIP340 private/public (int, int) key-pair."
# BIP340 is only defined for curves whose field prime p = 3 % 4
ec.require_p_ThreeModFour()
if prvkey is None:
# q in the range [1, ec.n-1]
q = 1 + secrets.randbelow(ec.n - 1)
else:
q = int_from_prvkey(prvkey, ec)
QJ = _mult_jac(q, ec.GJ, ec)
x_Q = ec._x_aff_from_jac(QJ)
return q, x_Q
# This implementation can be sped up by storing the midstate after hashing
# tag_hash instead of rehashing it all the time.
示例8: bot_move
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def bot_move(self, last: int):
"""
:param last:
:type last:
:return:
:rtype:
"""
choice, bad_col = None, True
while bad_col:
move = secrets.randbelow(3)
if move == 0:
mod = secrets.choice([-1, 0, 1])
choice = max(min(6, last + mod), 0)
else:
choice = secrets.randbelow(6)
if not self.column_full(choice):
bad_col = False
return choice
示例9: roll_quality
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def roll_quality():
"""
Rolls a random quality value when cooking.
:return:
:rtype: int
"""
roll_num = secrets.randbelow(100)
if roll_num in range(66, 85):
quality = 1
elif roll_num in range(86, 95):
quality = 2
elif roll_num in range(96, 100):
quality = 3
else:
quality = 0
return quality
示例10: roll_rarity
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def roll_rarity(self, profile):
"""
Rolls a random rarity.
:param profile: The user's profile data.
:type profile: dict
:return:
:rtype: int
"""
upgrade_file = profile.get('upgrades') or {}
upgrade_level = upgrade_file.get('luck', 0)
top_roll, rarities = self.create_roll_range(upgrade_level)
roll = secrets.randbelow(top_roll)
lowest = 0
for rarity in rarities:
if rarities[rarity] <= roll:
lowest = rarity
else:
break
return lowest
示例11: grab_interaction
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def grab_interaction(db, intername):
"""
Gets a single interaction for the given interaction type name.
:param db: The main database handler reference.
:type db: sigma.core.mechanics.database.Database
:param intername: The name of the interaction type.
:type intername: str
:return:
:rtype: dict
"""
cache_key = f'interaction_cache_{intername}'
interaction_cache = await db.cache.get_cache(cache_key) or {}
fill = False if interaction_cache else True
if fill:
interaction_cache = await get_interaction_list(db, intername)
await db.cache.set_cache(cache_key, interaction_cache)
if interaction_cache:
choice = interaction_cache.pop(secrets.randbelow(len(interaction_cache)))
await db.cache.set_cache(cache_key, interaction_cache)
else:
choice = {'url': 'https://i.imgur.com/m59E4nx.gif', 'user_id': None, 'server_id': None, 'interaction_id': None}
return choice
示例12: boobs
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def boobs(_cmd, pld):
"""
:param _cmd: The command object referenced in the command.
:type _cmd: sigma.core.mechanics.command.SigmaCommand
:param pld: The payload with execution data and details.
:type pld: sigma.core.mechanics.payload.CommandPayload
"""
api_url = 'http://api.oboobs.ru/boobs/'
api_url += str(secrets.randbelow(12243) + 1)
async with aiohttp.ClientSession() as session:
async with session.get(api_url) as data:
data = await data.read()
data = json.loads(data)
data = data[0]
image_url = 'http://media.oboobs.ru/' + data['preview']
model = data['model'] if data['model'] else 'Unknown'
rank = data['rank']
boobs_icon = 'http://fc01.deviantart.net/fs71/f/2013/002/d/9/_boobs_icon_base__by_laurypinky972-d5q83aw.png'
response = discord.Embed(color=0xF9F9F9)
response.set_author(name='Open Boobs', icon_url=boobs_icon)
response.set_image(url=image_url)
response.set_footer(text=f'Ranking: {rank} | Model: {model}')
await pld.msg.channel.send(embed=response)
示例13: butts
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def butts(_cmd, pld):
"""
:param _cmd: The command object referenced in the command.
:type _cmd: sigma.core.mechanics.command.SigmaCommand
:param pld: The payload with execution data and details.
:type pld: sigma.core.mechanics.payload.CommandPayload
"""
api_url = 'http://api.obutts.ru/butts/'
api_url += str(secrets.randbelow(5990) + 1)
async with aiohttp.ClientSession() as session:
async with session.get(api_url) as data:
data = await data.read()
data = json.loads(data)
data = data[0]
image_url = 'http://media.obutts.ru/' + data['preview']
model = data['model'] if data['model'] else 'Unknown'
rank = data['rank']
butts_icon = 'https://i.imgur.com/zjndjaj.png'
response = discord.Embed(color=0xF9F9F9)
response.set_author(name='Open Butts', icon_url=butts_icon)
response.set_image(url=image_url)
response.set_footer(text=f'Ranking: {rank} | Model: {model}')
await pld.msg.channel.send(embed=response)
示例14: experience_activity
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def experience_activity(ev, pld):
"""
:param ev: The event object referenced in the event.
:type ev: sigma.core.mechanics.event.SigmaEvent
:param pld: The event payload data to process.
:type pld: sigma.core.mechanics.payload.MessagePayload
"""
if pld.msg.guild:
if not await ev.bot.cool_down.on_cooldown(ev.name, pld.msg.author):
await ev.bot.cool_down.set_cooldown(ev.name, pld.msg.author, 80)
if len(pld.msg.guild.members) >= 100:
award_xp = 180
else:
award_xp = 150
award_xp += secrets.randbelow(5) * 18
await ev.db.add_resource(pld.msg.author.id, 'experience', award_xp, 'message_experience', pld.msg, True)
示例15: randomcolor
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbelow [as 別名]
def randomcolor(_cmd, pld):
"""
:param _cmd: The command object referenced in the command.
:type _cmd: sigma.core.mechanics.command.SigmaCommand
:param pld: The payload with execution data and details.
:type pld: sigma.core.mechanics.payload.CommandPayload
"""
piece_r = secrets.randbelow(256)
piece_g = secrets.randbelow(256)
piece_b = secrets.randbelow(256)
color_tupple = (piece_r, piece_g, piece_b)
hexname = f'Color: `#{str(hex(piece_r))[2:]}{str(hex(piece_g))[2:]}{str(hex(piece_b))[2:]}`'
image = Image.new('RGB', (128, 128), color_tupple)
image.save(f'cache/{pld.msg.id}.png')
img_file = discord.File(f'cache/{pld.msg.id}.png')
await pld.msg.channel.send(hexname, file=img_file)
os.remove(f'cache/{pld.msg.id}.png')