def createUserSessionKey(org, username, sessionId,
        Create a session key record in the usersessionkeys table for the given
        user session

            Name of organization for the user
            Name of the user
            ID of the session to create a key for
        charList = (list(range(48, 58)) +  # Numbers
                    list(range(65, 91)) +  # Uppercase
                    list(range(97, 123)))  # Lowercase
        sysrand = SystemRandom()
        sessionKey = ''.join(
            for i in range(64))
            createUserSessionKeyQuery = CassandraCluster.getPreparedStatement(
                INSERT INTO usersessionkeys ( sessionkey, org, username,
                    sessionid )
                VALUES ( ?, ?, ?, ? )
                """, keyspace=session.keyspace)
            createUserSessionKeyQuery.consistency_level = consistency
                            (sessionKey, org, username, sessionId))
            return sessionKey
        except Exception as e:
            log.critical("Exception in AuthDB.createUserSessionKey: %s" % (e,))
def check_collisions(upper_bound):
    Function that keeps guessing random numbers 1 to N incluside, until it hits a collision (or doesn't)
    cryptogen = SystemRandom() # OS Internal system for generating cryptographic random numbers
    already_found = set([]) # Set of numbers the adversary already found
    iterations = 1
    start = time.time()
    found = False
        while not found: # Runs until a collision is found
            item = cryptogen.randrange(1,upper_bound) # Uses the cryptographically secure PRNG to generate a random number
            if item in already_found: # If it's in the set of things already found - print the statistics
                found = True
                print "duplicate found in %.2e tries in %f seconds" % (iterations, time.time()-start)
                print "The upper bound on this probability is %.2f %%" % (coll(iterations,upper_bound)*100)
            else: # If it's a new number, add it to the set of numbers checked
    except KeyboardInterrupt: # If someone cancels the program midway - prints some statistics about the current progress
        total_time = time.time()-start
        print "Program cancelled - made %.2e attempts in %.4f seconds" % (iterations, total_time)
        print "The upper bound on getting a duplicate is %.2f %%" % (coll(iterations,upper_bound)*100)
        onepercent = ntimes(.01,upper_bound)
        rate = total_time/iterations
        seconds = onepercent*rate
        print "To have 1%% probability of guessing you need at least %d tries, at this rate it would take %f seconds" % (onepercent, seconds)
        print "%.2f minutes, %.2f hours, %.2f days, %.2f years" % (seconds/60, seconds/60/60, seconds/60/60/24, seconds/60/60/24/365)
Example #3
    def __init__(self, config, director, scheduler, _reactor=reactor):
        self._reactor = reactor
        self.director = director
        self.scheduler = scheduler

        self.config = config
        self.measurement_path = FilePath(config.measurements_directory)

        # We use a double submit token to protect against XSRF
        rng = SystemRandom()
        token_space = string.letters+string.digits
        self._xsrf_token = b''.join([rng.choice(token_space)
                                    for _ in range(30)])

        self._director_started = False
        self._is_initialized = config.is_initialized()

        # We use exponential backoff to trigger retries of the startup of
        # the director.
        self._director_startup_retries = 0
        # Maximum delay should be 30 minutes
        self._director_max_retry_delay = 30*60

        self.status_poller = LongPoller(
            self._long_polling_timeout, _reactor)
        self.director_event_poller = LongPoller(
            self._long_polling_timeout, _reactor)

        # XXX move this elsewhere

        if self._is_initialized:
def client_func(E, P, Q):
    n = E.order
    gen = SystemRandom()
    an = gen.randrange(n)
    bn = gen.randrange(n)
    am = an
    bm = bn
    Xn = P*an + Q*bn
    Xm = Xn

    while (True):
        i = __H(Xn, L)
        Xn += R[i]
        an += c[i]
        bn += d[i]

        for j in range(2):
            h = __H(Xm, L)
            Xm += R[h]
            am += c[h]
            bm += d[h]

        if Xn == Xm:

    if (bn == bm):
        raise ArithmeticError('Undefined value')

    f = an-am
    g = invmod(bm-bn, n)
    ret = (f * g) % n
    ret = (ret + n) % n
Example #5
    def generate_groups(self):
        Generates the groups based on a randomization algorithm.
        :return: the generated groups: a list of lists (names)

        if not self.names:
            raise AttributeError("Could not find names list. Try re-initializing Engine with valid filepath.")

        groups = []

        cryptogen = SystemRandom()

        current_group = []
        for name in self.names:


            is_last_name = self.names.index(name) == len(self.names) - 1
            is_group_full = len(current_group) == self.group_size

            if is_group_full or is_last_name:
                current_group = []"Created {} groups with max size {}.".format(len(groups), self.group_size))

        return groups
Example #6
    def __init__(self, known_pattern=None, session=db_session):
        '''Instantiates a color game based on a random color pattern.

        If known_pattern is specified, this color pattern is used to create the game
        instead of a random pattern.  This should only be used for testing purposes.

        If session is specified, this DB session is used instead of the standard session.

        :param known_pattern: a list (or tuple) of one-letter colors (default: None)
        :param session: the DB session (default: standard color game session)
        # Make sure to cleanup database resources on exit

        # Set up DB session
        self.s = session

        if known_pattern is None:
            sr = SystemRandom()
            self.pattern = [sr.choice(colors_short) for _ in range(PATTERN_LENGTH)]
            self.pattern = known_pattern
        self.pattern_set = set(self.pattern) = ColorGame(pattern=ColorPattern(self.pattern))
Example #7
def get_passphrase(wordnum=6, specialsnum=1, delimiter='', lang='en',
                   capitalized=True, wordlist_fd=None):
    """Get a diceware passphrase.

    The passphrase returned will contain `wordnum` words deliimted by

    If `capitalized` is ``True``, all words will be capitalized.

    If `wordlist_fd`, a file descriptor, is given, it will be used
    instead of a 'built-in' wordlist (and `lang` will be
    ignored). `wordlist_fd` must be open for reading.

    The wordlist to pick words from is determined by `lang`,
    representing a language (unless `wordlist_fd` is given).

    if wordlist_fd is None:
        wordlist_fd = open(get_wordlist_path(lang), 'r')
    word_list = get_wordlist(wordlist_fd)
    rnd = SystemRandom()
    words = [rnd.choice(word_list) for x in range(wordnum)]
    if capitalized:
        words = [x.capitalize() for x in words]
    result = delimiter.join(words)
    for _ in range(specialsnum):
        result = insert_special_char(result, rnd=rnd)
    return result
 def sign(self, message):
     """ Signs message using ECDSA.
     :param message: bytes to sign
     :return: bytes representing r, s.
     m = hashlib.sha256()
     e = m.digest()
     ln = self.sign_curve.order.bit_length() // 8
     n = self.sign_curve.order
     z = e[0:ln]
     z = int.from_bytes(z, byteorder="big")  # Matching the BigInteger form in the java signing.
     certificate = 0
     while certificate == 0:
         rng = SystemRandom()
         k = rng.randint(1, n)
         kg = self.sign_curve.get_member(k)
         r = kg.x
         if r == 0:
         s = (mod_inv(k, n) * (z + (r * self.sign_key) % n) % n) % n
         if s == 0:
         l = [r, s]
         int_length = self.sign_curve.int_length // 8
         certificate = list_to_bytes(l, int_length)
     return certificate
Example #9
	def new_password(self, user, passhash):
		Return new random password
		chars = '23456qwertasdfgzxcvbQWERTASDFGZXCVB789yuiophjknmYUIPHJKLNM'
		r = SystemRandom()
		return ''.join(r.sample(chars, 8))
Example #10
def random_password(description, min_chars=10, max_chars=20):
    Creates a random password from uppercase letters, lowercase letters and
    digits with a length between min_chars and max_chars

    # Open saved passwords file or create new one.
        fh = open("info/passwords.json", "r+")
        passwords = json.load(fh)
    except IOError:
        fh = open("info/passwords.json", "w+")
        passwords = {}

    # Return password if it exists already
    if description in passwords:
        return passwords[description]

    # Create new password if it does not exist
        seeded_random = SystemRandom()
        chars = ascii_letters + digits
        password_length = seeded_random.randint(min_chars, max_chars)
        password = "".join(seeded_random.choice(chars) for _ in range(password_length))
        passwords[description] = password
        json.dump(passwords, fh, indent=4)

        return password
Example #11
    def populate(self, *excludePSets):

        generate a bunch of seeds and stick them into this service
        This is the lazy user method.

        Optional args are names of PSets to *NOT* alter seeds.

        populate() will set all seeds
        populate("pset1", "pset2") will set all seeds but not those in
        psets named pset1 and pset2


        import random
        from random import SystemRandom
        _inst = SystemRandom()
        _MAXINT = 900000000

        #  //
        # // count seeds and create the required number of seeds
        newSeeds = [ _inst.randint(1, _MAXINT)
                     for i in range(self.countSeeds())]

        self._lockedSeeds = list(excludePSets)
        self._lockedSeeds = []
Example #12
def csprng(low, high, offset=0):
	rng = SystemRandom()
	rnum = rng.randint(low, high-1) + offset
	if rnum < 0:
		print("[-] Error: Random number generator returned out of bounds.")
		return None
	return rnum
Example #13
    def generate_config(self, env_script, start_script, server_cert=None):
        """Generates the plugin configuration file

        env_script : str
            The CLI call used to load the environment in which the plugin is
        start_script : str
            The script used to start the plugin
        server_cert : str, optional
            If the Qiita server used does not have a valid certificate, the
            path to the Qiita certificate so the plugin can connect over
            HTTPS to it
        logger.debug('Entered BaseQiitaPlugin.generate_config()')
        sr = SystemRandom()
        chars = ascii_letters + digits
        client_id = ''.join(sr.choice(chars) for i in range(50))
        client_secret = ''.join(sr.choice(chars) for i in range(255))

        server_cert = server_cert if server_cert else ""

        with open(self.conf_fp, 'w') as f:
            f.write(CONF_TEMPLATE % (, self.version, self.description,
                                     env_script, start_script,
                                     self._plugin_type, self.publications,
                                     server_cert, client_id, client_secret))
Example #14
	def generate_password(self):
		import string
		from random import SystemRandom
		rnd = SystemRandom() # use SystemRandom to get real random numbers
		chars = string.letters + string.digits
		length = 20
		return "".join(rnd.choice(chars) for _ in range(length))
Example #15
def generate(word_list, words=5, specials=0):
    rnd = SystemRandom()
    words = [ rnd.choice(word_list) for _ in range(words) ]

    # Insert at most options.special special characters. This is not
    # exactly the procedure described in the Diceware web page, because
    # this handles the case where there are more than 6 words in the
    # passphrase and more than 6 characters in the word.
    if specials:
        split_words = [ map(None, x) for x in words ]
        for _ in range(specials):
            # i is the index of the word in which the special character
            # replacement takes place.
            i = rnd.randrange(len(split_words))

            # j is the index of the character to be replaced with a special
            # character.
            j = rnd.randrange(len(split_words[i]))

            # k is the index of the special character
            k = rnd.randrange(len(SPECIAL_CHARS))

            # Split to individual characters, replace the k'th char, unsplit
            split_words[i][j] = SPECIAL_CHARS[k]

        with_specials = [ "".join(x) for x in split_words ]
        with_specials = words

    return words, with_specials
Example #16
def get_encrypted_password(password, hashtype='sha512', salt=None):

    # TODO: find a way to construct dynamically from system
    cryptmethod= {
        'md5':      '1',
        'blowfish': '2a',
        'sha256':   '5',
        'sha512':   '6',

    if hashtype in cryptmethod:
        if salt is None:
            r = SystemRandom()
            if hashtype in ['md5']:
                saltsize = 8
                saltsize = 16
            salt = ''.join([r.choice(string.ascii_letters + string.digits) for _ in range(saltsize)])

        if not HAS_PASSLIB:
            if sys.platform.startswith('darwin'):
                raise errors.AnsibleFilterError('|password_hash requires the passlib python module to generate password hashes on Mac OS X/Darwin')
            saltstring =  "$%s$%s" % (cryptmethod[hashtype],salt)
            encrypted = crypt.crypt(password, saltstring)
            if hashtype == 'blowfish':
                cls = passlib.hash.bcrypt;
                cls = getattr(passlib.hash, '%s_crypt' % hashtype)

            encrypted = cls.encrypt(password, salt=salt)

        return encrypted

    return None
Example #17
def generate_salt():
    # This uses os.urandom() underneath
    cryptogen = SystemRandom()

    # Create 16 byte hex salt
    salt_sequence = [cryptogen.randrange(256) for _ in range(16)]
    return ''.join([format(r, 'x') for r in salt_sequence])
Example #18
    def test_stress(self):
        Runs a large number of threads doing operations with resources
        checked out, ensuring properties of the pool.
        rand = SystemRandom()
        n = rand.randint(1, 400)
        passes = rand.randint(1, 20)
        rounds = rand.randint(1, 200)
        breaker = rand.uniform(0, 1)
        pool = EmptyListPool()

        def _run():
            for i in range(rounds):
                with pool.transaction() as a:
                    self.assertEqual([], a)
                    self.assertEqual([currentThread()], a)

                    for p in range(passes):
                        self.assertEqual([currentThread()], a)
                        if rand.uniform(0, 1) > breaker:


        threads = []

        for i in range(n):
            th = Thread(target=_run)

        for th in threads:
Example #19
    def get_session(self):
        get current session associated with this request.
        if no current session, create a new session
        if self.__session:
            return self.__session

        if "SESSIONID" in self.cookie:
            self.__sid = self.cookie["SESSIONID"].value
            rand = SystemRandom()
            rand_num = rand.random()
            self.__sid =

        if not os.path.exists("/tmp/.session"):
        self.__session_file =
        if self.__sid not in self.__session_file:
            self.__session_file[self.__sid] = {}
        self.__session = self.__session_file[self.__sid]
        return self.__session
Example #20
def newAccount():
	Create's a new account under this user. Balance
	is always 0
		check_params(request, ["session", "pin"])
		user = validate_session(request.form["session"])
	except StandardError as e:
		return respond(str(e), code=400), 400

	gen = SystemRandom()
	accnum = str(''.join(map(str, [gen.randrange(9) for i in range(10)])))
	pin = int(request.form["pin"])
	newaccount = Account(accnum, user, 0.00, pin)

		add_log(LOG_ACCOUNT, "User %s created a new account (%s)" % (user.username, accnum))

		return respond("An internal error has occured. Please try again.", code=400), 400

	# Delete their session

	return respond("Account created!", data={'account':, 'pin':})
Example #21
def throwAndSetRandomRun(source,runsAndProbs):
    """Pass a list of tuple pairs, with the first item of the pair a run number
    and the second number of the pair a weight.  The function will normalize the
    weights so you do not have to worry about that.  The pairs will be used to randomly choose what Run
    should be assigned to the job.
    from random import SystemRandom
    totalProb = 0.
    for r,p in runsAndProbs:
    #this is the same random generator used to set the seeds for the RandomNumberGeneratorService
    random = SystemRandom()
    runProb = random.uniform(0,totalProb)
    sumProb = 0
    runNumber = 0
    for r,p in runsAndProbs:
        if sumProb >= runProb:
            runNumber = r
    print('setting runNumber to: ',runNumber)
    if source.type_() == "PoolSource":
        source.setRunNumber = cms.untracked.uint32(runNumber)
        #sources that inherit from ConfigurableInputSource use 'firstRun'
        source.firstRun = cms.untracked.uint32(runNumber)

Example #22
def getFiles(gendpointDict, uendpoint, username, upath):

    label = str(uuid4())

    endNames = gendpointDict.keys()

    for thisEndName in endNames:

        fileList = gendpointDict[thisEndName]

        cryptogen = SystemRandom()
        transferFile = '/tmp/transferList_' + thisEndName + '_' + str(cryptogen.randint(1,9999)) + '.txt'
        file = open(transferFile, 'w')

        for thisFile in fileList:

            basename = os.path.basename(thisFile)

            if upath[-1] != '/':
                basename = '/' + basename

            remote = thisFile
            local = upath + basename

            file.write(remote + ' ' + local + '\n')


        os.system("globus transfer "+thisEndName+" "+uendpoint+" --batch --label \"CLI Batch\" < "+transferFile)


def directionsGenerator(steps):
    ''' generate unity steps in random directions '''
    from random import SystemRandom
    from numpy import exp, pi
    s = SystemRandom()
    for i in xrange(steps):
        yield exp(s.random()*pi*2j)
Example #24
def  rand_ortho1(n):
    r = SystemRandom()
    pos = [r.random() for x in range(n)]
    s = sum(pos)
    v = array(pos,dtype=float)-(s/float(n))
    norm = sqrt(sum(v*v))
    return v/norm
Example #25
def get_prime(low, high):
    csprng = SystemRandom()
    n = csprng.randrange(low, high)
    if n % 2 == 0:
        n += 1
    while not miller_rabin(n):
        n += 2
    return n
Example #26
 def __init__(self, length=16):
     rand = SystemRandom()
     rand_chars = rand.sample(RandomString.charsets,length)
     self.generated_string = "".join(rand_chars)
     m = hashlib.md5()
     self.md5 = m.digest()
Example #27
def  rand_ortho1(n):
    from random import SystemRandom
    r = SystemRandom()
    pos = [r.random() for x in xrange(n)]
    s = sum(pos)
    v = array(pos,dtype=float)-(s/len(pos))
    norm = sqrt(sum(v*v))
    return v/norm
Example #28
	def createRandomToken(self):
		'''Create a random byte sequence to use as a repeating token'''
		r = SystemRandom()
		token = bytearray()
		numBytes = r.choice([3, 4, 5, 6])
		for i in range(numBytes):
		return token
Example #29
def tcp_scan(ips, ports, randomize=True):
    loop = asyncio.get_event_loop()
    if randomize:
        rdev = SystemRandom()
        ips = rdev.shuffle(ips)
        ports = rdev.shuffle(ports)

    tcp_Scanner_run(tcp_scanner(ip, port) for port in ports for ip in ips)
Example #30
def encrypt(message,pubkey):
    ordnums = [ord(ch) for ch in message]
    p,a,akp = pubkey
    r1 = SystemRandom(time.time())
    l = r1.randint(1,p-2)
    d = pow(a,l,p)
    encnums = [onum * pow(akp,l,p) for onum in ordnums]
    return (d,encnums)