Python random.SystemRandom() Examples

The following are 30 code examples of random.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 random , or try the search function .
Example #1
Source File: config.py    From OctoPrint-Anywhere with MIT License 7 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
Source File: fuzzer.py    From Yuki-Chan-The-Auto-Pentest with 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 #3
Source File: install.py    From BioQueue with 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 #4
Source File: video_calls.py    From zulip with 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 #5
Source File: shamir.py    From pybtc with 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 #6
Source File: bip39_mnemonic.py    From pybtc with 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 #7
Source File: test_random.py    From ironpython2 with 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 #8
Source File: test_random.py    From oss-ftp with 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
Source File: test_random.py    From BinderFilter with 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
Source File: create.py    From daf-recipes with 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 #11
Source File: fuzzer.py    From Yuki-Chan-The-Auto-Pentest with 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 #12
Source File: options.py    From clusterfuzz with 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 #13
Source File: builtin.py    From clusterfuzz with 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 #14
Source File: utils.py    From is-service-up with Apache License 2.0 5 votes vote down vote up
def random_string(n=10):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n)) 
Example #15
Source File: secret.py    From notto with MIT License 5 votes vote down vote up
def generate():
    """
    Generates the key.
    """
    uni = string.ascii_letters + string.digits + string.punctuation
    key = ''.join([random.SystemRandom().choice(uni) for i in range(random.randint(45, 50))])
    return key 
Example #16
Source File: anchors.py    From COCO-Assistant with MIT License 5 votes vote down vote up
def run_kmeans(ann_dims, anchor_num):
    ann_num = ann_dims.shape[0]
    prev_assignments = np.ones(ann_num)*(-1)
    iteration = 0
    old_distances = np.zeros((ann_num, anchor_num))

    r = random.SystemRandom()
    indices = [r.randrange(ann_dims.shape[0]) for i in range(anchor_num)]
    centroids = ann_dims[indices]
    anchor_dim = ann_dims.shape[1]

    while True:
        distances = []
        iteration += 1
        for i in range(ann_num):
            d = 1 - iou(ann_dims[i], centroids)
            distances.append(d)
        distances = np.array(distances) # distances.shape = (ann_num, anchor_num)

        print("iteration {}: dists = {}".format(iteration, np.sum(np.abs(old_distances-distances))))

        #assign samples to centroids
        assignments = np.argmin(distances, axis=1)

        if (assignments == prev_assignments).all():
            return centroids

        #calculate new centroids
        centroid_sums = np.zeros((anchor_num, anchor_dim), np.float)
        for i in range(ann_num):
            centroid_sums[assignments[i]] += ann_dims[i]
        for j in range(anchor_num):
            centroids[j] = centroid_sums[j]/(np.sum(assignments == j) + 1e-6)

        prev_assignments = assignments.copy()
        old_distances = distances.copy() 
Example #17
Source File: tokens.py    From django-rest-passwordreset with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_token(self, *args, **kwargs):
        r = random.SystemRandom()

        # generate a random number between min_number and max_number
        return str(r.randint(self.min_number, self.max_number)) 
Example #18
Source File: test_ssl_profile.py    From f5-openstack-agent with Apache License 2.0 5 votes vote down vote up
def random_name(prefix, N):
    # create a name with random characters and digits
    return prefix + ''.join(
        random.SystemRandom().choice(
            string.ascii_uppercase + string.digits) for _ in range(N)) 
Example #19
Source File: random_numbers.py    From nufhe with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.rng = random.SystemRandom() 
Example #20
Source File: utils.py    From stan.py with Apache License 2.0 5 votes vote down vote up
def generate_client_id():
    return "%x" % random.SystemRandom().getrandbits(0x58) 
Example #21
Source File: client.py    From stan.py with Apache License 2.0 5 votes vote down vote up
def new_guid():
    return "%x" % random.SystemRandom().getrandbits(0x58) 
Example #22
Source File: zip.py    From mac-a-mal-cuckoo with MIT License 5 votes vote down vote up
def _random_extension(length=5):
    return '.' + ''.join(SystemRandom().choice(ascii_letters) for _ in range(length)) 
Example #23
Source File: utils.py    From zatt with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_random_string(lenght=12, allowed_chars=None):
    random_gen = random.SystemRandom()
    if allowed_chars is None:
        allowed_chars = string.ascii_letters + string.digits
    return ''.join([random_gen.choice(allowed_chars) for _ in range(lenght)]) 
Example #24
Source File: config.py    From Zabbix-Network-Weathermap with GNU General Public License v3.0 5 votes vote down vote up
def random_label():
        return ''.join(random.SystemRandom().choice('abcdefgijklmnoprstuvwxyz1234567890') for _ in range(8)) 
Example #25
Source File: test_i_thread_safety.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def random_pause_time(max_seconds=3):
    """Generates a random pause time between 0.0 and 10.0, limited by max_seconds.

    :param int max_seconds: Maximum pause time (default: 3)
    :rtype: float
    """
    return SystemRandom().random() * 10 % max_seconds 
Example #26
Source File: service.py    From designate with Apache License 2.0 5 votes vote down vote up
def _transfer_key_generator(self, size=8):
        chars = string.ascii_uppercase + string.digits
        sysrand = SystemRandom()
        return ''.join(sysrand.choice(chars) for _ in range(size)) 
Example #27
Source File: tools.py    From GTDBTk with GNU General Public License v3.0 5 votes vote down vote up
def generateTempTableName():
    rng = random.SystemRandom()
    suffix = ''
    for _ in range(0, 10):
        suffix += rng.choice(
            'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    return "TEMP" + suffix + str(int(time.time())) 
Example #28
Source File: models.py    From civet with Apache License 2.0 5 votes vote down vote up
def generate_build_key():
    return random.SystemRandom().randint(0, 2000000000) 
Example #29
Source File: zip.py    From cuckoo-osx-analyzer with MIT License 5 votes vote down vote up
def _random_extension(length=5):
    return '.' + ''.join(SystemRandom().choice(ascii_letters) for _ in range(length)) 
Example #30
Source File: megalal.py    From Crypton with MIT License 5 votes vote down vote up
def enc(m):
    M = int(binascii.hexlify(m), 16)
    assert len(bin(M)) < len(bin(p)), 'm too long'

    y = random.SystemRandom().randint(0, p-1)
    c1 = pow(g, y, p)
    c2 = (M * pow(h, y, p) ) % p 

    return c1, c2