本文整理匯總了Python中secrets.SystemRandom方法的典型用法代碼示例。如果您正苦於以下問題:Python secrets.SystemRandom方法的具體用法?Python secrets.SystemRandom怎麽用?Python secrets.SystemRandom使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類secrets
的用法示例。
在下文中一共展示了secrets.SystemRandom方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: sample_poly_ternary
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import SystemRandom [as 別名]
def sample_poly_ternary(parms):
"""Generate a ternary polynomial uniformally with elements [-1, 0, 1]
where -1 is represented as (modulus - 1) because -1 % modulus == modulus - 1.
Used for generating secret key using coeff_modulus(list of prime nos) which
represents as 'q' in the research paper.
Args:
parms (EncryptionParam): Encryption parameters.
Returns:
A 2-dim list having integer from [-1, 0, 1].
"""
coeff_modulus = parms.coeff_modulus
coeff_count = parms.poly_modulus
coeff_mod_size = len(coeff_modulus)
result = [0] * coeff_mod_size
for i in range(coeff_mod_size):
result[i] = [0] * coeff_count
for i in range(coeff_count):
rand_index = SystemRandom().choice([-1, 0, 1])
if rand_index == 1:
for j in range(coeff_mod_size):
result[j][i] = 1
elif rand_index == -1:
for j in range(coeff_mod_size):
result[j][i] = coeff_modulus[j] - 1
else:
for j in range(coeff_mod_size):
result[j][i] = 0
return result
示例2: generate_token
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import SystemRandom [as 別名]
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
"""Generates a non-guessable OAuth token
OAuth (1 and 2) does not specify the format of tokens except that they
should be strings of random characters. Tokens should not be guessable
and entropy when generating the random characters is important. Which is
why SystemRandom is used instead of the default random.choice method.
"""
rand = SystemRandom()
return ''.join(rand.choice(chars) for x in range(length))
示例3: authorization_url
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import SystemRandom [as 別名]
def authorization_url(self, **kwargs):
"""Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authorization URI (usually
Google's authorization server) and specifies that "offline" access is
desired. This is required in order to obtain a refresh token.
Args:
kwargs: Additional arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
Returns:
Tuple[str, str]: The generated authorization URL and state. The
user must visit the URL to complete the flow. The state is used
when completing the flow to verify that the request originated
from your application. If your application is using a different
:class:`Flow` instance to obtain the token, you will need to
specify the ``state`` when constructing the :class:`Flow`.
"""
kwargs.setdefault("access_type", "offline")
if self.autogenerate_code_verifier:
chars = ascii_letters + digits + "-._~"
rnd = SystemRandom()
random_verifier = [rnd.choice(chars) for _ in range(0, 128)]
self.code_verifier = "".join(random_verifier)
if self.code_verifier:
code_hash = hashlib.sha256()
code_hash.update(str.encode(self.code_verifier))
unencoded_challenge = code_hash.digest()
b64_challenge = urlsafe_b64encode(unencoded_challenge)
code_challenge = b64_challenge.decode().split("=")[0]
kwargs.setdefault("code_challenge", code_challenge)
kwargs.setdefault("code_challenge_method", "S256")
url, state = self.oauth2session.authorization_url(
self.client_config["auth_uri"], **kwargs
)
return url, state
示例4: binstr_from_rolls
# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import SystemRandom [as 別名]
def binstr_from_rolls(
bits: int, dice_sides: int, rolls: List[int], shuffle: bool = True,
) -> BinStr:
"""Return raw entropy from the input dice rolls.
Dice rolls are represented by integers in the [1-dice_sides] range;
there must be enough rolls to satisfy the bit-size requirement.
Only rolls having value in the [1-base] range are used,
with base being the highest power of 2 that is lower than the
dice_sides (e.g. for a traditional D6 dice, only rolls having value
in [1-4] are used; for a D20 dice, only rolls having value in
[1-16] are used; etc.). Rolls can also be shuffled.
If more bits than required are provided,
the leftmost ones are retained.
"""
if dice_sides < 2:
raise ValueError(f"Invalid dice base: {dice_sides}, must be >= 2")
bits_per_roll = math.floor(math.log2(dice_sides))
# used base
base = 2 ** bits_per_roll
if shuffle:
secrets.SystemRandom().shuffle(rolls)
min_roll_number = math.ceil(bits / bits_per_roll)
i = 0
for r in rolls:
# collect only usable rolls in [1-base)]
if 0 < r and r <= base:
i *= base
i += r - 1
min_roll_number -= 1
# reject invalid rolls not in [1-dice_sides)]
elif r < 1 or r > dice_sides:
msg = f"Invalid roll: {r} is not in [1-{dice_sides}]"
raise ValueError(msg)
if min_roll_number > 0:
msg = f"Too few rolls in the usable [1-{base}] range, missing {min_roll_number} rolls"
raise ValueError(msg)
return binstr_from_int(i, bits)