Python random.SystemRandom() Examples

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

Example 1
Project: lightstep-tracer-python   Author: lightstep   File: main.py    (MIT License) View Source Project 7 votes vote down vote up
def add_spans():
    """Calls the opentracing API, doesn't use any LightStep-specific code.
    """
    with opentracing.tracer.start_span(operation_name='trivial/initial_request') as parent_span:
        parent_span.set_tag('url', 'localhost')
        parent_span.log_event('All good here!', payload={'N': 42, 'pi': 3.14, 'abc': 'xyz'})
        parent_span.set_tag('span_type', 'parent')
        parent_span.set_baggage_item('checked', 'baggage')

        rng = random.SystemRandom()
        for i in range(50):
            time.sleep(rng.random() * 0.2)
            sys.stdout.write('.')
            sys.stdout.flush()

            # This is how you would represent starting work locally.
            with opentracing.start_child_span(parent_span, operation_name='trivial/child_request') as child_span:
                child_span.log_event('Uh Oh!', payload={'error': True})
                child_span.set_tag('span_type', 'child')

                # Play with the propagation APIs... this is not IPC and thus not
                # where they're intended to be used.
                text_carrier = {}
                opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier)

                span_context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, text_carrier)
                with opentracing.tracer.start_span(
                    'nontrivial/remote_span',
                    child_of=span_context) as remote_span:
                        remote_span.log_event('Remote!')
                        remote_span.set_tag('span_type', 'remote')
                        time.sleep(rng.random() * 0.1)

                opentracing.tracer.flush() 
Example 2
Project: dati-ckan-docker   Author: italia   File: create.py    (license) View Source Project 7 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 3
Project: PimuxBot   Author: Finn10111   File: forgot_password.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def index():
    if request.args.get('code'):
        unlock_code = request.args.get('code')
        # unlock, new password
        re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none()
        if re:
            jid = re.jid
            re.password_code = None
            s.merge(re)
            s.commit()
            # set new password and send email
            email_address = re.email
            password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10))
            p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
            args = bytes("%s\n%s\n" % (password, password), encoding='utf8')
            p.communicate(args)
            sendMail(email_address, 'new password', password)
            content = render_template('success.html', message='password was sent')
        else:
            content = render_template('error.html', message='link invalid')
    else:
        content = render_template('index.html')
    return content 
Example 4
Project: privcount   Author: privcount   File: test_counter.py    (license) View Source Project 6 votes vote down vote up
def try_counters(counters, modulus, N, X=None, multi_bin=True):
    '''
    Validate that a counter run with counters, modulus, N, X, and multi_bin works,
    and produces consistent results
    Also try a randomly selected number modulus_random between modulus_min and modulus,
    and a randomly selected number N_random between 0 and min(q_random, N)
    and a randomly selected number X_random between 0 and min(q_random, X)
    If X is None, use the 2-argument form of increment, otherwise, use the
    3-argument form
    '''
    # randrange is not uniformly distributed in python versions < 3.2
    modulus_random = SystemRandom().randrange(modulus_min, modulus)
    N_random = SystemRandom().randrange(0, min(modulus_random, N))
    X_random = None
    if X is not None:
        X_random = SystemRandom().randrange(0, min(modulus_random, X))
    run_counters(counters, modulus_random, N_random, X_random, multi_bin)
    run_counters(counters, modulus, N, X, multi_bin)

# Check the counter table is valid, and perform internal checks 
Example 5
Project: toy_dht   Author: MuxZeroNet   File: generate_network.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self):
        self.dead = SystemRandom().randint(0, 100) < 25
        self.responsibility = SystemRandom().randint(0, 0xffffff)
        self.has_keys = set([SystemRandom().randint(0, 0xffffff) for i in range(SystemRandom().randint(0, 10))])
        self.known_nodes = set([nodeName() for i in range(SystemRandom().randint(0, 10))])
        self.data = "GOOD_DATA" if (SystemRandom().randint(0, 100) < 50) else "BAD_DATA"

        r = SystemRandom().randint(0, 100)

        if r < 10:
            self.responsibility = KEY
            self.has_keys.add(KEY)
        elif r < 25:
            shift = r % 16 + 1
            self.responsibility = (KEY >> shift) << shift
        elif r < 50:
            self.has_keys.add(self.responsibility) 
Example 6
Project: BioQueue   Author: liyao001   File: install.py    (license) View Source Project 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 = '[email protected]#$%^&*(-_=+)'
    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 7
Project: GAMADV-XTD   Author: taers232c   File: __init__.py    (license) View Source Project 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 8
Project: zeronet-debian   Author: bashrc   File: BitcoinECC.py    (license) View Source Project 6 votes vote down vote up
def SignECDSA(self,m):
        #Sign a message. The private key is self.d .
        h=hashlib.new("SHA256")
        h.update(m)
        z=int(h.hexdigest(),16)
        
        r=0
        s=0
        while not r or not s:
            #k=random.randint(1,self.n-1)
            k=random.SystemRandom().randint(1,self.n-1) # Better random fix
            R=self*k
            R.Normalize()
            r=R.x[0]%self.n
            s=(InvMod(k,self.n)*(z+r*self.d))%self.n

        return (r,s) 
Example 9
Project: utils   Author: rapydo   File: test_basher.py    (license) View Source Project 6 votes vote down vote up
def randomString(len=16, prefix="TEST:"):
    """
        Create a random string to be used to build data for tests
    """
    if len > 500000:
        lis = list(string.ascii_lowercase)
        return ''.join(random.choice(lis) for _ in range(len))

    rand = random.SystemRandom()
    charset = string.ascii_uppercase + string.digits

    random_string = prefix
    for _ in range(len):
        random_string += rand.choice(charset)

    return random_string 
Example 10
Project: bitcoincash-utils   Author: bitaps-com   File: tools.py    (license) View Source Project 6 votes vote down vote up
def BIP32_create_master():
    rnd = random.SystemRandom()
    a = rnd.randint(0, MAX_INT_PRIVATE_KEY)
    i = int((time.time() % 0.01) * 100000)
    h = a.to_bytes(32, byteorder="big")
    Key = b"Bitcoin seed"
    while True:
        h = hashlib.sha256(h).digest()
        if i > 1:
            i -= 1
        else:
            if int.from_bytes(h, byteorder="big") < MAX_INT_PRIVATE_KEY:
                break
    I = hmac_sha512(Key, h)
    M, C = I[:32], I[32:]
    return b'\x04\x88\xAD\xE4\x00\x00\x00\x00\x00\x00\x00\x00\x00' + C + b'\x00' + M 
Example 11
Project: DevOps   Author: YoLoveLife   File: password.py    (license) View Source Project 6 votes vote down vote up
def _random_password(length=DEFAULT_LENGTH, chars=C.DEFAULT_PASSWORD_CHARS):
    '''Return a random password string of length containing only chars

    :kwarg length: The number of characters in the new password.  Defaults to 20.
    :kwarg chars: The characters to choose from.  The default is all ascii
        letters, ascii digits, and these symbols ``.,:-_``

    .. note: this was moved from the old ansible utils code, as nothing
        else appeared to use it.
    '''
    assert isinstance(chars, text_type), '%s (%s) is not a text_type' % (chars, type(chars))

    random_generator = random.SystemRandom()

    password = []
    while len(password) < length:
        new_char = random_generator.choice(chars)
        password.append(new_char)

    return u''.join(password) 
Example 12
Project: zippy   Author: securesystemslab   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_main(verbose=None):
    testclasses =    [MersenneTwister_TestBasicOps,
                      TestDistributions,
                      TestModule]

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

    support.run_unittest(*testclasses)

    # verify reference counting
    import sys
    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in range(len(counts)):
            support.run_unittest(*testclasses)
            counts[i] = sys.gettotalrefcount()
        print(counts) 
Example 13
Project: Adventure-Insecure   Author: colinnewell   File: ldap_init.py    (license) View Source Project 6 votes vote down vote up
def add_user(self, username, name, surname, password, group_id, user_id):
        alphabet = string.ascii_letters + string.digits
        salt = ''.join(SystemRandom().choice(alphabet) for i in range(16))
        c = '{crypt}' + crypt(password, '$6$%s$' % salt)
        self.connection.add('uid=%s,ou=People,%s' % (escape_attribute_value(username), self.dn), ['posixAccount','inetOrgPerson', 'shadowAccount'], {
            'uid': username,
            'sn': surname,
            'displayName': name,
            'cn': name,
            'userPassword': c,
            'gidNumber': group_id,
            'uidNumber': user_id,
            'homeDirectory': '/home/%s' % username,
            'loginShell': '/bin/bash',
            'gecos': '',
            'mail': '%[email protected]' % username,
            'description': 'Test user',
        }) 
Example 14
Project: oil   Author: oilshell   File: test_random.py    (license) View Source Project 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 15
Project: python2-tracer   Author: extremecoders-re   File: test_random.py    (license) View Source Project 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 16
Project: pointpointgame   Author: EnighmaLab   File: IrisIA.py    (license) View Source Project 6 votes vote down vote up
def randPoint(self,can,point_dico):

        r = 5

        secure_random = random.SystemRandom()
        coord = secure_random.choice(self.randomList)
        array = coord.split('_')
        x = int(array[0])
        y = int(array[1])

        can.create_oval(x-r, y-r, x+r, y+r, fill=self.getColor())

        point = {}
        point['x'] = x
        point['y'] = y

        return point

    #Dictionnaire de point de l'IA. ce Dictionnaire permettra de connaitre tous les emplacements des points de l'IA. 
Example 17
Project: WAFNinja   Author: khalilbijjou   File: fuzzer.py    (license) View Source Project 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 18
Project: WAFNinja   Author: khalilbijjou   File: fuzzer.py    (license) View Source Project 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 19
Project: gister   Author: tacticalrce   File: tester.py    (license) View Source Project 6 votes vote down vote up
def test_post_large_message(self):
        blob_size = 100000
        for i in range(0,2):
            message = ''.join(chr(random.SystemRandom().randint(0,255)) for _ in range(random.SystemRandom().randint(blob_size,blob_size*10)))
            pre_shared_key = '0192837465OKMijnUHBygv'

            #generate the encrypted package
            enc_derived_key, enc_salt, enc_iv, real_gist_file_name = gister_transmit.generate_key_material(pre_shared_key)
            encrypted_package = gister_transmit.generate_upload_package(message, enc_derived_key, enc_iv, real_gist_file_name)
            gist_id = gister_transmit.upload_package_to_gist(encrypted_package)
            
            #pass the encrypted package, key, and iv to the decrypter
            time.sleep(5)
            encrypted_package = gister_receive.retrieve_message(gist_id)
            decrypted_message = gister_receive.decrypt_message(encrypted_package, enc_derived_key)

            self.assertTrue(decrypted_message == message) 
Example 20
Project: pyom_mud   Author: bodrich   File: auth.py    (license) View Source Project 6 votes vote down vote up
def random_base32_token(length: int=16, rng=random.SystemRandom(),
                        charset='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'):
    """
    This method just provides a quick way to obtain a proper key to
    use for a 2-factor authentication secret key.

    :param length: Normally 16
    :type length: int
    :param rng: Normally, the system RNG
    :type rng: method
    :param charset: The base32 character set
    :type charset: str
    :return: A 16-character base32 encoded token
    :rtype: str
    """
    token = ''.join(rng.choice(charset) for i in range(length))
    return '-'.join((token[0:4], token[4:8], token[8:12], token[12:16])) 
Example 21
Project: charm-plumgrid-gateway   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 22
Project: margy   Author: opentower   File: encryption.py    (MIT License) View Source Project 5 votes vote down vote up
def ran(N):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

#given a string s, returns a list containing an encrypted string and a key 
Example 23
Project: charm-swift-proxy   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 24
Project: charm-swift-proxy   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 25
Project: Lattice-Based-Signatures   Author: krishnacharya   File: Unimodal_RS.py    (license) View Source Project 5 votes vote down vote up
def crypt_secure_randint(r):
	'''
		input: 
		r : the range in which we want the random integer [-r,r]
		output:
		a cryptographiically secure random integer in [-r,r] 
	'''
	cryptogen = SystemRandom()  #takes entropy from operating system
	return cryptogen.randrange(-r,r+1) 
Example 26
Project: Lattice-Based-Signatures   Author: krishnacharya   File: util.py    (license) View Source Project 5 votes vote down vote up
def crypt_secure_randint(a, b):
	'''
		input: 
		r : the range in which we want the random integer [a,b]
		output:
		a cryptographiically secure random integer in [a,b] 
	'''
	cryptogen = SystemRandom()  #takes entropy from operating system
	return cryptogen.randrange(a, b+1) 
Example 27
Project: PimuxBot   Author: Finn10111   File: forgot_password.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def request_password():
    jid = request.form.get('jid')
    re = s.query(RecoveryEmail).filter(RecoveryEmail.jid==jid, RecoveryEmail.confirmed==True).one_or_none()
    if re:
        password_code = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(64))
        re.password_code = password_code
        s.merge(re)
        s.commit()
        password_code_link = 'https://www.pimux.de/password/?code=%s' % password_code
        sendMail(re.email, 'password reset request', 'click here: %s' % password_code_link)
        content = render_template('success.html', message='link was sent')
    else:
        content = render_template('error.html', message='user not found')
    return content 
Example 28
Project: ipwb   Author: oduwsdl   File: testUtil.py    (MIT License) View Source Project 5 votes vote down vote up
def getRandomString(n):
    return ''.join(random.SystemRandom().choice(
                   string.ascii_lowercase + string.digits) for _ in range(n)) 
Example 29
Project: iyzipay-python   Author: iyzico   File: iyzipay_resource.py    (MIT License) View Source Project 5 votes vote down vote up
def get_http_header(self, options=None, pki_string=None):
        header = {"Accept": "application/json", "Content-type": "application/json"}
        if pki_string is not None:
            random_header_value = "".join(
                random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in
                range(self.RANDOM_STRING_SIZE))
            header.update(
                {'Authorization': self.prepare_auth_string(options, random_header_value, pki_string)})
            header.update({'x-iyzi-rnd': random_header_value})
            header.update({'x-iyzi-client-version': 'iyzipay-python-1.0.29'})
        return header 
Example 30
Project: factotum   Author: Denubis   File: diceware.py    (GNU General Public License v3.0) View Source Project 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 31
Project: django-paydirekt   Author: ParticulateSolutions   File: wrappers.py    (MIT License) View Source Project 5 votes vote down vote up
def _get_random(self, length=64):
        valid_chars = string.ascii_letters + string.digits + '-' + '_'
        return ''.join(random.SystemRandom().choice(valid_chars) for x in range(length)) 
Example 32
Project: Projects   Author: it2school   File: session.py    (license) View Source Project 5 votes vote down vote up
def _generate_oauth_nonce(cls, length=8):
        return ''.join([str(random.SystemRandom().randint(0, 9)) for _ in range(length)]) 
Example 33
Project: privcount   Author: privcount   File: test_random.py    (license) View Source Project 5 votes vote down vote up
def random_value(modulus):
    '''
    call python's random.randrange(modulus)
    '''
    # random.randrange() takes one argument: a maximum value
    # and returns a random value in [0, modulus)
    # it is *NOT* uniformy distributed in python versions < 3.2
    # but this test is not sophisticated enough to pick that up
    # https://docs.python.org/3.5/library/random.html#random.randrange
    return SystemRandom().randrange(modulus) 
Example 34
Project: privcount   Author: privcount   File: test_counter.py    (license) View Source Project 5 votes vote down vote up
def try_adjust_count_signed(modulus):
    '''
    check that adjust_count_signed works as expected for modulus,
    and a randomly chosen number between modulus_min and modulus
    '''
    # randrange is not uniformly distributed in python versions < 3.2
    modulus_random = SystemRandom().randrange(modulus_min, modulus)
    check_adjust_count_signed(modulus_random)
    check_adjust_count_signed(modulus) 
Example 35
Project: privcount   Author: privcount   File: counter.py    (license) View Source Project 5 votes vote down vote up
def noise(sigma, sum_of_sq, p_exit):
    '''
    Sample noise from a gussian distribution
    the distribution is over +/- sigma, scaled by the noise weight, which is
    calculated from the exit probability p_exit, and the overall sum_of_sq
    bandwidth
    returns a floating-point value between +sigma and -sigma, scaled by
    noise_weight
    '''
    sigma_i = p_exit * sigma / sqrt(sum_of_sq)
    # the noise needs to be cryptographically secure, because knowing the RNG
    # state could allow an adversary to remove the noise
    random_sample = SystemRandom().gauss(0, sigma_i)
    return random_sample 
Example 36
Project: privcount   Author: privcount   File: counter.py    (license) View Source Project 5 votes vote down vote up
def sample(modulus):
    '''
    Sample a uniformly distributed value from the SystemRandom CSPRNG
    (uses rejection sampling to avoid bias)
    returns a long uniformly distributed in [0, modulus)
    '''
    # sanitise input
    modulus = long(modulus)
    assert modulus > 0
    # to get values up to modulus-1, we need this many bits
    sample_bit_count = (modulus-1).bit_length()
    # handle the case where modulus is 1
    if sample_bit_count == 0:
        sample_bit_count = 1
    # check the bit count is sane
    assert modulus <= 2L**sample_bit_count
    assert modulus >= 2L**(sample_bit_count-1)
    ## Unbiased sampling through rejection sampling
    while True:
        # sample that many bits
        v = SystemRandom().getrandbits(sample_bit_count)
        assert v >= 0
        assert v < 2L**sample_bit_count
        # the maximum rejection rate is 1 in 2, when modulus is 2**N + 1
        if 0L <= v < modulus:
            break
    return v 
Example 37
Project: charm-heat   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 38
Project: charm-heat   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 39
Project: charm-keystone   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 40
Project: charm-keystone   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 41
Project: charm-keystone   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 42
Project: charm-keystone   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 43
Project: charm-keystone   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars)) 
Example 44
Project: SoCFoundationFlow   Author: mattaw   File: preforkjava.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def init_key(ctx):
		try:
			key = ctx.SHARED_KEY = os.environ['SHARED_KEY']
		except KeyError:
			key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)])
			os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key
		os.environ['PREFORKPID'] = str(os.getpid())
		return key 
Example 45
Project: SoCFoundationFlow   Author: mattaw   File: prefork.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def init_key(ctx):
		try:
			key = ctx.SHARED_KEY = os.environ['SHARED_KEY']
		except KeyError:
			key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)])
			os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key

		os.environ['PREFORKPID'] = str(os.getpid())
		return key 
Example 46
Project: SoCFoundationFlow   Author: mattaw   File: preforkjava.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def init_key(ctx):
		try:
			key = ctx.SHARED_KEY = os.environ['SHARED_KEY']
		except KeyError:
			key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)])
			os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key
		os.environ['PREFORKPID'] = str(os.getpid())
		return key 
Example 47
Project: SoCFoundationFlow   Author: mattaw   File: prefork.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def init_key(ctx):
		try:
			key = ctx.SHARED_KEY = os.environ['SHARED_KEY']
		except KeyError:
			key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)])
			os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key

		os.environ['PREFORKPID'] = str(os.getpid())
		return key 
Example 48
Project: SoCFoundationFlow   Author: mattaw   File: preforkjava.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def init_key(ctx):
		try:
			key = ctx.SHARED_KEY = os.environ['SHARED_KEY']
		except KeyError:
			key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)])
			os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key
		os.environ['PREFORKPID'] = str(os.getpid())
		return key 
Example 49
Project: toy_dht   Author: MuxZeroNet   File: generate_network.py    (MIT License) View Source Project 5 votes vote down vote up
def nodeName():
    return SystemRandom().choice(list(node_names)) 
Example 50
Project: toy_dht   Author: MuxZeroNet   File: generate_network.py    (MIT License) View Source Project 5 votes vote down vote up
def makeNames(n):
    for node in BOOTSTRAP:
        node_names.add(node)

    for i in range(n):
        name = SystemRandom().choice(LETTERS) + SystemRandom().choice(LETTERS)
        node_names.add(name)