Python secrets.randbelow() Examples
The following are 30
code examples of secrets.randbelow().
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: test_curves.py From btclib with MIT License | 7 votes |
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)
Example #2
Source File: mnemonic.py From torba with MIT License | 6 votes |
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
Example #3
Source File: thresha.py From mpyc with MIT License | 6 votes |
def random_split(s, t, m): """Split each secret given in s into m random Shamir shares. The (maximum) degree for the Shamir polynomials is t, 0 <= t < n. Return matrix of shares, one row per party. """ field = type(s[0]) p = field.modulus order = field.order T = type(p) # T is int or gfpx.Polynomial n = len(s) shares = [[None] * n for _ in range(m)] for h in range(n): c = [secrets.randbelow(order) for _ in range(t)] # polynomial f(X) = s[h] + c[t-1] X + c[t-2] X^2 + ... + c[0] X^t for i in range(m): y = 0 if T is int else T(0) for c_j in c: y += c_j y *= i+1 shares[i][h] = (y + s[h].value) % p return shares
Example #4
Source File: cooldown.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def get_scaled(self, uid, base, multiplier=5): """ Scales a cooldown amount based on incrementing usage. :type uid: int :type base: int or float :type multiplier: int or float :param uid: User ID of the invoking user. :param base: Base cooldown amount to scale. :param multiplier: Maximum capped cooldown multiplier. :return: """ last_entry = self.scaling.get(uid, {}) last_stamp = last_entry.get('stamp', 0) last_count = last_entry.get('count', 0) now_stamp = arrow.utcnow().timestamp if now_stamp - last_stamp > base * multiplier: cooldown = base data_entry = {'stamp': now_stamp, 'count': 0} else: mod_base, mod_divider = 1125, 1000 modifier = (int(mod_base * 0.8) + secrets.randbelow(int(mod_base * 0.2))) / mod_divider cooldown = base * (1 + (modifier * last_count)) data_entry = {'stamp': now_stamp, 'count': last_count + 1} self.scaling.update({uid: data_entry}) return int(cooldown)
Example #5
Source File: randomcolor.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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')
Example #6
Source File: experience_activity.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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)
Example #7
Source File: butts.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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)
Example #8
Source File: boobs.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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)
Example #9
Source File: interaction_mechanics.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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
Example #10
Source File: item_core.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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
Example #11
Source File: item_object.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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
Example #12
Source File: core.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
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
Example #13
Source File: mnemonic.py From lbry-sdk with MIT License | 6 votes |
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
Example #14
Source File: test_curves.py From btclib with MIT License | 6 votes |
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")
Example #15
Source File: bms.py From btclib with MIT License | 6 votes |
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
Example #16
Source File: test_borromean.py From btclib with MIT License | 6 votes |
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))
Example #17
Source File: test_curves.py From btclib with MIT License | 6 votes |
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")
Example #18
Source File: ssa.py From btclib with MIT License | 6 votes |
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.
Example #19
Source File: auth.py From friendly-telegram with GNU Affero General Public License v3.0 | 5 votes |
def send_code(self, request): uid = int(await request.text()) if uid in self._uid_to_code.keys(): return web.Response() code = secrets.randbelow(100000) asyncio.ensure_future(asyncio.shield(self._clear_code(uid))) self._uid_to_code[uid] = b64encode(hashlib.scrypt((str(code).zfill(5) + str(uid)).encode("utf-8"), salt="friendlytgbot".encode("utf-8"), n=16384, r=8, p=1, dklen=64)).decode("utf-8") await self.client_data[uid][1].send_message("me", "Your code is <code>{:05d}</code>\nDo <b>not</b> " "share this code with anyone, even is they say they are" " from friendly-telegram.\nThe code will expire in " "2 minutes.".format(code)) return web.Response()
Example #20
Source File: human.py From lightbus with Apache License 2.0 | 5 votes |
def generate_human_friendly_name(): return "{}-{}-{}".format( secrets.choice(_adjectives), secrets.choice(_nouns), secrets.randbelow(999) + 1 )
Example #21
Source File: util.py From graham_discord_bot with MIT License | 5 votes |
def random_float() -> float: return secrets.randbelow(100) / 100
Example #22
Source File: schnorr.py From Zilliqa-Mining-Proxy with GNU General Public License v3.0 | 5 votes |
def sign(bytes_msg: bytes, bytes_private: bytes, retries=10) -> Optional[bytes]: for i in range(retries): k = secrets.randbelow(CURVE.q) if k == 0: continue signature = sign_with_k(bytes_msg, bytes_private, k) if signature: return signature return None
Example #23
Source File: currency_commands.py From PythonTwitchBotFramework with MIT License | 5 votes |
def cmd_gamble(msg: Message, *args): if len(args) != 2: raise InvalidArgumentsError(reason='missing required arguments', cmd=cmd_gamble) try: sides = int(args[0]) bet = int(args[1]) except ValueError: raise InvalidArgumentsError(reason='invalid value for sides or bet', cmd=cmd_gamble) if bet < 10: raise InvalidArgumentsError(reason='bet cannot be less then 10', cmd=cmd_gamble) elif sides < 2: raise InvalidArgumentsError(reason='sides cannot be less than 2', cmd=cmd_gamble) bal = get_balance_from_msg(msg) cur_name = get_currency_name(msg.channel_name).name if bal.balance < bet: raise InvalidArgumentsError(reason=f"{msg.mention} you don't have enough {cur_name}", cmd=cmd_gamble) n = randbelow(sides) + 1 if n == 1: if sides >= 6: bet *= 2 gain = bet + int(bet * (sides / 6)) bal.balance += gain await msg.reply(f'you rolled {n} and won {gain} {cur_name}') else: bal.balance -= bet await msg.reply(f'you rolled {n} and lost your bet of {bet} {cur_name}') session.commit()
Example #24
Source File: XDR_iocs.py From content with MIT License | 5 votes |
def create_iocs_to_keep_time(): offset = secrets.randbelow(115) hour, minute, = divmod(offset, 60) hour += 1 return hour, minute
Example #25
Source File: command.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def add_usage_sumarum(self, message): """ Adds a special currency type when a command is executed. :type message: discord.Message :param message: The message that triggered the resource addition. :return: """ trigger = f'usage_{self.name}' if message.guild and not await self.bot.cool_down.on_cooldown(trigger, message.author): await self.bot.cool_down.set_cooldown(trigger, message.author, 450) award = secrets.randbelow(3) if award: await self.db.add_resource(message.author.id, 'sumarum', award, trigger, message, True)
Example #26
Source File: dsa.py From btclib with MIT License | 5 votes |
def gen_keys(prvkey: PrvKey = None, ec: Curve = secp256k1) -> Tuple[int, Point]: "Return a private/public (int, Point) key-pair." 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) Q = ec._aff_from_jac(QJ) # q.to_bytes(ec.nsize, 'big') # bytes_from_point(Q, ec, compressed) return q, Q
Example #27
Source File: combinechains.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def shuffle(items): new = [] copy = [i for i in items] while len(copy) > 0: new.append(copy.pop(secrets.randbelow(len(copy)))) return new
Example #28
Source File: cyanideandhappiness.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def cyanideandhappiness(_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 """ comic_img_url = None comic_url = None tries = 0 while not comic_img_url and tries < 3: comic_number = secrets.randbelow(5060) + 1 comic_url = f'http://explosm.net/comics/{comic_number}/' async with aiohttp.ClientSession() as session: async with session.get(comic_url) as data: page = await data.text() root = html.fromstring(page) comic_element = root.cssselect('#main-comic') try: comic_img_url = comic_element[0].attrib.get('src') if comic_img_url.startswith('//'): comic_img_url = 'https:' + comic_img_url except IndexError: tries += 1 if comic_img_url: response = discord.Embed(color=0xFF6600) response.set_image(url=comic_img_url) cnh_image = 'https://i.imgur.com/jJl7FoT.jpg' response.set_author(name='Cyanide and Happiness', icon_url=cnh_image, url=comic_url) else: response = error('Failed to grab a comic, try again.') await pld.msg.channel.send(embed=response)
Example #29
Source File: entropy.py From btclib with MIT License | 5 votes |
def collect_rolls(bits: int) -> Tuple[int, List[int]]: dice_sides = 0 while dice_sides not in _dice_sides: automate = False msg = f"{_dice_sides}" msg = "dice sides " + msg[:-1] msg += ", prefix with 'a' to automate rolls): " dice_sides_str = input(msg) dice_sides_str = dice_sides_str.lower() if dice_sides_str.startswith("a"): automate = True dice_sides_str = dice_sides_str[1:] try: dice_sides = 6 if dice_sides_str == "" else int(dice_sides_str) except Exception: dice_sides = 0 bits_per_roll = math.floor(math.log2(dice_sides)) base = 2 ** bits_per_roll print(f"rolls are used only if in 1..{base}") rolls: List[int] = [] min_roll_number = math.ceil(bits / bits_per_roll) for i in range(min_roll_number): x = 0 while x < 1 or x > base: try: if automate: x_str = str(1 + secrets.randbelow(dice_sides)) else: x_str = input(f"roll #{i+1}/{min_roll_number}: ") x = int(x_str) except Exception: x = 0 rolls.append(x) print(f"collected {min_roll_number} usable D{dice_sides} rolls") return dice_sides, rolls
Example #30
Source File: status_rotation.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def status_clockwork(ev): """ :param ev: The event object referenced in the event. :type ev: sigma.core.mechanics.event.SigmaEvent """ while True: if ev.bot.is_ready(): if ev.bot.cfg.pref.status_rotation: if not status_cache: status_files = await ev.db[ev.db.db_nam].StatusFiles.find().to_list(None) [status_cache.append(status_file.get('text')) for status_file in status_files] if status_cache: status = status_cache.pop(secrets.randbelow(len(status_cache))) activity = discord.Activity(name=status, type=discord.ActivityType.playing) # noinspection PyBroadException try: if ev.bot.cfg.pref.dev_mode: status_type = discord.Status.dnd else: if ev.bot.latency > 5 or ev.bot.latency < 0: status_type = discord.Status.dnd elif ev.bot.latency > 2: status_type = discord.Status.idle else: status_type = discord.Status.online await ev.bot.change_presence(activity=activity, status=status_type) except Exception: pass await asyncio.sleep(60)