Example #1
0
def Brent_Cycle_finding_method(N : int):
    random = SystemRandom()
    if N % 2 == 0:
        return 2
    y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)
    g, r, q = 1, 1, 1
    while g == 1:
        x = y
        for i in range(r):
            y = ((y * y) % N + c) % N
        k = 0
        while k < r and g == 1:
            ys = y
            for i in range(min(m, r - k)):
                y = ((y * y) % N + c) % N
                q = q * (abs(x - y)) % N
            g = gcd(q, N)
            k = k + m
        r *= 2
    if g == N:
        while True:
            ys = ((ys * ys) % N + c) % N
            g = gcd(abs(x - ys), N)
            if g > 1:
                break
    return g
Example #2
0
    def gen_votes(self):
        cryptogen = SystemRandom()
        votings = [cryptogen.randint(1, 5000) for i in range(10)]
        users = [cryptogen.randint(3, 5002) for i in range(50)]
        for v in votings:
            a1 = str(cryptogen.randint(2, 500))
            b1 = str(cryptogen.randint(2, 500))
            a2 = str(cryptogen.randint(2, 500))
            b2 = str(cryptogen.randint(2, 500))
            votacion = self.gen_voting(v)
            random_user = cryptogen.choice(users)
            user = self.get_or_create_user(random_user)
            self.login(user=user.username)
            census = Census(voting_id=v, voter_id=random_user)
            census.save()
            question = votacion.question.all()
            data = {
                "voting": v,
                "voter": random_user,
                "question_id": question[0].id,
                "vote": [{
                    "a": a1,
                    "b": b1
                }, {
                    "a": a2,
                    "b": b2
                }]
            }
            response = self.client.post('/store/', data, format='json')
            self.assertEqual(response.status_code, 200)

        self.logout()
        return votings, users, question[0].id
Example #3
0
def get_report(survey_id, collection_exercise_id):
    rand_gen = SystemRandom()

    sample_size = rand_gen.randint(100, 1000)
    accounts_enrolled = rand_gen.randint(0, sample_size)
    accounts_pending = rand_gen.randint(0, (sample_size - accounts_enrolled) //
                                        10)
    downloads = rand_gen.randint(0, accounts_enrolled)
    uploads = rand_gen.randint(0, downloads)

    response = {
        'metadata': {
            'collectionExerciseId': collection_exercise_id,
            'timeUpdated': datetime.now().timestamp()
        },
        'report': {
            'inProgress': downloads - uploads,
            'accountsPending': accounts_pending,
            'accountsEnrolled': accounts_enrolled,
            'notStarted': sample_size - downloads,
            'completed': uploads,
            'sampleSize': sample_size
        }
    }

    return Response(json.dumps(response), content_type='application/json')
Example #4
0
    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)
                    a.append(currentThread())
                    self.assertEqual([currentThread()], a)

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

                    a.remove(currentThread())

        threads = []

        for i in range(n):
            th = Thread(target=_run)
            threads.append(th)
            th.start()

        for th in threads:
            th.join()
    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)
                    a.append(currentThread())
                    self.assertEqual([currentThread()], a)

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

                    a.remove(currentThread())

        threads = []

        for i in range(n):
            th = Thread(target=_run)
            threads.append(th)
            th.start()

        for th in threads:
            th.join()
def get_report(survey_id, collection_exercise_id):
    rand_gen = SystemRandom()

    sample_size = rand_gen.randint(100, 1000)
    accounts_enrolled = rand_gen.randint(0, sample_size)
    accounts_pending = rand_gen.randint(0, (sample_size - accounts_enrolled) //
                                        10)
    downloads = rand_gen.randint(0, accounts_enrolled)
    uploads = rand_gen.randint(0, downloads)

    response = {
        "metadata": {
            "collectionExerciseId": collection_exercise_id,
            "timeUpdated": datetime.now().timestamp()
        },
        "report": {
            "inProgress": downloads - uploads,
            "accountsPending": accounts_pending,
            "accountsEnrolled": accounts_enrolled,
            "notStarted": sample_size - downloads,
            "completed": uploads,
            "sampleSize": sample_size,
        },
    }

    return Response(json.dumps(response), content_type="application/json")
Example #7
0
 def test_basePoint(self):
     r = SystemRandom()
     for i in range(10):
         p = getRandPrime(5)
         while p <= 10:
             p = getRandPrime(5)
         e = ecc.ECC(r.randint(1, 100), r.randint(1, 100), p)
         G = e.G
         self.assertTrue(e.isInCurve(G))
Example #8
0
def genKeys(nbits):
    p,nchecks = findPrime(nbits)
    r1 = SystemRandom(time.time())
    r2 = SystemRandom(time.time())
    a = r1.randint(1,p-2)
    k = r2.randint(1,p-2)
    pubkey = (p,a,pow(a,k,p))
    prikey = k
    return (pubkey,prikey)
Example #9
0
 def test_listPointGenerator(self):
     r = SystemRandom()
     for i in range(10):
         p = getRandPrime(5)
         while p <= 10:
             p = getRandPrime(5)
         e = ecc.ECC(r.randint(1, 100), r.randint(1, 100), p)
         for point in e.listPointGenerator():
             self.assertTrue(e.isInCurve(point))
Example #10
0
class Handpar_Process:
    """
    Handpar randomizer: see Cli() for usage.
    """
    def __init__(self, **lopts):
        self.random = SystemRandom()
        if len(lopts) > 0:
            self.update(lopts)

    def update(self, lopts):
        self.__dict__.update(lopts)
        self.parangle = self.markovwalk(getattr(self, "minparangle", 0),
                                        getattr(self, "maxparangle", 0))

    @autocount
    def __call__(self, par):
        return "\\begin{handparfull}{%d}{%.2f}\n%s\n\end{handparfull}" % (
            next(self.parangle),
            self.random.uniform(self.minparscale, self.maxparscale),
            fill(" ".join(
                [(self.rotatebox(word) if state else word)
                 for state, word in izip(
                     self.bernouilli(self.freqword),
                     [
                         self.wordcount(i)
                         for i in re.split("\s+", par.group(1)) if len(i) > 0
                     ],
                 )])),
        )

    @autocount
    def wordcount(self, word):
        return word

    @autocount
    def rotatebox(self, word):
        return "\\handword{%d}{%s}" % (
            self.randpick((self.lowwordangle, self.highwordangle)),
            word,
        )

    def bernouilli(self, freq):
        while True:
            yield True if (self.random.uniform(0, 1) <= freq) else False

    def markovwalk(self, a, b):
        pos = self.random.randint(a, b)
        while True:
            step = self.random.randint(-1, 1)
            pos += step
            if (pos < a) or (pos > b):
                pos -= step
            yield pos

    def randpick(self, pick):
        return pick[self.random.randint(0, len(pick) - 1)]
Example #11
0
def random_non_trivial_unit(n, max_tries=100):
    r = SystemRandom()
    v = r.randint(2, n - 2)
    tries = 0
    while GCD(v, n) != 1 and (max_tries is None or tries < max_tries):
        v = r.randint(2, n - 2)
        tries += 1
        if max_tries is not None and tries >= max_tries:
            raise ValueError("could not find a random non-trivial unit")
    return v
def plot_custom(c_pattern, all_points, w, h):
    w -= 2
    h -= 2
    randGenerator = SystemRandom()
    points = [(randGenerator.randint(0,
                                     w - 1), randGenerator.randint(0, h - 1))
              for _ in range(all_points)]
    for p in points:
        c_pattern.create_oval([(p[0] - 2, p[1] - 2), (p[0] + 2, p[1] + 2)],
                              tag='grid_line',
                              fill='red')
Example #13
0
def make_cert():
    """Generate and return a public key PEM and a secret key PEM."""

    secretkey = rsa.generate_private_key(public_exponent=65537,
                                         key_size=2048,
                                         backend=default_backend())
    secretkey_pem = secretkey.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())

    f = make_fields()
    attrs = []
    if f.country:
        attrs.append(x509.NameAttribute(NameOID.COUNTRY_NAME, f.country))
    if f.state:
        attrs.append(
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, f.state))
    if f.locality:
        attrs.append(x509.NameAttribute(NameOID.LOCALITY_NAME, f.locality))
    if f.org:
        attrs.append(x509.NameAttribute(NameOID.ORGANIZATION_NAME, f.org))
    if f.unit:
        attrs.append(
            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, f.unit))
    if f.common:
        attrs.append(x509.NameAttribute(NameOID.COMMON_NAME, f.common))

    rng = SystemRandom()
    date_from = datetime.utcnow() - timedelta(
        days=f.delta * rng.randint(0, 80) / 100,
        hours=rng.randint(0, 23),
        minutes=rng.randint(0, 59),
        seconds=rng.randint(0, 59),
    )
    dns_list = []
    for name in f.dns_names:
        dns_list.append(x509.DNSName(name))

    subject = issuer = x509.Name(attrs)
    cert = x509.CertificateBuilder() \
        .subject_name(subject) \
        .issuer_name(issuer) \
        .public_key(secretkey.public_key()) \
        .serial_number(x509.random_serial_number()) \
        .not_valid_before(date_from) \
        .not_valid_after(date_from + timedelta(days=f.delta)) \
        .add_extension(x509.SubjectAlternativeName(dns_list), critical=False) \
        .sign(secretkey, hashes.SHA256(), default_backend())

    publickey_pem = cert.public_bytes(serialization.Encoding.PEM)

    return (publickey_pem, secretkey_pem)
Example #14
0
    def generate_question(self):
        """Generate random question."""
        generator = SystemRandom()
        operation = generator.choice(self.operators)
        first = generator.randint(self.interval[0], self.interval[1])
        second = generator.randint(self.interval[0], self.interval[1])

        # We don't want negative answers
        if operation == '-':
            first += self.interval[1]

        return ' '.join((str(first), operation, str(second)))
Example #15
0
def BuildCommitmentPrivate(v, private_bit_commitments, target_bits=64):
    #Sort bit commitments
    pc, index = zip(*sorted(
        zip(private_bit_commitments,
            list(range(0, len(private_bit_commitments))))))

    #Find transition from commitments to 0 to commitments to 1
    one_start_index = 0
    while (pc[one_start_index][0] == 0):
        one_start_index += 1

    indices_zero = list(range(0, one_start_index))
    indices_one = list(range(one_start_index, len(pc)))

    #Build commitments
    sr = SystemRandom()

    indices = [0] * target_bits

    total_bf = 0
    bit_flag = (1 << target_bits - 1)
    for i in range(0, target_bits):
        total_bf = total_bf * 2 % bn128.curve_order

        #If out of indices, refresh pool
        if len(indices_zero) == 0 or len(indices_one) == 0:
            indices_zero = list(range(0, one_start_index))
            indices_one = list(range(one_start_index, len(pc)))

        if v & bit_flag == 0:
            #Pick random zero commitment index
            r = sr.randint(0, len(indices_zero) - 1)
            indices[i] = index[indices_zero[r]]

            #Remove index from further choices
            indices_zero = indices_zero[:r] + indices_zero[r + 1:]
        else:
            #Pick random one commitment index
            r = sr.randint(0, len(indices_one) - 1)
            indices[i] = index[indices_one[r]]

            #Remove index from further choices
            indices_one = indices_one[:r] + indices_one[r + 1:]

        #Update total_bf
        total_bf = total_bf + private_bit_commitments[
            indices[i]][1] % bn128.curve_order
        bit_flag >>= 1

    #Create Proof

    return indices, total_bf
Example #16
0
def roll(count, sides):
    results = []
    rand = SystemRandom()
    for x in range(count):
        if sides == 100 or sides == 1000:
            #Special Case for 100 sized dice
            results.append(rand.randint(1, 10))
            results.append(rand.randrange(0, 100, 10))
            if sides == 1000:
                results.append(rand.randrange(0, 1000, 100))
        else:
            results.append(rand.randint(1, sides))
    return results
Example #17
0
 def test_add(self):
     r = SystemRandom()
     for i in range(10):
         p = getRandPrime(5)
         while p <= 10:
             p = getRandPrime(5)
         e = ecc.ECC(r.randint(1, 100), r.randint(1, 100), p)
         all_points = list(e.listPointGenerator())
         for j in range(100):
             point1 = r.choice(all_points)
             point2 = r.choice(all_points)
             point = e.add(point1, point2)
             self.assertEqual(e.isInCurve(point), True)
Example #18
0
class MultiElGamal(object):
    def __init__(self, p, g):
        self.p = p
        self.q = (p - 1) / 2
        self.g = g
        self.random_source = SystemRandom()

    def generate_private_key(self):
        return self.random_source.randint(2, self.q - 1)

    def generate_public_key(self, x):
        return pow(self.g, x, self.p)

    def generate_shares(self, x, share_count, recovery_threshold):
        # generate a list of coefficients, of length recovery_threshold, in the form:
        #  [x, randint(0, q - 1), randint(0, q - 1) ...]
        coefficients = [x] + [
            self.random_source.randint(0, self.q - 1)
            for _ in range(recovery_threshold - 1)
        ]

        # use the coefficients to construct a polynomial, of degree recovery_threshold - 1,
        # with y-intercept of x, in the form:
        #  coefficients[0] * i ^ 0 + coefficients[1] * i ^ 1 + coefficients[2] * i ^ 2 ...
        def recovery_polynomial(i):
            return sum(coefficient * pow(i, j)
                       for j, coefficient in enumerate(coefficients))

        # generate shares, in the form:
        #  [recovery_polynomial(1), recovery_polynomial(2), ..., recovery_polynomial(share_count)]
        shares = [recovery_polynomial(i + 1) for i in range(share_count)]

        # generate commitments for each random coefficient, in the form:
        #  [g ^ coefficients[1] % p, g ^ coefficients[2] % p ...]
        commitments = [
            pow(self.g, coefficient, self.p)
            for coefficient in coefficients[1:]
        ]

        return shares, commitments, coefficients

    def confirm_share(self, share_input, share_output, commitments):
        secret_share_check = pow(self.g, share_output, self.p)
        commitment_check = modular_product(
            (pow(commitment, pow(share_input, i), self.p)
             for i, commitment in enumerate(commitments)), self.p)
        return secret_share_check == commitment_check

    def combine_public_keys(self, y_list):
        return modular_product([y for y in y_list], self.p)
Example #19
0
    def populate(self, *excludePSets):
        """
        _populate_

        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.

        Eg:
        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.insertSeeds(*newSeeds)
        self._lockedSeeds = []
        return
Example #20
0
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 #21
0
def random_mac(value, seed=None):
    ''' takes string prefix, and return it completed with random bytes
        to get a complete 6 bytes MAC address '''

    if not isinstance(value, string_types):
        raise AnsibleFilterError('Invalid value type (%s) for random_mac (%s)' % (type(value), value))

    value = value.lower()
    mac_items = value.split(':')

    if len(mac_items) > 5:
        raise AnsibleFilterError('Invalid value (%s) for random_mac: 5 colon(:) separated items max' % value)

    err = ""
    for mac in mac_items:
        if len(mac) == 0:
            err += ",empty item"
            continue
        if not re.match('[a-f0-9]{2}', mac):
            err += ",%s not hexa byte" % mac
    err = err.strip(',')

    if len(err):
        raise AnsibleFilterError('Invalid value (%s) for random_mac: %s' % (value, err))

    if seed is None:
        r = SystemRandom()
    else:
        r = Random(seed)
    # Generate random int between x1000000000 and xFFFFFFFFFF
    v = r.randint(68719476736, 1099511627775)
    # Select first n chars to complement input prefix
    remain = 2 * (6 - len(mac_items))
    rnd = ('%x' % v)[:remain]
    return value + re.sub(r'(..)', r':\1', rnd)
Example #22
0
    def populate(self, *excludePSets):
        """
        _populate_

        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.

        Eg:
        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.insertSeeds(*newSeeds)
        self._lockedSeeds = []
        return
Example #23
0
def rabin_miller(n, t=7):
    is_prime = True
    if n < 6:
        return [
            not is_prime, not is_prime, is_prime, is_prime, not is_prime,
            is_prime
        ][n]
    elif not n & 1:
        return not is_prime

    def check(a, s, r, n):
        x = pow(a, r, n)
        if x == 1:
            return is_prime
        for i in range(s - 1):
            if x == n - 1:
                return is_prime
            x = pow(x, 2, n)
        return x == n - 1

    # Find s and r such as n - 1 = 2^s * r
    s, r = 0, n - 1
    while r & 1:
        s = s + 1
        r = r >> 1

    rand = SystemRandom()
    for i in range(t):
        a = rand.randint(2, n - 1)
        if not check(a, s, r, n):
            return not is_prime

    return is_prime
Example #24
0
    def generate_question(self):
        """Generate random question."""
        generator = SystemRandom()
        operation = generator.choice(self.operators)
        first = generator.randint(self.interval[0], self.interval[1])
        second = generator.randint(self.interval[0], self.interval[1])

        # We don't want negative answers
        if operation == '-':
            first += self.interval[1]

        return ' '.join((
            str(first),
            operation,
            str(second)
        ))
Example #25
0
class Dice:
    """A Class that mimics a physical dice used in board games."""
    def __init__(self):
        super().__init__()
        self._seed = int(time() * 100_000)
        self._generator = SystemRandom(self._seed)
        self.last_result = None
        return

    @property
    def roll(self):
        self.last_result = self._generator.randint(1, 6)
        return self.last_result

    def __str__(self):
        s = "Dice Object" if self.last_result is None else \
            "Dice that last rolled to {}".format(self.last_result)
        return s

    def __repr__(self):
        return "Dice()"

    @property
    def picture_file_name(self):
        folder = Path(__file__).absolute().parent
        file_name = folder / Path("config/D{}.png".format(self.last_result))
        file_name = file_name if file_name.exists() else Path("")
        return file_name
Example #26
0
def isPrime(number):
    systemRandom = SystemRandom()

    if number == 2:
        return True
    if number < 1 or number % 2 == 0:
        return False
    s = 0
    d = number - 1

    while d % 2 == 0:
        d //= 2
        s = s + 1

    for _ in range(128):
        x = systemRandom.randint(2, number - 1)
        x = pow(x, d, number)
        if x != 1 and x != number - 1:
            for i in range(s):
                x = pow(x, 2, number)
                if x == 1:
                    return False
                if x == number - 1:
                    break
            if x != number - 1:
                return False
    return True
Example #27
0
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')

        file.close()

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

        os.remove(transferFile)

    return
def generate_keys(parties_number):
    """ generates a private key and saves it to a file. publishes public key to BB.
    """
    private_keys = []
    for party_id in range(1, parties_number + 1):
        rng = SystemRandom()
        private_key = rng.randint(2, VOTING_CURVE.order)
        while private_key in private_keys:
            private_key = rng.randint(2, VOTING_CURVE.order)
        public_key = VOTING_CURVE.get_member(private_key)
        data = dict(party_id=party_id, first=str(public_key.x), second=str(public_key.y))
        publish_dict(data, LOCAL_BB_URL + PUBLISH_PUBLIC_KEY_TABLE_FOR_PARTIES)
        filename = PRIVATE_KEYS_PATH + "privateKey_" + str(party_id) + ".txt"
        f = open(filename, "w")
        f.writelines(["party id: \n", str(party_id) + "\n", "private key:\n", str(private_key) + "\n"])
        f.close()
Example #29
0
def encode(openPath, writePath, data, mapSeed, password=""):
	"""encode a text file with data using homoglyphs

	Args:
		openPath (string): path to the original text file to open
		writePath (string): path to write the stego-text file
		data (string): data to encode
		mapSeed (string): seed to generate the lsb map
		password (str, optional): password to encrypt the data with. Defaults to "".
	"""
	with open(openPath, encoding="utf-8") as openData:
		fileData = openData.read()
	position = 0
	output = []
	data = otp(toBin(data), password) + b"\x00"
	encodeMap = getMap(fileData, mapSeed)
	systemRandom = SystemRandom()
	for char in data:
		shift = 0
		while shift < 8:
			if encodeMap[position] > 0:
				result, shift = encodeGlyph(fileData, position, char, shift)
			else:
				result, _shift = encodeGlyph(fileData, position,
				systemRandom.randint(0, 1) << shift, shift)
			output.append(result)
			position += 1
	output.append(fileData[position:])
	with open(writePath, "w", encoding="utf-8") as writeData:
		writeData.write("".join(output))
Example #30
0
def create_password(length=None):
    special_chars = "-.*<>_!%&/()=?@${[]}"
    chars = 2 * ascii_lowercase + ascii_letters + 3 * digits + special_chars
    rand = SystemRandom()
    if not length:
        length = rand.randint(16, 24)
    return "".join(rand.choice(chars) for x in range(length))
Example #31
0
    def run(self) -> None:
        # Set a random state independent for each thread
        rng = SystemRandom()
        seed_ = rng.randint(0, 2**32 - 1)
        seed(seed_)
        np.random.seed(seed_)

        # Initialize Worker
        print(f"Worker {self.id} Reporting for duty! seed:{seed_}")
        try:
            self.env = create_env(seed=seed_)
            self.model_ref = ModelWrapper.wrap_model(self.backlog_queue,
                                                     self.return_dict, self.id)
            self.controller = create_controller(self.model_ref)
            # Run episodes until shutdown
            while not self.shutdown:
                print(f"Worker {self.id} Starting a new episode!")
                start_time = time.time()
                trajectories, stat_string = self._run_episode()
                print(
                    f"Worker {self.id} finished an episode in {time.time() - start_time} seconds"
                )
                print(stat_string)
                start_time = time.time()
                self._add_to_buffer(trajectories)
                self._update_parameters()

        except Exception as e:
            print(f"Worker {self.id} crashed {e}")
            print(traceback.print_exception(*sys.exc_info()))
        print(f"Worker {self.id} Disengaged")
Example #32
0
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.
    try:
        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:
        fh.close()
        return passwords[description]

    # Create new password if it does not exist
    else:
        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
        fh.seek(0)
        json.dump(passwords, fh, indent=4)
        fh.close()

        return password
Example #33
0
def create_dump(data, expires):
    import fcntl

    gen = SystemRandom()
    for x in range(10):
        new_id = gen.randint(1, sys.maxsize)
        location = get_dump_location(new_id)
        prepare_location_dirs(location)
        fobj = open(location, 'a+')
        try:
            fcntl.lockf(fobj, fcntl.LOCK_EX)
            if fobj.read():
                raise OSError
        except OSError:
            pass
        else:
            save_dump(
                {
                    'id': new_id,
                    'data': data,
                    'created': int(time.time()),
                    'expires': expires,
                }, fobj)
            print('New dump saved to %s' % location)
            return new_id
        finally:
            fobj.close()
    raise Exception('Could not generate unique ID for new dump')
 def sign(self, message):
     """ Signs message using ECDSA.
     :param message: bytes to sign
     :return: bytes representing r, s.
     """
     m = hashlib.sha256()
     m.update(message)
     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:
             continue
         s = (mod_inv(k, n) * (z + (r * self.sign_key) % n) % n) % n
         if s == 0:
             continue
         l = [r, s]
         int_length = self.sign_curve.int_length // 8
         certificate = list_to_bytes(l, int_length)
     return certificate
def main(args):
    r = SystemRandom()
    try:
        try:
            _min = int(args[1])
            _max = int(args[2])
        except:
            _min = 0
            _max = int(args[1])
    except:
        _min = 0
        _max = 10
    try:
        if args[0] == 'simple':
            l = list(string.letters + string.digits)
            r.shuffle(l)
            return ''.join(l[0:_max])
        if args[0] == 'strong':
            l = list(string.letters + string.digits + string.punctuation)
            r.shuffle(l)
            return ''.join(l[0:_max])
        if args[0] == 'integer':
            return r.randint(_min, _max)
        return r.uniform(_min, _max)
    except:
        return r.random()
Example #36
0
def getFiles(gendpointDict, uendpoint, username, upath, sshkey):

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

    label = str(uuid4())

    endNames = gendpointDict.keys()

    for thisEndName in endNames:

        fileList = gendpointDict[thisEndName]

        for thisFile in fileList:

            basename = os.path.basename(thisFile)

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

            remote = thisEndName + thisFile
            local = uendpoint + upath + basename

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

    file.close()

    os.system("cat '" + transferFile  + "' | ssh " + sshkey + "  " + username + "@cli.globusonline.org transfer --verify-checksum --encrypt --label=" + label + " --delete")

    os.remove(transferFile)

    return
Example #37
0
def getFiles(gendpointDict, uendpoint, username, upath):

    label = str(uuid4())

    endNames = list(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')

        file.close()

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

        os.remove(transferFile)

    return
Example #38
0
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 #39
0
class BackOffRetry(object):
    def __init__(self):
        self.backoff = {}
        self.random = SystemRandom()

    def should_run(self, instance_name):
        if instance_name not in self.backoff:
            self.backoff[instance_name] = {
                'retries': 0,
                'scheduled': time.time()
            }

        if self.backoff[instance_name]['scheduled'] <= time.time():
            return True

        return False

    def do_backoff(self, instance_name):
        tracker = self.backoff[instance_name]

        self.backoff[instance_name]['retries'] += 1
        jitter = min(
            MAX_BACKOFF_SECS,
            BASE_BACKOFF_SECS * 2**self.backoff[instance_name]['retries'])

        # let's add some jitter (half jitter)
        backoff_interval = jitter // 2
        backoff_interval += self.random.randint(0, backoff_interval)

        tracker['scheduled'] = time.time() + backoff_interval
        return backoff_interval, self.backoff[instance_name]['retries']

    def reset_backoff(self, instance_name):
        self.backoff[instance_name]['retries'] = 0
        self.backoff[instance_name]['scheduled'] = time.time()
Example #40
0
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.
    try:
        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:
        fh.close()
        return passwords[description]

    # Create new password if it does not exist
    else:
        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
        fh.seek(0)
        json.dump(passwords, fh, indent=4)
        fh.close()

        return password
Example #41
0
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)
Example #42
0
def statsGen():
    rand = SystemRandom()
    while True:
        stats = []
        for s in range(0, 6):  # Six Stats
            rolls = []
            for d in range(0, 4):  # Four Dice
                roll = rand.randint(1, 6)
                if roll == 1:  # Reroll 1's once
                    roll = rand.randint(1, 6)
                rolls.append(roll)
            rolls.sort()
            rolls.reverse()
            stats.append(rolls[0] + rolls[1] + rolls[2])
        if statsCheck(stats):
            return stats
    return None
Example #43
0
def checkPrime(n,k=10):
    isComposite = False
    for i in range(0,k):
        r1 = SystemRandom(time.time())
        a = r1.randint(1,n-1)
        isComposite = pow(a,n-1,n) != 1
        if isComposite:
            return False
    return True
Example #44
0
def key_gen():
    """
    Generates a random key for bets, placed bets and accounts.
    :return: Random key between 0 and 2147483647 (max size for django's PositiveIntegerField)
    """
    from random import SystemRandom

    randomiser = SystemRandom()
    return randomiser.randint(0, 2147483647)
Example #45
0
 def generatePin(cls):
     """
     Generate a pin to be entered into another device.
     Restricting this to 8 bytes (16 hex chars) for now.
     """
     pin = bytearray(8)
     random = SystemRandom()
     for i in range(8):
         pin[i] = random.randint(0,0xff)
     return str(pin).encode('hex')
Example #46
0
class MultiElGamal(object):
    def __init__(self, p, g):
        self.p = p
        self.q = (p-1)/2
        self.g = g
        self.random_source = SystemRandom()

    def generate_private_key(self):
        return self.random_source.randint(2, self.q - 1)

    def generate_public_key(self, x):
        return pow(self.g, x, self.p)

    def generate_shares(self, x, share_count, recovery_threshold):
        # generate a list of coefficients, of length recovery_threshold, in the form:
        #  [x, randint(0, q - 1), randint(0, q - 1) ...]
        coefficients = [x] + [self.random_source.randint(0, self.q - 1) for _ in range(recovery_threshold - 1)]

        # use the coefficients to construct a polynomial, of degree recovery_threshold - 1,
        # with y-intercept of x, in the form:
        #  coefficients[0] * i ^ 0 + coefficients[1] * i ^ 1 + coefficients[2] * i ^ 2 ...
        def recovery_polynomial(i):
            return sum(coefficient * pow(i, j) for j, coefficient in enumerate(coefficients))

        # generate shares, in the form:
        #  [recovery_polynomial(1), recovery_polynomial(2), ..., recovery_polynomial(share_count)]
        shares = [recovery_polynomial(i+1) for i in range(share_count)]

        # generate commitments for each random coefficient, in the form:
        #  [g ^ coefficients[1] % p, g ^ coefficients[2] % p ...]
        commitments = [pow(self.g, coefficient, self.p) for coefficient in coefficients[1:]]

        return shares, commitments, coefficients

    def confirm_share(self, share_input, share_output, commitments):
        secret_share_check = pow(self.g, share_output, self.p)
        commitment_check = modular_product(
            (pow(commitment, pow(share_input, i), self.p) for i, commitment in
             enumerate(commitments)), self.p)
        return secret_share_check == commitment_check

    def combine_public_keys(self, y_list):
        return modular_product([y for y in y_list], self.p)
Example #47
0
def make_board():
    global ship_coord, board_size

    # The board size is 5 times the number of ships
    board_size = num_ships * 5
    # Build an empty board of ocean waves
    for y in range(board_size):
        board.append(["~"] * board_size)

    for z in range(num_ships):
        ship_row = SystemRandom.randint(r1, 1, board_size)
        ship_col = SystemRandom.randint(r1, 1, board_size)
        # For every ship we roll to see if it is longer than one coordinate
        ship_length = SystemRandom.randint(r1, 0, 4)
        # If it is, then we roll to see what direction it stems out from.
        if ship_length:
            ship_orientation = SystemRandom.randint(r1, 1, 4)
            # These are ships that can be 2-5 coordinates long and stem in one of the 4 directions.
            # We also don't worry if they leave the board, it just makes a shorter ship.
            if ship_orientation == 1:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_row += 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 2:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_col += 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 3:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_row -= 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 4:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_col -= 1
                    ship_coord.append([ship_row, ship_col])
        # This is a single coordinate ship
        else:
            ship_coord.append([ship_row, ship_col])
Example #48
0
class CameraService(Service):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._rnd = SystemRandom()

    @rpc_method
    async def take_photo(self):
        return 'Picture `{}` has been taken.'.format(await self.save_photo())

    async def save_photo(self):
        await asyncio.sleep(self._rnd.randint(500, 1000) / 1000)
        return '{}.bmp'.format(uuid4().hex)
Example #49
0
    def roll(self, count):
        result = []
        while count:
            count -= 1
            random = SystemRandom()
            result.append(random.randint(1,6))

        # superfluous here, but handy if you switch
        # to quantum results
        result = [int(x) for x in result]

        return result
Example #50
0
def create_salt() -> bytes:
    """
    Create a Salt in Bytes

    :return: Salt data
    :rtype: bytes
    """
    rand = SystemRandom()
    salt_bytes = []
    while len(salt_bytes) < 64:
        salt_bytes.append(rand.randint(0, 255))
    return bytes(salt_bytes)
Example #51
0
def simexp(nvars):
	nvar1 = nvars[0]
	nvar2 = nvars[1]

	r = SystemRandom()
	npr.seed(r.randint(0,1e15))
	x = npr.exponential(30, nvar1)
	npr.seed(r.randint(0,1e15))
	y = npr.exponential(35,nvar2)
	
	if False:
		x.sort()
		y.sort()
	
		darray = np.zeros(100)
		for i in xrange(0,100):
			yprime = r.sample(y, len(x))
			yprime.sort()
			darray[i] = util.dice(x,yprime)
			return max_conf_est(darray, 0.99)


	return new_similarity_invcdf(x,y)
Example #52
0
def place_ships():
    global ship_coord
    for z in range(num_ships):
        ship_row = SystemRandom.randint(r1, 1, board_size)
        ship_col = SystemRandom.randint(r1, 1, board_size)
        # For every ship we roll to see if it is longer than one coordinate
        ship_length = SystemRandom.randint(r1, 0, 4)
        # If it is, then we roll to see what direction it stems out from.
        if ship_length:
            ship_orientation = SystemRandom.randint(r1, 1, 4)
            # These are ships that can be 2-5 coord long and stem in one of the 4 directions.
            # We also don't worry if they leave the board, this is caught later and we can't fire off the board
            if ship_orientation == 1:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_row += 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 2:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_col += 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 3:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_row -= 1
                    ship_coord.append([ship_row, ship_col])
            elif ship_orientation == 4:
                ship_coord.append([ship_row, ship_col])
                for i in range(1, ship_length):
                    ship_col -= 1
                    ship_coord.append([ship_row, ship_col])

        # This saves the coordinates to be referenced for hits later
        # This is a single coordinate ship
        else:
            ship_coord.append([ship_row, ship_col])
 def from_int(num, num_len, curve):
     """encodes integer num to an ECCGroupMember object
     algorithm from https://eprint.iacr.org/2013/373.pdf part 2.4
     num must be of bit size at most half of the bit size of curve.order"""
     rng = SystemRandom()
     prefix_length = curve.order.bit_length() - num_len
     a = curve.a
     b = curve.b
     p = curve.p
     while True:
         prefix = rng.randint(1, 2 ** prefix_length - 1)
         candidate_x = concat_bits(prefix, num, num_len)
         candidate_y2 = (candidate_x ** 3 + a * candidate_x + b) % p
         candidate_y = mod_sqrt(candidate_y2, p)
         if ECGroupMember.verify_point(candidate_x, candidate_y, curve):
             return ECGroupMember(curve, candidate_x, candidate_y)
Example #54
0
    def __init__(self, conf=None):
        if not conf:
            conf = Configuration()

        self._conf = conf
        self.encoding = conf.get('encoding') or 'utf-8'
        self._iter = conf.get('iter') or 0.05
        self._timeout = conf.get('timeout') or 60
        if not(1 <= self._timeout <= 60):
            self._timeout = 60

        self._buffer_size = conf.get('buffer_size') or 512
        self._logger = conf.get_logger(
            wraper=LoggerWrapper('client'))
        self.command_builder = self.cls_command_builder()
        rand = SystemRandom()
        self._cid_part = '{:0>4}'.format(hex(rand.randint(0, int('ffff', 16)))[2:])
Example #55
0
    def prepare_auth_token(conf, silently=False):
        assert isinstance(conf, Configuration)
        priv_key_path = conf.get('crypto_priv_key_path')
        rand = SystemRandom()
        logger = conf.get_logger()
        auth_data = None
        try:
            with open(priv_key_path, 'r') as key_file:
                priv_rsakey = key_file.read()
                algorithms = get_default_algorithms()
                # 2 random parts
                segments = [
                    base64.urlsafe_b64encode(''.join(
                        # get ascii from [48, 122]
                        chr(rand.randint(48, 123))
                        for _ in range(_random_part_size)
                    ).encode(encoding=encoding))
                    for _ in range(2)
                ]
                algorithm = conf.get('crypto_algorithm')
                try:
                    alg_obj = algorithms[algorithm]
                    signature = alg_obj.sign(
                        b'.'.join(segments),
                        alg_obj.prepare_key(priv_rsakey))

                    segments.append(base64.urlsafe_b64encode(signature))
                    auth_data = b'.'.join(segments)

                except KeyError:
                    if not silently:
                        raise NotImplementedError(
                            'Algorithm "{}" not supported.'.format(algorithm))

        except (TypeError, FileNotFoundError, PermissionError) as err:
            logger.fatal(
                'Can not use private key "{}", error: {}'.format(
                    priv_key_path, err))

            if not silently:
                raise
        else:
            logger.debug('auth data: {}'.format(auth_data))

        return auth_data
Example #56
0
def chancesuccess():
    form = RandNumForm()
    if form.validate_on_submit():
        rngchance = form.rngchance.data
        rngcount = form.rngcount.data
        if rngchance not in [str(x) for x in range(0, 101)]:
            rngerror = "Chance must be whole number from 0 to 100."
            return render_template('chancesuccess.html', form=form,
                                   rngerror=rngerror)
        if rngcount not in [str(x) for x in range(1, 101)]:
            rngerror = "Count must be whole number from 1 to 100."
            return render_template('chancesuccess.html', form=form,
                                   rngerror=rngerror)
        randrng = SystemRandom()
        successcount = sum([1 for x in range(int(rngcount)) if int(rngchance) >= randrng.randint(1, 100)])
        results = (successcount, rngcount)
        return render_template('chancesuccess.html', form=form, results=results)
    return render_template('chancesuccess.html', form=form)