当前位置: 首页>>代码示例>>Python>>正文


Python secrets.SystemRandom方法代码示例

本文整理汇总了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 
开发者ID:OpenMined,项目名称:PySyft,代码行数:35,代码来源:rlwe.py

示例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)) 
开发者ID:kylebebak,项目名称:Requester,代码行数:12,代码来源:common.py

示例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 
开发者ID:googleapis,项目名称:google-auth-library-python-oauthlib,代码行数:46,代码来源:flow.py

示例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) 
开发者ID:fametrano,项目名称:btclib,代码行数:46,代码来源:entropy.py


注:本文中的secrets.SystemRandom方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。