Python random.SystemRandom() Examples

The following are code examples for showing how to use random.SystemRandom(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_random.py    GNU Lesser General Public License v3.0 7 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 2
Project: Ciphersaber-2   Author: RJ-Russell   File: rc4.py    MIT License 6 votes vote down vote up
def encrypt(plain_message, key, iv=""):
    """
    :param plain_message: Message sent in from the client
    :param key: value used  for all encryption/decryption
    :param iv: stores first ten 'bytes' of the plain message
    :return: joined list in string format of the encrypted message
    """
    # addes time stamp to message
    plain_message += "\n" + "Sent on: " + get_time() + "\n"
    print "ENCRYPTING..."
    iv_rand = random.SystemRandom()
    # Creates the IV
    while len(iv) < 10:
        iv += chr(int(iv_rand.random()))
    # maps each character to an integer value and sends to be xor'd.
    encrypted_message = rc4(map(ord, plain_message), map(ord, key + iv))

    # joins the list in string format and converts each int to a string representation
    return iv + string.join(map(chr, encrypted_message), "") 
Example 3
Project: picoCTF   Author: picoCTF   File: rekey.py    MIT License 6 votes vote down vote up
def sha512_crypt(password, salt=None, rounds=None):
    """This is used in place of `mkpasswd --sha-512`"""
    if salt is None:
        rand = random.SystemRandom()
        salt = "".join(
            [rand.choice(string.ascii_letters + string.digits) for _ in range(8)]
        )

    prefix = "$6$"
    if rounds is not None:
        rounds = max(1000, min(999999999, rounds or 5000))
        prefix += "rounds={0}$".format(rounds)
    return crypt.crypt(password, prefix + salt)


# known good, default found in vault.yml
# known to fail on windows (but WSL works) 
Example 4
Project: tapedrive   Author: janw   File: settings.py    Apache License 2.0 6 votes vote down vote up
def get_secret_key(PROJECT_DIR):
    SECRET_FILE = os.path.join(PROJECT_DIR, "secret.txt")
    try:
        with open(SECRET_FILE) as sf:
            SECRET_KEY = sf.read().strip()
    except IOError:
        try:
            SECRET_KEY = "".join(
                [
                    random.SystemRandom().choice(
                        "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
                    )
                    for i in range(50)
                ]
            )
            with open(SECRET_FILE, "w") as sf:
                sf.write(SECRET_KEY)
        except IOError:
            Exception(
                "Please create a %s file with random characters \
            to generate your secret key!"
                % SECRET_FILE
            )
    return SECRET_KEY 
Example 5
Project: OctoPrint-Anywhere   Author: kennethjiang   File: config.py    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() 
Example 6
Project: cog   Author: drone115b   File: uid.py    Apache License 2.0 6 votes vote down vote up
def create_uid( target_datetime = None ):
    __CREATE_LOCK.acquire()
    t = None
    try:
        n = target_datetime if target_datetime else datetime.datetime.now()
        time.sleep( ( 2.0 / 1000000.0 ) ) # more than one microsecond - this is more a theoretical safeguard than anything else
        t = n.microsecond + n.second * 1000000 
        t += n.minute * 1000000 * 60 
        t += n.hour * 1000000 * 60 * 60
        t += (n.day-1) * 1000000 * 60 * 60 * 24 
        t += (n.month-1) * 1000000 * 60 * 60 * 24 * 33 
        t += (n.year - EPOCH_YEAR) * 1000000 * 60 * 60 * 24 * 33 * 12
        t <<= __RANDOMBITS
        randombits = random.SystemRandom().randint( 0, (1 << __RANDOMBITS)-1) # for some reason, the range on this function is inclusive.
        t |= randombits
    finally:
        __CREATE_LOCK.release()
    return t 
Example 7
Project: ironpython2   Author: IronLanguages   File: test_random.py    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
Project: paradux   Author: paradux   File: init.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def run(args, settings) :
    """
    Run this command.

    args: parsed command-line arguments
    settings: settings for this paradux instance
    """
    try :
        nbits  = 512
        recoverySecret = random.SystemRandom().randint(0, 1<<nbits)

        paradux.logging.trace( 'recovery secret:', recoverySecret)

        settings.checkCanCreateImage()
        settings.createAndMountImage(recoverySecret)

        settings.populateWithInitialData(args.min_stewards, nbits, recoverySecret)

    finally:
        settings.cleanup()

    return 0 
Example 9
Project: paradux   Author: paradux   File: shamir.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def createGenerator(self, secret, requiredShares):
        """
        Create a generator that knows how to create new shares based on a new
        random polynomial

        :param secret:         the secret to be split
        :param requiredShares: the number of shares required to reconstruct the secret (k)
        :return:               the ShareGenerator from which to obtain the shares
        """
        if secret >= self.prime:
            raise ValueError('Secret too large for the configured number of bits: ' + str(secret) + ' vs ' + str(self.prime) )

        # create random polynomial of rank requiredShares where poly[0] is the secret
        polyK1 = []
        for i in range( 1, requiredShares ):
            polyK1.append(random.SystemRandom().randint(0, self.prime))

        return ShareGenerator(self, polyK1, secret) 
Example 10
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def generate_password(size=10, charset=_52charset):
    """generate random password using given length & charset

    :param size:
        size of password.

    :param charset:
        optional string specified set of characters to draw from.

        the default charset contains all normal alphanumeric characters,
        except for the characters ``1IiLl0OoS5``, which were omitted
        due to their visual similarity.

    :returns: :class:`!str` containing randomly generated password.

    .. note::

        Using the default character set, on a OS with :class:`!SystemRandom` support,
        this function should generate passwords with 5.7 bits of entropy per character.
    """
    return getrandstr(rng, charset, size)

#=============================================================================
# object type / interface tests
#============================================================================= 
Example 11
Project: nablaweb   Author: Nabla-NTNU   File: views.py    MIT License 6 votes vote down vote up
def post(self, request):
        email_form = EmailForm(request.POST)
        if email_form.is_valid():
            emails = email_form.get_emails()
            email_list = emails.splitlines()
            qr_event = email_form.get_qr_event()
            for email in email_list:
                # Generates a random string of uppercase letters and numbers, stolen from stack overflow :))
                randstr = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
                ticket = QrTicket.objects.create(event=qr_event, email = email)
                ticket.ticket_id = str(ticket.id) + randstr
                ticket.save()

                subject = 'din nablabillett' #noe mer spes etterhvert
                message = 'Din billett til ' + str(ticket.event) + ' finner du her:\n'
                link = 'nabla.no/qrTickets/render/' + str(qr_event.id) + '/' + ticket.ticket_id
                message += link
                
                try:
                    send_mail(subject, message, "noreply@nablatickets.no", [email], fail_silently=False)
                except BadHeaderError:
                    return HttpResponse('Invalid header found')
            return HttpResponse("Billetter generert og send på epost!") 
Example 12
Project: factotum   Author: Denubis   File: diceware.py    GNU General Public License v3.0 5 votes vote down vote up
def generatePhrase(numWords):
	phrase = re.compile("[0-9]+\t(.*)")

	path_to_diceware = resource_filename("factotum", "diceware.wordlist.asc")

	with open(path_to_diceware, "r") as diceware:
		password = diceware.readlines()
		password = [m.group(1) for l in password for m in [phrase.search(l)] if m]
		random.SystemRandom().shuffle(password)
		return ' '.join(password[0:numWords]) 
Example 13
Project: slidoc   Author: mitotic   File: sliauth.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gen_random_number(low=2**123, high=2**128):
    # Returns secure random number using system call (default: 38 or 39 decimal digits)
    return random.SystemRandom().randrange(low, high) 
Example 14
Project: django-template   Author: liip   File: fabfile.py    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 15
Project: historia   Author: acrosman   File: system_db.py    GNU General Public License v3.0 5 votes vote down vote up
def str_generator(size=6, chars=string.ascii_letters + string.digits):
        return ''.join(random.SystemRandom().choice(chars) for _ in range(size)) 
Example 16
Project: flasky   Author: RoseOu   File: flask_httpauth.py    MIT License 5 votes vote down vote up
def __init__(self, scheme=None, realm=None, use_ha1_pw=False):
        super(HTTPDigestAuth, self).__init__(scheme, realm)
        self.use_ha1_pw = use_ha1_pw
        self.random = SystemRandom()
        try:
            self.random.random()
        except NotImplementedError:
            self.random = Random()

        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 17
Project: kagi   Author: justinmayer   File: util.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_challenge(challenge_len):
    return "".join(
        [
            random.SystemRandom().choice(string.ascii_letters + string.digits)
            for i in range(challenge_len)
        ]
    ) 
Example 18
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: utils.py    Apache License 2.0 5 votes vote down vote up
def generate_password(length=None, symbolgroups=DEFAULT_PASSWORD_SYMBOLS):
    """Generate a random password from the supplied symbol groups.

    At least one symbol from each group will be included. Unpredictable
    results if length is less than the number of symbol groups.

    Believed to be reasonably secure (with a reasonable password length!)

    """
    if length is None:
        length = CONF.password_length

    r = random.SystemRandom()

    # NOTE(jerdfelt): Some password policies require at least one character
    # from each group of symbols, so start off with one random character
    # from each symbol group
    password = [r.choice(s) for s in symbolgroups]
    # If length < len(symbolgroups), the leading characters will only
    # be from the first length groups. Try our best to not be predictable
    # by shuffling and then truncating.
    r.shuffle(password)
    password = password[:length]
    length -= len(password)

    # then fill with random characters from all symbol groups
    symbols = ''.join(symbolgroups)
    password.extend([r.choice(symbols) for _i in range(length)])

    # finally shuffle to ensure first x characters aren't from a
    # predictable group
    r.shuffle(password)

    return ''.join(password) 
Example 19
Project: ngo-addons-backport   Author: camptocamp   File: mail.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_tracking_message_id(res_id):
    """Returns a string that can be used in the Message-ID RFC822 header field

       Used to track the replies related to a given object thanks to the "In-Reply-To"
       or "References" fields that Mail User Agents will set.
    """
    try:
        rnd = random.SystemRandom().random()
    except NotImplementedError:
        rnd = random.random()
    rndstr = ("%.15f" % rnd)[2:]
    return "<%.15f.%s-openerp-%s@%s>" % (time.time(), rndstr, res_id, socket.gethostname()) 
Example 20
Project: SayluaLegacy   Author: saylua   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def random_token(length=32):
    choices = string.ascii_letters + string.digits
    return ''.join([random.SystemRandom().choice(choices) for _ in range(length)]) 
Example 21
Project: SayluaLegacy   Author: saylua   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def random_token(length=32):
    choices = string.ascii_letters + string.digits
    return ''.join([random.SystemRandom().choice(choices) for _ in range(length)]) 
Example 22
Project: picourl   Author: PradheepShrinivasan   File: urlshortener.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generateShortUrl(self, length=6):
        """ generates an shorturl needed from so
            http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python/23728630#23728630"""
        return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) 
Example 23
Project: zip-shotgun   Author: jpiechowka   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def get_random_shell_name(name_length: int) -> str:
    # Generate random name using ASCII letters and digits
    random_shell_name = ''.join(SystemRandom().choices(string.ascii_letters + string.digits, k=name_length))
    logging.warning(f'Shell name was not provided. Generated random shell name: {random_shell_name}')
    return random_shell_name 
Example 24
Project: inmanta   Author: inmanta   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def generate_password(context: Context, pw_id: "string", length: "number" = 20) -> "string":
    """
    Generate a new random password and store it in the data directory of the
    project. On next invocations the stored password will be used.

    :param pw_id: The id of the password to identify it.
    :param length: The length of the password, default length is 20
    """
    data_dir = context.get_data_dir()
    pw_file = os.path.join(data_dir, "passwordfile.txt")

    if "=" in pw_id:
        raise Exception("The password id cannot contain =")

    records = get_passwords(pw_file)

    if pw_id in records:
        return records[pw_id]

    rnd = random.SystemRandom()
    pw = ""
    while len(pw) < length:
        x = chr(rnd.randint(33, 126))
        if re.match("[A-Za-z0-9]", x) is not None:
            pw += x

    # store the new value
    records[pw_id] = pw
    save_passwords(pw_file, records)

    return pw 
Example 25
Project: python3-qoqa   Author: ebsuku   File: qoqa.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_key():
    """
    Generate Secret key for django
    """
    key = ''.join([random.SystemRandom().choice(string.ascii_letters +
                                                string.digits +
                                                string.punctuation)
                   for _ in range(50)])
    return key 
Example 26
Project: ks-python-api   Author: Kriegspiel   File: auth_token.py    MIT License 5 votes vote down vote up
def random_string(n=100):
    return ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits)
        for _ in range(n)
    ) 
Example 27
Project: Garnet   Author: OneTesseractInMultiverse   File: entropy.py    MIT License 5 votes vote down vote up
def gen_salt(length):
    return ''.join(random.SystemRandom()
                   .choice(string.ascii_uppercase + string.digits) for _ in range(length))


# --------------------------------------------------------------------------
# METHOD __COMPUTE_HASH
# --------------------------------------------------------------------------
# Computes the SHA256 hash of the given password and encodes the result into
# a hexadecimal string. 
Example 28
Project: loaner   Author: google   File: password.py    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 29
Project: raspiblitz   Author: rootzoll   File: memo.py    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 30
Project: gitlab-tools   Author: Salamek   File: crypto.py    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 31
Project: surreptitious   Author: neuroFuzz   File: get_nf_toolkit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_rand_crap(length=0):
    ''' '''
    if length:
        chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
        return ''.join(random.SystemRandom().choice(chars) for _ in range(length)) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: test_random.py    GNU General Public License v3.0 5 votes vote down vote up
def test_randbelow_overridden_random(self, random_mock):
        # Random._randbelow() can only use random() when the built-in one
        # has been overridden but no new getrandbits() method was supplied.
        random_mock.side_effect = random.SystemRandom().random
        maxsize = 1<<random.BPF
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", UserWarning)
            # Population range too large (n >= maxsize)
            self.gen._randbelow(maxsize+1, maxsize = maxsize)
        self.gen._randbelow(5640, maxsize = maxsize)
        # issue 33203: test that _randbelow raises ValueError on
        # n == 0 also in its getrandbits-independent branch.
        with self.assertRaises(ValueError):
            self.gen._randbelow(0, maxsize=maxsize)
        # This might be going too far to test a single line, but because of our
        # noble aim of achieving 100% test coverage we need to write a case in
        # which the following line in Random._randbelow() gets executed:
        #
        # rem = maxsize % n
        # limit = (maxsize - rem) / maxsize
        # r = random()
        # while r >= limit:
        #     r = random() # <== *This line* <==<
        #
        # Therefore, to guarantee that the while loop is executed at least
        # once, we need to mock random() so that it returns a number greater
        # than 'limit' the first time it gets called.

        n = 42
        epsilon = 0.01
        limit = (maxsize - (maxsize % n)) / maxsize
        random_mock.side_effect = [limit + epsilon, limit - epsilon]
        self.gen._randbelow(n, maxsize = maxsize) 
Example 33
Project: randomnames   Author: lavr   File: generate.py    MIT License 5 votes vote down vote up
def get_random_name():
    r = random.SystemRandom()
    while 1:
        name = '%s_%s' % (r.choice(left), r.choice(right))
        if name == "boring_wozniak": # Steve Wozniak is not boring
            continue
        return name 
Example 34
Project: mist.api   Author: mistio   File: models.py    Apache License 2.0 5 votes vote down vote up
def get_secure_rand_token(num_of_chars=64):
    token = ''.join(random.SystemRandom().choice(string.hexdigits[:16])
                    for _ in range(num_of_chars))
    return token 
Example 35
Project: LifelongVAE   Author: jramapuram   File: utils.py    MIT License 5 votes vote down vote up
def random_str(length):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) 
Example 36
Project: kolla-kubernetes-personal   Author: rthallisey   File: generate_passwords.py    Apache License 2.0 5 votes vote down vote up
def main():
    # These keys should be random uuids
    uuid_keys = ['ceph_cluster_fsid', 'rbd_secret_uuid']

    # If these keys are None, leave them as None
    blank_keys = ['docker_registry_password']

    # length of password
    length = 40

    with open('/etc/kolla/passwords.yml', 'r') as f:
        passwords = yaml.load(f.read())

    for k, v in passwords.items():
        if v is None:
            if k in blank_keys and v is None:
                continue
            if k in uuid_keys:
                passwords[k] = str(uuid.uuid4())
            else:
                passwords[k] = ''.join([
                    random.SystemRandom().choice(
                        string.ascii_letters + string.digits)
                    for n in range(length)
                ])

    with open('/etc/kolla/passwords.yml', 'w') as f:
        f.write(yaml.dump(passwords, default_flow_style=False)) 
Example 37
Project: kolla-kubernetes-personal   Author: rthallisey   File: genpwd.py    Apache License 2.0 5 votes vote down vote up
def main():
    # These keys should be random uuids
    uuid_keys = ['ceph_cluster_fsid', 'rbd_secret_uuid']

    # If these keys are None, leave them as None
    blank_keys = ['docker_registry_password']

    # length of password
    length = 40

    with open('/etc/kolla/passwords.yml', 'r') as f:
        passwords = yaml.load(f.read())

    for k, v in passwords.items():
        if v is None:
            if k in blank_keys and v is None:
                continue
            if k in uuid_keys:
                passwords[k] = str(uuid.uuid4())
            else:
                passwords[k] = ''.join([
                    random.SystemRandom().choice(
                        string.ascii_letters + string.digits)
                    for n in range(length)
                ])

    with open('/etc/kolla/passwords.yml', 'w') as f:
        f.write(yaml.dump(passwords, default_flow_style=False)) 
Example 38
Project: detour   Author: de-tour   File: meta.py    GNU General Public License v3.0 5 votes vote down vote up
def balance(concurrent=3):
        instances = [
            SearxMe, SearxDk, SearxCh, SearxAt, SearxInfo, SearxPotato,
            SearxAbenthung, SearxGotrust, SearxPrvcy, SearxGoodOne, SearxNulltime,
            SucheFTP, Rubbeldiekatz, Datensturm, OpenGo,
        ]

        targets = []
        for _ in range(concurrent):
            index = SystemRandom().randint(0, len(instances) - 1)
            targets.append(instances.pop(index))

        return targets 
Example 39
Project: pydruuid   Author: Famoco   File: druuid.py    MIT License 5 votes vote down vote up
def _gen(self):
        ms = int(round(time.time() * 1e3))
        rand = int(round(random.SystemRandom().random() * 1e16))
        return ms << SHIFT | rand % (2 ** SHIFT) 
Example 40
Project: nucypher   Author: nucypher   File: test_deploy.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_insecure_secret() -> str:
    insecure_secret = ''.join(SystemRandom().choice(ascii_uppercase + digits) for _ in range(16))
    formatted_secret = insecure_secret + '\n'
    return formatted_secret


# TODO: Use temp module 
Example 41
Project: filter-bubble-study   Author: duckduckgo   File: measure_difference.py    Apache License 2.0 5 votes vote down vote up
def get_random_participant(participant_results, participant_id):
    secure_random = random.SystemRandom()
    while True:
        id = secure_random.choice(participant_results.keys())
        if id != participant_id:
            break
    return id 
Example 42
Project: DL4MT   Author: thompsonb   File: pyro_utils.py    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 43
Project: lambdabot   Author: timokoola   File: common.py    GNU General Public License v2.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 = random.SystemRandom()
    return ''.join(rand.choice(chars) for x in range(length)) 
Example 44
Project: zosia16-site   Author: ksiuwr   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def random_string(length=10):
    return "".join(random.SystemRandom().choice(
        string.ascii_uppercase + string.digits) for _ in range(length)) 
Example 45
Project: zosia16-site   Author: ksiuwr   File: common.py    GNU General Public License v3.0 5 votes vote down vote up
def random_string(length=10):
    return ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) 
Example 46
Project: jbox   Author: jpush   File: flask_httpauth.py    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 47
Project: dcos-ethereum   Author: iss-lab   File: publish_aws.py    MIT License 5 votes vote down vote up
def s3_urls_from_env(package_name):
    s3_bucket = os.environ.get("S3_BUCKET") or "infinity-artifacts"
    logger.info("Using artifact bucket: {}".format(s3_bucket))

    s3_dir_path = os.environ.get("S3_DIR_PATH") or "autodelete7d"
    s3_dir_name = os.environ.get("S3_DIR_NAME")
    if not s3_dir_name:
        s3_dir_name = "{}-{}".format(
            time.strftime("%Y%m%d-%H%M%S"),
            "".join(
                [
                    random.SystemRandom().choice(string.ascii_letters + string.digits)
                    for i in range(16)
                ]
            ),
        )

    # sample s3_directory: 'infinity-artifacts/autodelete7d/kafka/20160815-134747-S6vxd0gRQBw43NNy'
    s3_directory_url = os.environ.get(
        "S3_URL", "s3://{}/{}/{}/{}".format(s3_bucket, s3_dir_path, package_name, s3_dir_name)
    )

    http_directory_url = os.environ.get(
        "ARTIFACT_DIR",
        "https://{}.s3.amazonaws.com/{}/{}/{}".format(
            s3_bucket, s3_dir_path, package_name, s3_dir_name
        ),
    )

    return s3_directory_url, http_directory_url 
Example 48
Project: Odoo_Samples   Author: Yenthe666   File: button_action_demo.py    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 49
Project: Odoo_Samples   Author: Yenthe666   File: button_action_demo.py    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 50
Project: fabsetup   Author: theno   File: selfoss.py    MIT License 5 votes vote down vote up
def setup_selfoss_user(username, sitename, site_dir):
    if not exists(flo('{site_dir}/selfoss/config.ini')):
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
        salt = ''.join(random.SystemRandom().choice(chars) for _ in range(150))
        install_file_legacy('~/sites/SITENAME/selfoss/config.ini',
                     SITENAME=sitename, salt=salt)

    run('sudo service nginx reload')
    run('sudo service php5-fpm restart')

    selfoss_username(username, sitename)
    selfoss_password(sitename) 
Example 51
Project: GTDBNCBI   Author: Ecogenomics   File: Tools.py    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 52
Project: django-uwsgi-nginx   Author: nicodv   File: django_secret_keygen.py    MIT License 5 votes vote down vote up
def main():
    return ''.join([random.SystemRandom().choice(ALLOWED_CHARS) for _ in range(50)]) 
Example 53
Project: rucio   Author: rucio   File: authentication.py    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 
Example 54
Project: pylips   Author: eslavnov   File: pylips.py    MIT License 5 votes vote down vote up
def createDeviceId(self):
        return "".join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(16))

    # creates signature 
Example 55
Project: nova   Author: ZhanHan   File: utils.py    Apache License 2.0 5 votes vote down vote up
def generate_password(length=None, symbolgroups=DEFAULT_PASSWORD_SYMBOLS):
    """Generate a random password from the supplied symbol groups.

    At least one symbol from each group will be included. Unpredictable
    results if length is less than the number of symbol groups.

    Believed to be reasonably secure (with a reasonable password length!)

    """
    if length is None:
        length = CONF.password_length

    r = random.SystemRandom()

    # NOTE(jerdfelt): Some password policies require at least one character
    # from each group of symbols, so start off with one random character
    # from each symbol group
    password = [r.choice(s) for s in symbolgroups]
    # If length < len(symbolgroups), the leading characters will only
    # be from the first length groups. Try our best to not be predictable
    # by shuffling and then truncating.
    r.shuffle(password)
    password = password[:length]
    length -= len(password)

    # then fill with random characters from all symbol groups
    symbols = ''.join(symbolgroups)
    password.extend([r.choice(symbols) for _i in range(length)])

    # finally shuffle to ensure first x characters aren't from a
    # predictable group
    r.shuffle(password)

    return ''.join(password) 
Example 56
Project: labchain   Author: ChaAC-FAU   File: crypto.py    GNU General Public License v3.0 5 votes vote down vote up
def get_random_int(length: int) -> int:
    rnd = random.SystemRandom()
    return rnd.randint(0, (2 ** length) - 1) 
Example 57
Project: PokemonGo-Bot   Author: PokemonGoF   File: api_wrapper.py    MIT License 5 votes vote down vote up
def gen_device_id(self):
        if self.config is None or self.config.username is None:
            ApiWrapper.DEVICE_ID = "3d65919ca1c2fc3a8e2bd7cc3f974c34"
            return
        file_salt = None
        did_path = os.path.join(_base_dir, 'data', 'deviceid-%s.txt' % self.config.username)
        if os.path.exists(did_path):
            file_salt = open(did_path, 'r').read()
        if self.config is not None:
            key_string = self.config.username
            if file_salt is not None:
                # Config and file are set, so use those.
                ApiWrapper.DEVICE_ID = hashlib.md5(key_string + file_salt).hexdigest()[:32]
            else:
                # Config is set, but file isn't, so make it.
                rand_float = random.SystemRandom().random()
                salt = base64.b64encode((struct.pack('!d', rand_float)))
                ApiWrapper.DEVICE_ID = hashlib.md5(key_string + salt).hexdigest()[:32]
                with open(did_path, "w") as text_file:
                    text_file.write("{0}".format(salt))
        else:
            if file_salt is not None:
                # No config, but there's a file, use it.
                ApiWrapper.DEVICE_ID = hashlib.md5(file_salt).hexdigest()[:32]
            else:
                # No config or file, so make up a reasonable default.
                ApiWrapper.DEVICE_ID = "3d65919ca1c2fc3a8e2bd7cc3f974c34" 
Example 58
Project: PGPgram   Author: tallero   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def random_id(N):
    """ Returns a random alphanumeric (ASCII) string of given length
    
    Args:
        N (int):
       
    Returns:
        (str) random alphanumeric string 
    """
    return ''.join(random().choice(string.ascii_letters + string.digits) for _ in range(N)) 
Example 59
Project: tapedrive   Author: janw   File: 0003_create_initial_superuser.py    Apache License 2.0 5 votes vote down vote up
def create_superuser(apps, schema_editor):
    User = get_user_model()
    username = os.getenv('TAPEDRIVE_ADMIN_USER', 'admin')
    random_password = ''.join([random.SystemRandom().choice(
        string.ascii_uppercase + string.ascii_lowercase + string.digits)
        for i in range(10)])
    print('Creating initial user:', username, '// pass:', random_password)
    User.objects.create_superuser(username, DUMMY_EMAIL, random_password) 
Example 60
Project: PrivacyScore   Author: PrivacyScore   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_random_token() -> str:
    """Generate a random token."""
    return''.join(random.SystemRandom().choice(
        string.ascii_uppercase + string.ascii_lowercase + string.digits)
                  for _ in range(50)) 
Example 61
Project: sawtooth-core   Author: hyperledger   File: block_tree_manager.py    Apache License 2.0 5 votes vote down vote up
def _generate_id(length=16):
    return ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits)
        for _ in range(length)) 
Example 62
Project: analysis-py-utils   Author: verilylifesciences   File: bq_test_case.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls, use_mocks=False, alternate_bq_client_class=None):
        """Sets up BQ client and creates dataset and tables for testing.

        Args:
            use_mocks: Whether to use a mock implementation of the client.
            alternate_bq_client_class:  An alternate class for the real bq.Client class to use
                instead of Google's bigquery.Client.  The bq.Client class uses an internal
                instance to communicate with BigQuery; this optional parameter allows the caller
                to provide an alternate implementation of the Google BigQuery API to be used.
        """
        force_use_real_bq = bool(cls.FORCE_USE_REAL_BQ)
        if force_use_real_bq:
            log = logging.getLogger("BQTestCase")
            log.warning('Forcing test to run in real BigQuery.')

        cls.use_mocks = False if force_use_real_bq else use_mocks
        cls.default_test_dataset_id = (datetime.datetime.utcnow().strftime("test_%Y_%m_%d_%H_%M_") +
                                       str(random.SystemRandom().randint(1000, 9999)))
        if cls.use_mocks:
            cls.TEST_PROJECT = 'mock_bq_project'
            cls.client = mock_bq.Client(cls.TEST_PROJECT, cls.default_test_dataset_id)
        else:
            if cls.TEST_PROJECT is None:
              raise ValueError("Environment variable 'TEST_PROJECT' is not set. "
                               "Set its value to be the project id in which you "
                               "wish to run test queries.")
            cls.client = real_bq.Client(cls.TEST_PROJECT, cls.default_test_dataset_id,
                                        alternate_bq_client_class=alternate_bq_client_class)
        # Make the tables in the test datasets expire after an hour.
        cls.client.create_dataset_by_name(cls.default_test_dataset_id,
                                          expiration_hours=EXPIRATION_HOURS)
        cls.create_mock_tables()

        # Get the tables present in the class before anything else runs.
        cls.tables_created_in_constructor.extend(cls.client.tables(cls.default_test_dataset_id)) 
Example 63
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def gen_word(count):
    # Bug, shouldn't re-initialize RNG everytime we need it
    r = random.SystemRandom()
    word = ''.join(r.choice(ALPHABET) for x in range(count))
    return word.capitalize() 
Example 64
Project: Hibernate   Author: asurion   File: randomGen.py    Apache License 2.0 5 votes vote down vote up
def generateRandomString(size):
  chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

  cryptogen = SystemRandom()
  randomNumbers = [cryptogen.randrange(len(chars)) for i in range(size)]

  randomChars = [chars[i] for i in randomNumbers]
  randomStr = ''.join(randomChars)

  return randomStr 
Example 65
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 66
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 67
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 68
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 69
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 70
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 71
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 72
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 73
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 74
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 75
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 76
Project: donut   Author: ASCIT   File: misc_utils.py    MIT License 5 votes vote down vote up
def generate_random_string(length, chars=None):
    """
  Generates a random string. Chars should be a string or list with the
  characters to choose from. If chars is not provided, then we default to all
  uppercase and lowercase letters plus digits.
  """
    # Sanity check on inputs.
    if not length >= 1:
        raise ValueError
    # Default character set.
    if chars is None:
        chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for i in range(length)) 
Example 77
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def genseed(value=None):
    """generate prng seed value from system resources"""
    from hashlib import sha512
    if hasattr(value, "getstate") and hasattr(value, "getrandbits"):
        # caller passed in RNG as seed value
        try:
            value = value.getstate()
        except NotImplementedError:
            # this method throws error for e.g. SystemRandom instances,
            # so fall back to extracting 4k of state
            value = value.getrandbits(1 << 15)
    text = u("%s %s %s %.15f %.15f %s") % (
        # if caller specified a seed value, mix it in
        value,

        # add current process id
        # NOTE: not available in some environments, e.g. GAE
        os.getpid() if hasattr(os, "getpid") else None,

        # id of a freshly created object.
        # (at least 1 byte of which should be hard to predict)
        id(object()),

        # the current time, to whatever precision os uses
        time.time(),
        tick(),

        # if urandom available, might as well mix some bytes in.
        os.urandom(32).decode("latin-1") if has_urandom else 0,
        )
    # hash it all up and return it as int/long
    return int(sha512(text.encode("utf-8")).hexdigest(), 16) 
Example 78
Project: avocado-vt   Author: avocado-framework   File: utils_net.py    GNU General Public License v2.0 5 votes vote down vote up
def generate_mac_address_simple():
    r = random.SystemRandom()
    mac = "9a:%02x:%02x:%02x:%02x:%02x" % (r.randint(0x00, 0xff),
                                           r.randint(0x00, 0xff),
                                           r.randint(0x00, 0xff),
                                           r.randint(0x00, 0xff),
                                           r.randint(0x00, 0xff))
    return mac 
Example 79
Project: nucypher   Author: nucypher   File: test_deployer.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def test_rapid_deployment(token_economics, test_registry, tmpdir):
    compiler = SolidityCompiler()
    allocation_registry = InMemoryAllocationRegistry()

    blockchain = _TesterBlockchain(eth_airdrop=False,
                                   test_accounts=4,
                                   compiler=compiler)

    # TODO: #1092 - TransactingPower
    blockchain.transacting_power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,
                                                    account=blockchain.etherbase_account)
    blockchain.transacting_power.activate()
    deployer_address = blockchain.etherbase_account

    deployer = ContractAdministrator(deployer_address=deployer_address,
                                     registry=test_registry)

    secrets = dict()
    for deployer_class in deployer.upgradeable_deployer_classes:
        secrets[deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD

    deployer.deploy_network_contracts(secrets=secrets, emitter=StdoutEmitter())

    all_yall = blockchain.unassigned_accounts

    # Start with some hard-coded cases...
    allocation_data = [{'beneficiary_address': all_yall[1],
                        'amount': token_economics.maximum_allowed_locked,
                        'duration_seconds': ONE_YEAR_IN_SECONDS},

                       {'beneficiary_address': all_yall[2],
                        'amount': token_economics.minimum_allowed_locked,
                        'duration_seconds': ONE_YEAR_IN_SECONDS*2},

                       {'beneficiary_address': all_yall[3],
                        'amount': token_economics.minimum_allowed_locked*100,
                        'duration_seconds': ONE_YEAR_IN_SECONDS*3}
                       ]

    # Pile on the rest
    for _ in range(NUMBER_OF_ALLOCATIONS_IN_TESTS - len(allocation_data)):
        random_password = ''.join(random.SystemRandom().choice(string.ascii_uppercase+string.digits) for _ in range(16))
        acct = w3.eth.account.create(random_password)
        beneficiary_address = acct.address
        amount = random.randint(token_economics.minimum_allowed_locked, token_economics.maximum_allowed_locked)
        duration = random.randint(token_economics.minimum_locked_periods*ONE_YEAR_IN_SECONDS,
                                  (token_economics.maximum_rewarded_periods*ONE_YEAR_IN_SECONDS)*3)
        random_allocation = {'beneficiary_address': beneficiary_address, 'amount': amount, 'duration_seconds': duration}
        allocation_data.append(random_allocation)

    deployer.deploy_beneficiary_contracts(allocations=allocation_data,
                                          allocation_registry=allocation_registry,
                                          output_dir=tmpdir,
                                          interactive=False) 
Example 80
Project: a4kScrapers   Author: a4k-openproject   File: __init__.py    MIT License 4 votes vote down vote up
def loadUserAgent(self, *args, **kwargs):
        self.browser = kwargs.pop('browser', None)

        if isinstance(self.browser, dict):
            self.custom = self.browser.get('custom', None)
            self.desktop = self.browser.get('desktop', True)
            self.mobile = self.browser.get('mobile', True)
            self.browser = self.browser.get('browser', None)
        else:
            self.custom = kwargs.pop('custom', None)
            self.desktop = kwargs.pop('desktop', True)
            self.mobile = kwargs.pop('mobile', True)

        if not self.desktop and not self.mobile:
            sys.tracebacklimit = 0
            raise RuntimeError("Sorry you can't have mobile and desktop disabled at the same time.")

        user_agents = json.load(
            open(os.path.join(os.path.dirname(__file__), 'browsers.json'), 'r'),
            object_pairs_hook=OrderedDict
        )

        if self.custom:
            if not self.tryMatchCustom(user_agents):
                self.cipherSuite = [
                    ssl._DEFAULT_CIPHERS,
                    '!ECDHE+SHA',
                    '!AES128-SHA'
                ]
                self.headers = OrderedDict([
                    ('User-Agent', self.custom),
                    ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'),
                    ('Accept-Language', 'en-US,en;q=0.9'),
                    ('Accept-Encoding', 'gzip, deflate, br')
                ])
        else:
            if self.browser and not user_agents.get(self.browser):
                sys.tracebacklimit = 0
                raise RuntimeError('Sorry "{}" browser User-Agent was not found.'.format(self.browser))

            if not self.browser:
                self.browser = random.SystemRandom().choice(list(user_agents))

            self.cipherSuite = user_agents.get(self.browser).get('cipherSuite', [])

            filteredAgents = self.filterAgents(user_agents.get(self.browser).get('releases'))

            user_agent_version = random.SystemRandom().choice(list(filteredAgents))

            self.loadHeaders(user_agents, user_agent_version)

            self.headers['User-Agent'] = random.SystemRandom().choice(filteredAgents[user_agent_version])

        if not kwargs.get('allow_brotli', False) and 'br' in self.headers['Accept-Encoding']:
            self.headers['Accept-Encoding'] = ','.join([
                encoding for encoding in self.headers['Accept-Encoding'].split(',') if encoding.strip() != 'br'
            ]).strip()