Python random.SystemRandom() Examples

The following are 30 code examples for showing how to use random.SystemRandom(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module random , or try the search function .

Example 1
Project: OctoPrint-Anywhere   Author: kennethjiang   File: config.py    License: MIT License 6 votes vote down vote up
def reset_config(self):
        original_items = self.__items__
        try:
            import random
            import string
            # If config file not found, create a new random string as token
            token = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))

            with open(self.config_path, 'w') as outfile:
                with self._mutex:
                    original_items.update(dict(
                            token=token,
                            registered=False,
                            ws_host="wss://www.getanywhere.io",
                            api_host="https://www.getanywhere.io",
                            stream_host="http://stream.getanywhere.io"
                            ))

                    self.__items__ = original_items
                    yaml.dump(self.__items__, outfile, default_flow_style=False)
        except:
            self.sentry.captureException()
            import traceback; traceback.print_exc() 
Example 2
Project: ironpython2   Author: IronLanguages   File: test_random.py    License: Apache License 2.0 6 votes vote down vote up
def test_main(verbose=None):
    testclasses =    [WichmannHill_TestBasicOps,
                      MersenneTwister_TestBasicOps,
                      TestDistributions,
                      TestModule]

    try:
        random.SystemRandom().random()
    except NotImplementedError:
        pass
    else:
        testclasses.append(SystemRandom_TestBasicOps)

    test_support.run_unittest(*testclasses)

    # verify reference counting
    import sys
    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in xrange(len(counts)):
            test_support.run_unittest(*testclasses)
            counts[i] = sys.gettotalrefcount()
        print counts 
Example 3
Project: clusterfuzz   Author: google   File: options.py    License: Apache License 2.0 6 votes vote down vote up
def get_engine_arguments(self, engine):
    """Return a list of fuzzer options."""
    arguments = {}
    for option_name, option_value in six.iteritems(
        self._get_option_section(engine)):
      # Check option value for usage of random() function.
      match = self.OPTIONS_RANDOM_REGEX.match(option_value)
      if match:
        min_value, max_value = match.groups()
        option_value = str(random.SystemRandom().randint(
            int(min_value), int(max_value)))

      if option_name == 'dict':
        option_value = self._get_dict_path(option_value)

      arguments[option_name] = option_value

    return FuzzerArguments(arguments) 
Example 4
Project: clusterfuzz   Author: google   File: builtin.py    License: Apache License 2.0 6 votes vote down vote up
def _get_fuzzer_binary_name_and_path(self):
    """Returns the fuzzer binary name and its path."""
    # Fuchsia doesn't use file paths to call fuzzers, just the name of the
    # fuzzer, so we set both from FUZZ_TARGET here.
    if environment.platform() == 'FUCHSIA':
      fuzzer_binary_name = fuzzer_path = environment.get_value('FUZZ_TARGET')
      return fuzzer_binary_name, fuzzer_path
    build_directory = environment.get_value('BUILD_DIR')

    if not build_directory:
      raise BuiltinFuzzerException('BUILD_DIR environment variable is not set.')

    fuzzers = fuzzers_utils.get_fuzz_targets(build_directory)

    if not fuzzers:
      raise BuiltinFuzzerException(
          'No fuzzer binaries found in |BUILD_DIR| directory.')

    fuzzer_binary_name = environment.get_value('FUZZ_TARGET')
    if fuzzer_binary_name:
      fuzzer_path = _get_fuzzer_path(fuzzers, fuzzer_binary_name)
    else:
      fuzzer_path = random.SystemRandom().choice(fuzzers)
      fuzzer_binary_name = os.path.basename(fuzzer_path)
    return fuzzer_binary_name, fuzzer_path 
Example 5
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: fuzzer.py    License: MIT License 6 votes vote down vote up
def insertFuzz(url, fuzz):
    """
        :Description: This function inserts the Fuzz as GET Parameter in the URL 

        :param url: Target URL
        :type type: String
        
        :param fuzz: Fuzzing string
        :type fuzz: String

        :return: The URL with a concatenated string consisting of a random string and the fuzz.
        :note: Some fuzzing symbols can be part of a normal response. In order to distinctly find the fuzz that was sent, a random string is added before the fuzz.

    """

    fuzz = urllib.quote_plus(fuzz) #url encoding
    randomString = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6))
    return randomString, url.replace('FUZZ', randomString + str(fuzz)) 
Example 6
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: fuzzer.py    License: MIT License 6 votes vote down vote up
def setParams(params, fuzz):
    """
        :Description: This function sets the Fuzz in the POST Parameter.

        :param url: Target URL
        :type type: String
        
        :param fuzz: Fuzzing string
        :type fuzz: String

        :return: The post parameter with a concatenated string consisting of a random string and the fuzz
        :note: Some fuzzing symbols can be part of a normal response. In order to distinctly find the fuzz that was sent, a random string is added before the fuzz.

    """
    
    randomString = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6))
    parameter = copy.deepcopy(params) #makes a deep copy. this is needed because using a reference does not work
    for param in parameter:
        if parameter[param] == 'FUZZ':
            parameter[param] = randomString + str(fuzz)
    return randomString, parameter; 
Example 7
Project: daf-recipes   Author: italia   File: create.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_random_username_from_email(email):
    localpart = email.split('@')[0]
    cleaned_localpart = re.sub(r'[^\w]', '-', localpart).lower()

    # if we can't create a unique user name within this many attempts
    # then something else is probably wrong and we should give up
    max_name_creation_attempts = 100

    for i in range(max_name_creation_attempts):
        random_number = random.SystemRandom().random() * 10000
        name = '%s-%d' % (cleaned_localpart, random_number)
        if not ckan.model.User.get(name):
            return name

    return cleaned_localpart


## Modifications for rest api 
Example 8
Project: BinderFilter   Author: dxwu   File: test_random.py    License: MIT License 6 votes vote down vote up
def test_main(verbose=None):
    testclasses =    [WichmannHill_TestBasicOps,
                      MersenneTwister_TestBasicOps,
                      TestDistributions,
                      TestModule]

    try:
        random.SystemRandom().random()
    except NotImplementedError:
        pass
    else:
        testclasses.append(SystemRandom_TestBasicOps)

    test_support.run_unittest(*testclasses)

    # verify reference counting
    import sys
    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in xrange(len(counts)):
            test_support.run_unittest(*testclasses)
            counts[i] = sys.gettotalrefcount()
        print counts 
Example 9
Project: oss-ftp   Author: aliyun   File: test_random.py    License: MIT License 6 votes vote down vote up
def test_main(verbose=None):
    testclasses =    [WichmannHill_TestBasicOps,
                      MersenneTwister_TestBasicOps,
                      TestDistributions,
                      TestModule]

    try:
        random.SystemRandom().random()
    except NotImplementedError:
        pass
    else:
        testclasses.append(SystemRandom_TestBasicOps)

    test_support.run_unittest(*testclasses)

    # verify reference counting
    import sys
    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in xrange(len(counts)):
            test_support.run_unittest(*testclasses)
            counts[i] = sys.gettotalrefcount()
        print counts 
Example 10
Project: pybtc   Author: bitaps-com   File: shamir.py    License: GNU General Public License v3.0 6 votes vote down vote up
def split_secret(threshold, total,  secret):
    if not isinstance(secret, bytes):
        raise TypeError("Secret as byte string required")
    if threshold > 255:
        raise ValueError("threshold <= 255")
    if total > 255:
        raise ValueError("total shares <= 255")
    shares = dict()
    for i in range(total):
        shares[i+1] = b""
    for b in secret:
        q = [b]
        for i in range(threshold - 1):
            a = random.SystemRandom().randint(0, 255)
            q.append(a)

        for x in range(total):
            shares[x+1] += bytes([_fn(x + 1, q)])

    return shares 
Example 11
Project: pybtc   Author: bitaps-com   File: bip39_mnemonic.py    License: GNU General Public License v3.0 6 votes vote down vote up
def generate_entropy(strength=256, hex=True):
    """
    Generate 128-256 bits entropy bytes string

    :param int strength: entropy bits strength, by default is 256 bit.
    :param boolean hex: return HEX encoded string result flag, by default True.
    :return: HEX encoded or bytes entropy string.
    """
    if strength not in [128, 160, 192, 224, 256]:
        raise ValueError('strength should be one of the following [128, 160, 192, 224, 256]')
    a = random.SystemRandom().randint(0, ECDSA_SEC256K1_ORDER)
    i = int((time.time() % 0.01 ) * 100000)
    h = a.to_bytes(32, byteorder="big")
    # more entropy from system timer and sha256 derivation
    while i:
        h = hashlib.sha256(h).digest()
        i -= 1
        if not i and int_from_bytes(h, byteorder="big") > ECDSA_SEC256K1_ORDER:
            i += 1
    return h[:int(strength/8)] if not hex else h[:int(strength/8)].hex() 
Example 12
Project: BioQueue   Author: liyao001   File: install.py    License: Apache License 2.0 6 votes vote down vote up
def get_random_secret_key():
    import random
    import hashlib
    import time
    try:
        random = random.SystemRandom()
        using_sysrandom = True
    except NotImplementedError:
        import warnings
        warnings.warn('A secure pseudo-random number generator is not available '
                      'on your system. Falling back to Mersenne Twister.')
        using_sysrandom = False

    chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$^&*(-_=+)'
    if not using_sysrandom:
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    'BioQueue')).encode('utf-8')
            ).digest())
    return ''.join(random.choice(chars) for i in range(50)) 
Example 13
Project: zulip   Author: zulip   File: video_calls.py    License: Apache License 2.0 6 votes vote down vote up
def get_bigbluebutton_url(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
    # https://docs.bigbluebutton.org/dev/api.html#create for reference on the api calls
    # https://docs.bigbluebutton.org/dev/api.html#usage for reference for checksum
    id = "zulip-" + str(random.randint(100000000000, 999999999999))
    password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
    checksum = hashlib.sha1(("create" + "meetingID=" + id + "&moderatorPW="
                             + password + "&attendeePW=" + password + "a" + settings.BIG_BLUE_BUTTON_SECRET).encode()).hexdigest()
    url = add_query_to_redirect_url("/calls/bigbluebutton/join", urlencode({
        "meeting_id": "\"" + id + "\"",
        "password": "\"" + password + "\"",
        "checksum": "\"" + checksum + "\""
    }))
    return json_success({"url": url})


# We use zulip_login_required here mainly to get access to the user's
# full name from Zulip to prepopulate the user's name in the
# BigBlueButton meeting.  Since the meeting's details are encoded in
# the link the user is clicking, there is no validation tying this
# meeting to the Zulip organization it was created in. 
Example 14
Project: aegea   Author: kislyuk   File: iam.py    License: Apache License 2.0 5 votes vote down vote up
def generate_password(length=16):
    while True:
        password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)]
        password.insert(8, "-")
        if not any(c in string.ascii_uppercase for c in password):
            continue
        if not any(c in string.ascii_lowercase for c in password):
            continue
        if not any(c in string.digits for c in password):
            continue
        return ''.join(password) 
Example 15
Project: ALF   Author: blackberry   File: Radamsa.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        if sys.platform.startswith("linux"):
            self.bin = os.path.join(TOOL_DIR, "radamsa-linux")
            if os.path.isfile(self.bin):
                os.chmod(self.bin, os.stat(self.bin).st_mode | stat.S_IXUSR)
            else:
                raise RuntimeError("Missing file %s" % self.bin)
        elif sys.platform.startswith("win32"):
            self.bin = os.path.join(TOOL_DIR, "radamsa-windows.exe")
            if not os.path.isfile(self.bin):
                raise RuntimeError("Missing file %s" % self.bin)
        else:
            raise RuntimeError("RadamsaFuzzer not supported on this platform")
        self.sys_rnd = random.SystemRandom() 
Example 16
Project: django-template   Author: liip   File: fabfile.py    License: MIT License 5 votes vote down vote up
def generate_secret_key():
    """
    Generate a random secret key, suitable to be used as a SECRET_KEY setting.
    """
    return "".join(
        [
            random.SystemRandom().choice(
                "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
            )
            for i in range(50)
        ]
    ) 
Example 17
Project: django-accounting   Author: dulacp   File: utils.py    License: MIT License 5 votes vote down vote up
def random_token(extra=None, hash_func=hashlib.sha256):
    """
    Extracted from `django-user-accounts`
    """
    if extra is None:
        extra = []
    bits = extra + [str(random.SystemRandom().getrandbits(512))]
    return hash_func("".join(bits)).hexdigest() 
Example 18
Project: loaner   Author: google   File: password.py    License: Apache License 2.0 5 votes vote down vote up
def generate(length):
  """Generates a new password of a given length.

  Args:
    length: int, the length of the password to generate.

  Returns:
    A random password of type string with the given length.

  Raises:
    ValueError: if the length provided is invalid.
  """
  if length < _MIN or length > _MAX:
    raise ValueError(
        'password length must be between {!r} and {!r} characters length '
        'provided was: {!r}'.format(_MIN, _MAX, length))

  logging.debug('Generating a password with length: %r.', length)

  chars = (
      'abcdefghijklmnopqrstuvwxyz'
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      '0123456789'
      '!$%^&*()-_=+@:;~#,.<>? '
  )
  password = ''
  rand = random.SystemRandom()
  while len(password) < length:
    password += rand.choice(chars)
  return password 
Example 19
Project: raspiblitz   Author: rootzoll   File: memo.py    License: MIT License 5 votes vote down vote up
def adjective_noun_pair():
    """
    taken from https://github.com/aaronbassett/Pass-phrase/blob/master/pass_phrase.py

    The MIT License (MIT)
    Copyright (c) 2012 Aaron Bassett, http://aaronbassett.com
    Permission is hereby granted, free of charge, to any person 
    obtaining a copy of this software and associated documentation 
    files (the "Software"), to deal in the Software without restriction, 
    including without limitation the rights to use, copy, modify, 
    merge, publish, distribute, sublicense, and/or sell copies of the 
    Software, and to permit persons to whom the Software is furnished 
    to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be 
    included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
    IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    """

    # random.SystemRandom() should be cryptographically secure
    try:
        rng = random.SystemRandom
    except AttributeError:
        sys.stderr.write("WARNING: System does not support cryptographically "
                         "secure random number generator or you are using Python "
                         "version < 2.4.\n"
                         "Continuing with less-secure generator.\n")
        rng = random.Random

    adjective = rng().choice(adjectives)
    noun = rng().choice(nouns)
    return adjective, noun 
Example 20
Project: gitlab-tools   Author: Salamek   File: crypto.py    License: GNU General Public License v3.0 5 votes vote down vote up
def random_password() -> str:
    """
    Generates random password with fixed len of 64 characters
    :return: 64 len string
    """
    return hashlib.sha256('{}_{}_{}'.format(
        random.randint(0, sys.maxsize),
        round(time.time() * 1000),
        ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20))
    ).encode('UTF-8')).hexdigest() 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def make_rand(rand_source=None, rand_seed=None):
    if rand_source is None:
        if rand_seed is None:
            rand_source = random.SystemRandom()
        else:
            rand_source = random.Random(rand_seed)
    return rand_source 
Example 22
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def MakeRandomKey():
  # Use the system (hardware-based) random number generator if it exists.
  if hasattr(random, 'SystemRandom'):
    randrange = random.SystemRandom().randrange
  else:
 	  randrange = random.randrange
  csrf_key = hashlib.md5('%s%s' % (randrange(0, settings.MAX_HASH_KEY),
                                   settings.SECRET_KEY)
                         ).hexdigest()
  return csrf_key 
Example 23
Project: browserscope   Author: elsigh   File: user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def _get_random_sandboxid():
  # Use the system (hardware-based) random number generator if it exists.
  if hasattr(random, 'SystemRandom'):
    randrange = random.SystemRandom().randrange
  else:
    randrange = random.randrange
  sanboxid_md5 = hashlib.md5('%s' % (randrange(0, _MAX_SANDBOXID)))
  sanboxid = sanboxid_md5.hexdigest()[0:_MAX_SANDBOXID_LEN]
  return sanboxid 
Example 24
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def _make_csrf_key():
  # Use the system (hardware-based) random number generator if it exists.
  if hasattr(random, 'SystemRandom'):
    randrange = random.SystemRandom().randrange
  else:
 	  randrange = random.randrange
  csrf_key = md5_constructor('%s%s' % (randrange(0, _MAX_CSRF_KEY),
                                       SECRET_KEY)
                            ).hexdigest()
  return csrf_key 
Example 25
Project: APIFuzzer   Author: KissPeter   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def secure_randint(minimum, maximum):
    """
    Provides solution for B311 "Standard pseudo-random generators are not suitable for security/cryptographic purposes."
    :param minimum: minimum value
    :type minimum: int
    :param maximum: maximum value
    :type maximum: int
    :return: random integer value between min and maximum
    """
    rand = SystemRandom()
    return rand.randrange(start=minimum, stop=maximum) 
Example 26
Project: DL4MT   Author: thompsonb   File: pyro_utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_random_key():
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10)) 
Example 27
Project: jbox   Author: jpush   File: flask_httpauth.py    License: MIT License 5 votes vote down vote up
def __init__(self, scheme=None, realm=None, use_ha1_pw=False):
        super(HTTPDigestAuth, self).__init__(scheme or 'Digest', realm)
        self.use_ha1_pw = use_ha1_pw
        self.random = SystemRandom()
        try:
            self.random.random()
        except NotImplementedError:  # pragma: no cover
            self.random = Random()

        self.generate_nonce_callback = None
        self.verify_nonce_callback = None
        self.generate_opaque_callback = None
        self.verify_opaque_callback = None

        def _generate_random():
            return md5(str(self.random.random()).encode('utf-8')).hexdigest()

        def default_generate_nonce():
            session["auth_nonce"] = _generate_random()
            return session["auth_nonce"]

        def default_verify_nonce(nonce):
            return nonce == session.get("auth_nonce")

        def default_generate_opaque():
            session["auth_opaque"] = _generate_random()
            return session["auth_opaque"]

        def default_verify_opaque(opaque):
            return opaque == session.get("auth_opaque")

        self.generate_nonce(default_generate_nonce)
        self.generate_opaque(default_generate_opaque)
        self.verify_nonce(default_verify_nonce)
        self.verify_opaque(default_verify_opaque) 
Example 28
Project: Odoo_Samples   Author: Yenthe666   File: button_action_demo.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_record_name(self):
	self.ensure_one()
	#Generates a random name between 9 and 15 characters long and writes it to the record.
	self.write({'name': ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(randint(9,15)))}) 
Example 29
Project: Odoo_Samples   Author: Yenthe666   File: button_action_demo.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_record_password(self):
	self.ensure_one()
	#Generates a random password between 12 and 15 characters long and writes it to the record.
	self.write({
	    'password': ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(randint(12,15)))
	}) 
Example 30
Project: rucio   Author: rucio   File: authentication.py    License: Apache License 2.0 5 votes vote down vote up
def get_ssh_challenge_token(account, appid, ip=None, session=None):
    """
    Prepare a challenge token for subsequent SSH public key authentication.

    The challenge lifetime is fixed to 10 seconds.

    :param account: Account identifier as a string.
    :param appid: The application identifier as a string.
    :param ip: IP address of the client as a string.

    :returns: Challenge token token as a Python struct
              .token string
              .expired_at datetime
    """

    # Make sure the account exists
    if not account_exists(account, session=session):
        return None

    # Cryptographically secure random number.
    # This requires a /dev/urandom like device from the OS
    rng = random.SystemRandom()
    crypto_rand = rng.randint(0, sys.maxsize)

    # give the client 10 seconds max to sign the challenge token
    expiration = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
    expiration_unix = expiration.strftime("%s")

    challenge_token = 'challenge-%(crypto_rand)s-%(account)s-%(expiration_unix)s' % locals()

    new_challenge_token = models.Token(account=account, token=challenge_token, ip=ip,
                                       expired_at=expiration)
    new_challenge_token.save(session=session)
    session.expunge(new_challenge_token)

    return new_challenge_token