Python secrets.SystemRandom() Examples

The following are 5 code examples of secrets.SystemRandom(). 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: rlwe.py    From PySyft with Apache License 2.0 5 votes vote down vote up
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 
Example #2
Source File: common.py    From Requester with MIT License 5 votes vote down vote up
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)) 
Example #3
Source File: common.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #4
Source File: flow.py    From google-auth-library-python-oauthlib with Apache License 2.0 4 votes vote down vote up
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 
Example #5
Source File: entropy.py    From btclib with MIT License 4 votes vote down vote up
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)