Esempio n. 1
0
def gen_commitments():
    secret = bytearray(Random.get_random_bytes(16))

    rc = hash(secret + b"r")
    kouho = bytearray(b'r' + bytearray([15]) * 15)
    rcs = fukugen(rc, kouho)
    print(rcs)

    pc = hash(secret + b"p")
    kouho = bytearray(b'p' + bytearray([15]) * 15)
    pcs = fukugen(pc, kouho)
    print(pcs)

    sc = hash(secret + b"s")
    kouho = bytearray(b's' + bytearray([15]) * 15)
    scs = fukugen(sc, kouho)
    print(scs)

    secret = hex(bytes_to_int(secret))[2:]
    print(secret)
    rps = [("r", rc), ("p", pc), ("s", sc)]
    print('get random')
    random.shuffle(rps)
    print('get random done')
    return secret, rps
def generate_password(length=16, symbolgroups=DEFAULT_PASSWORD_SYMBOLS):
    """Generate a random password from the supplied symbol groups.

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

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

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

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

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

    return ''.join(password)
Esempio n. 3
0
def decideAmounts(totalInputs, toSend, Partitions, k, fuzz):
    #fuzz is an optional amount to fuzz the transaction by
    #so if you start with a big obvious number like 2000, it might be fuzzed by up to "fuzz" amount
    fz = rand.randint(0, int(fuzz * 1000) ) / 1000.0
    toSend += fz


    g, ii =frexp10(totalInputs)
    ii = 10 ** (-1 * min(ii - 2, 0))
    print("ii", ii)
    M = 10 ** (int(math.log(2 ** Partitions) / math.log(10))) * ii
    #M = 10 ** M
    print("multiplier:", M)
    totalInputs = int(totalInputs *  M)
    toSend = int(toSend * M)
    change = totalInputs - toSend
    send_amounts, change_amounts = decomposition3(totalInputs, Partitions, toSend, k)
    all_amounts = send_amounts[:] + change_amounts[:]
    rand.shuffle(all_amounts)
    print("")
    print("change amounts:", divv(change_amounts, M))
    print("send amounts:", divv(send_amounts, M))
    print("now from the following, how much is sent?")
    print("all amounts:", sorted(divv(all_amounts, M)))
    print("possible sent amounts:")
    amounts = []
    for L in range(0, len(all_amounts)+1):
        for subset in itertools.combinations(all_amounts, L):
            amounts.append(sum(subset))

    print("number of possible sent amounts:")
    print(len(amounts))
    print("2^N:", 2 ** len(all_amounts))
    print("number of possible sent amounts duplicates removed:")
    print(len(list(set(amounts))))
Esempio n. 4
0
def decideAmounts(totalInputs, toSend, Partitions, k, fuzz):
    #fuzz is an optional amount to fuzz the transaction by
    #so if you start with a big obvious number like 2000, it might be fuzzed by up to "fuzz" amount
    fz = rand.randint(0, int(fuzz * 1000)) / 1000.0
    toSend += fz

    g, ii = frexp10(totalInputs)
    ii = 10**(-1 * min(ii - 2, 0))
    print("ii", ii)
    M = 10**(int(math.log(2**Partitions) / math.log(10))) * ii
    #M = 10 ** M
    print("multiplier:", M)
    totalInputs = int(totalInputs * M)
    toSend = int(toSend * M)
    change = totalInputs - toSend
    send_amounts, change_amounts = decomposition3(totalInputs, Partitions,
                                                  toSend, k)
    all_amounts = send_amounts[:] + change_amounts[:]
    rand.shuffle(all_amounts)
    print("")
    print("change amounts:", divv(change_amounts, M))
    print("send amounts:", divv(send_amounts, M))
    print("now from the following, how much is sent?")
    print("all amounts:", sorted(divv(all_amounts, M)))
    print("possible sent amounts:")
    amounts = []
    for L in range(0, len(all_amounts) + 1):
        for subset in itertools.combinations(all_amounts, L):
            amounts.append(sum(subset))

    print("number of possible sent amounts:")
    print(len(amounts))
    print("2^N:", 2**len(all_amounts))
    print("number of possible sent amounts duplicates removed:")
    print(len(list(set(amounts))))
Esempio n. 5
0
 def decrypt(self, crypto_list):
     decrypted_list = []
     for crypto_pair in crypto_list:
         decrypted_pair = [self.key._decrypt(c) for c in crypto_pair]
         decrypted_list.append(decrypted_pair)
     random.shuffle(decrypted_list)
     return decrypted_list
Esempio n. 6
0
 def decrypt_multi_cipher(self, crypto_list, pub_keys):
     p = int(self.key.p)
     g = int(self.key.g)
     x = int(self.key.x)
     while 1:
         k = random.randint(1, p - 1)
         if GCD(k, p - 1) == 1: break
     decrypted_list = []
     for cipher_pair in crypto_list:
         decrypted_pair = []
         for c in cipher_pair:
             c1 = int(c[0])
             c2 = int(c[1])
             c1_ = (c1 * pow(g, k, p)) % p
             prod = 1
             for y in pub_keys:
                 y = int(y)
                 prod *= pow(y, k, p)
                 prod %= p
             c1_pow = pow(c1, x, p)
             c2_ = (((c2 * prod) % p) * inverse(c1_pow, p)) % p
             decrypted_pair.append((c1_, c2_))
         decrypted_list.append(decrypted_pair)
         random.shuffle(decrypted_list)
     return decrypted_list
Esempio n. 7
0
    def classical_garble(self):
        """
            The most simple type of garbling. In classical garbled
            circuits, the whole boolean table is obfuscated by
            encrypting the output label using the input labels as keys.
            After this the table is shuffled (or *garbled*) so that
            the evaluator can't know more than one output label. For
            more information see `the paper
            <https://dl.acm.org/citation.cfm?id=1382944>`_.

            Note that a *Fernet* scheme is used since this method
            relies on knowing whether decryption was successful or not,
            as the evaluator needs to try and decrypt the four possible entries
            in the boolean table.
        """
        for left_label in self.left_wire.labels():
            for right_label in self.right_wire.labels():
                key1 = Fernet(left_label.to_base64())
                key2 = Fernet(right_label.to_base64())
                in1, in2 = left_label.represents, right_label.represents
                logic_value = self.evaluate_gate(in1, in2)
                output_label = self.output_wire.get_label(logic_value)
                pickled = pickle.dumps(output_label)
                table_entry = key1.encrypt(key2.encrypt(pickled))
                self.table.append(table_entry)

        shuffle(self.table)
Esempio n. 8
0
 def pick_files(self):
     """Pick a random subset of filenames in the Pool and return them as a
     list.  If the Pool isn't sufficiently large, return an empty list.
     """
     poolfiles = os.listdir(self.pooldir)
     poolsize = len(poolfiles)
     log.debug("Pool contains %s messages", poolsize)
     if poolsize < self.size:
         # The pool is too small to send messages.
         log.info("Pool is insufficiently populated to trigger sending.")
         return []
     process_num = (poolsize * self.rate) / 100
     log.debug("Attempting to send %s messages from the pool.", process_num)
     assert process_num <= poolsize
     # Shuffle the poolfiles into a random order
     random.shuffle(poolfiles)
     # Even though the list is shuffled, we'll pick a random point in the
     # list to slice from/to.  It does no harm, might do some good and
     # doesn't cost a lot!
     startmax = poolsize - process_num
     if startmax <= 0:
         return poolfiles
     start = random.randint(0, startmax - 1)
     end = start + process_num
     return poolfiles[start:end]
Esempio n. 9
0
def build_index(MK, ID, keyword_list):
    secure_index = [0] * len(keyword_list)
    for i in range(len(keyword_list)):
        codeword = build_codeword(ID, build_trapdoor(MK, keyword_list[i]))
        secure_index[i] = codeword
    random.shuffle(secure_index)
    return secure_index
Esempio n. 10
0
    def garble(self):

        self.output_table = {}
        self.garbled_table = {}  # emptying tables

        for gate in self.circuit.G.values():
            if not gate.is_circuit_output:
                k_0 = AES_key()  # generate a random aes key
                k_1 = AES_key()  # same
                self.output_table[gate.gate_id] = k_0, k_1

        for gate in self.circuit.G.values():
            if not gate.is_circuit_input:
                gate_0 = gate.gate_0
                gate_1 = gate.gate_1
                K_0 = self.output_table[gate_0.gate_id]  # K_0 = k_00, k_01
                K_1 = self.output_table[gate_1.gate_id]  # K_1 = k_10, k_11
                c_list = []
                for i in range(2):
                    for j in range(2):
                        alpha = gate.loc_eval(
                            i, j)  # 'real' evaluation of the gate on i,j
                        if gate.is_circuit_output:
                            m = alpha  # 0 or 1
                        else:
                            K = self.output_table[gate.gate_id]
                            m = K[alpha].rep_AES_str  # k_0 or k_1 (see above)

                        c = K_1[j].encrypt(m)
                        c_ij = K_0[i].encrypt(c)
                        c_list.append(c_ij)

                random.shuffle(c_list)
                self.garbled_table[gate.gate_id] = c_list
        return self.garbled_table
Esempio n. 11
0
 def init_from_build_info(cls, build_key, usability):
     boffset = 0
     api_host = None
     if build_key in ('Dropbox', 'DropboxTeam') and not usability:
         host = 'www.dropbox.com'
         api_host = [ ('client%d.dropbox.com' % i, 443) for i in xrange(100) ]
         random.shuffle(api_host)
     elif build_key.startswith('DropboxDev'):
         host = 'tarak.corp.dropbox.com'
         boffset -= 100
     elif build_key.startswith('DropboxAPI'):
         host = 'will-meta.getdropbox.com'
     elif build_key.startswith('DropboxBuild'):
         host = 'www.dropbox.com'
     elif build_key.startswith('DropboxId3'):
         host = os.getenv('DROPBOX_HOST')
         if not host:
             host = 'musicbox.corp.getdropbox.com'
     else:
         host = os.getenv('DROPBOX_HOST')
         if not host:
             host = 'www.dropbox.com'
     if not api_host:
         api_host = [(host, 443)]
     if build_key[-1].isdigit():
         p2p_port = 17501 + int(build_key[-1]) + boffset
     else:
         p2p_port = 17500 + boffset
     discovery_port = p2p_port
     port = 443
     toret = cls(host, port, discovery_port, p2p_port)
     toret.api_hosts = api_host
     return toret
Esempio n. 12
0
    def __init__(self):
        self.shipgirls = [
            "Aulick", "Beagle", "Benson", "Bulldog", "Cassin", "Comet",
            "Craven", "Crescent", "Cygnet", "Downes", "Foote", "Foxhound",
            "Kisaragi", "McCall", "Mikazuki", "Minazuki", "Mutsuki",
            "Shiranui", "Spence", "Uzuki", "Z20", "Z21", "Acasta", "Akatsuki",
            "Amazon", "Arashio", "Ardent", "Ariake", "Asashio", "Aylwin",
            "Bache", "Bailey", "Bush", "Dewey", "Echo", "Fletcher", "Forbin",
            "Fortune", "Fumizuki", "Gridley", "Halsey Powell", "Hamakaze",
            "Hammann", "Hatakaze", "Hatsuharu", "Hatsushimo", "Hazelwood",
            "Hobby", "Ikazuchi", "Inazuma", "Isokaze", "Jenkins", "Jersey",
            "Juno", "Jupiter", "Kagerou", "Kalk", "Kamikaze", "Kimberly",
            "Kiyonami", "Kuroshio", "Le Mars", "Matsukaze", "Michishio",
            "Mullany", "Nagatsuki", "Ooshio", "Oyashio", "Radford", "San Juan",
            "Shiratsuyu", "Sims", "Smalley", "Stanly", "Tanikaze", "Thatcher",
            "Urakaze", "Wakaba", "Yuugure", "Z18", "Z19", "Z36", "An Shan",
            "Ayanami", "Carabiniere", "Chang Chun", "Charles Ausburne",
            "Cooper", "Fu Shun", "Fubuki", "Glowworm", "Grenville", "Grozny",
            "Hanazuki", "Harutsuki", "Hibiki", "Javelin", "Kasumi",
            "L Opiniatre", "Laffey", "Le Temeraire", "Makinami", "Matchless",
            "Maury", "Minsk", "Musketeer", "Naganami", "Nicholas", "Niizuki",
            "Nowaki", "Shigure", "Tai Yuan", "Tartu", "Universal Bulin",
            "Uranami", "Vampire", "Vauquelin", "Yoizuki", "Z1", "Z23", "Z25",
            "Z35", "Eldridge", "Kawakaze", "Le Malin", "Le Triomphant",
            "Prototype Bulin MKII", "Tashkent", "Yudachi", "Yukikaze", "Z46"
        ]
        random.shuffle(self.shipgirls)
        self.lcg = LCG(len(self.shipgirls))

        self.counter = 0
 def alert_players_have_been_ordered(self):
     if self.peer_map.get(self.cli.ident).get(self.ROLL) == 0:
         # This is player 0, initiate the shuffle
         pl = self.gen_playerlist()
         shuffle(pl)
         self.cli.post_message(data={self.MESSAGE_KEY: self.SHUFFLED_LIST,
                                     self.SHUFFLED_LIST: pl})
Esempio n. 14
0
 def step_5_12(self, rx_enc):
     c_list = []
     if (self.delta == 0):
         c0_enc = 1
         for i in range(self.l):
             c0_enc *= self.crypto.secure_addition(c0_enc, rx_enc[i])
         bl = random.randint(1, 2**self.l)
         c0 = self.crypto.secure_scalar_multiplication(c0_enc, bl)
         c_list.append(c0)
         for i in range(1, self.l):
             randomint = random.randint(1, 2**self.l)
             randomint_enc = self.crypto.encrypt(randomint)
             c_list.append(randomint_enc)
     else:
         enc_minus1 = self.crypto.encrypt(self.crypto.n - 1)
         for i in range(self.l):
             prod = 1
             for j in range(i + 1, self.l):
                 prod *= self.crypto.secure_addition(prod, rx_enc[j])
             prod_sq = self.crypto.secure_scalar_multiplication(prod, 2)
             c_i_1 = self.crypto.secure_addition(enc_minus1, rx_enc[i])
             c_i_2 = self.crypto.secure_addition(c_i_1, prod_sq)
             randomint = random.randint(1, 2**self.l)
             c_i_fin = self.crypto.secure_scalar_multiplication(
                 c_i_2, randomint)
             c_list.append(c_i_fin)
     random.shuffle(c_list)
     return c_list
Esempio n. 15
0
    def rstr(self, alphabet, start_range=None,
             end_range=None, include='', exclude=''):
        """Generate a random string containing elements from 'alphabet'

        By default, rstr() will return a string between 1 and 10 characters.
        You can specify a second argument to get an exact length of string.

        If you want a string in a range of lengths, specify the start and end of
        that range as the second and third arguments.

        If you want to make certain that particular characters appear in the
        generated string, specify them as "include".

        If you want to *prevent* certain characters from appearing, pass them as
        'exclude'.

        """
        popul = [char for char in list(alphabet) if char not in list(exclude)]

        if end_range is None:
            if start_range is None:
                start_range, end_range = (1, 10)
            else:
                k = start_range

        if end_range:
            k = random.randint(start_range, end_range)

        result = sample_wr(popul, k) + list(include)
        random.shuffle(result)
        return ''.join(result)
Esempio n. 16
0
 def shuffleAddresses(addresses):
     """ Create a shuffled copy (only references!) of the encrypted output addresses. """
     indices = [i for i in xrange(0, len(addresses))]
     random.shuffle(indices)
     result = []
     for index in indices:
         result.append(addresses[index])
     return result
Esempio n. 17
0
 def __init__(self, input_wires, output_wire, logic_function):
     self.input_wires, self.output_wire, self.rows = input_wires, output_wire, []
     for entry in product(*map(enumerate, input_wires)):
         function_parameters = [x[0] for x in entry]
         input_labels = [x[1] for x in entry]
         function_value = logic_function(*function_parameters)
         output_label = self.output_wire.labels[function_value]
         self.rows.append(Gate.crypt_row(output_label, input_labels))
     shuffle(self.rows)
Esempio n. 18
0
def cutChromosome(cuttingPlace, chromosome):
    result = []
    pieces = chromosome.split(cuttingPlace)
    for piece in pieces[:-1]:
        result.append(piece + cuttingPlace)
    if pieces[-1]:
        result.append(pieces[-1])
    random.shuffle(result)
    return result
Esempio n. 19
0
def gen_commitments():
    secret = bytearray(Random.get_random_bytes(16))
    rc = hash(secret + b"r")
    pc = hash(secret + b"p")
    sc = hash(secret + b"s")
    secret = hex(bytes_to_int(secret))[2:]
    rps = [("r", rc), ("p", pc), ("s", sc)]
    random.shuffle(rps)
    return secret, rps
Esempio n. 20
0
def build_index(MK, ID, keyword_list):

    # build index for the given input file

    secure_index = [0] * len(keyword_list)
    for item in range(len(keyword_list)):
        codeword = gen_codeword(ID, gen_trapdoor(MK, keyword_list[item]))
        secure_index[item] = codeword
    random.shuffle(secure_index)
    return secure_index
Esempio n. 21
0
def shuffle_headers(request_text):
    lines = request_text.split('\r\n')
    method = lines[:1]
    headers = lines[1:4]
    ending = lines[4:]

    # shuffle headers
    random.shuffle(headers)

    return "\r\n".join(method + headers + ending)
Esempio n. 22
0
 def get_unique_languages(self):
     """
     Returns a shuffled list of languages that the user speaks, without
     repetition
     """
     if hasattr(self, 'unique_langs'):
         unique_langs = self.unique_langs
     else:
         unique_langs = list(set(self.db_csv_to_array('lang_str')))
     random.shuffle(unique_langs)
     return unique_langs
Esempio n. 23
0
def generate_password(range=None, size=16):
    if not range:
        range = string.digits + string.ascii_letters + string.digits
    a = []
    while len(a) < size - 4:
        a.append(random.choice(range))
    while len(a) < size - 2:
        a.append(random.choice(r"+=-@#~,.[]()!%^*$"))
    random.shuffle(a)
    return random.choice(string.ascii_letters) + \
           ''.join(a) + \
           random.choice(string.ascii_letters)
Esempio n. 24
0
    def known_contacts_list(self):
        """
        Return an unordered list of past and present friends' ids.
        """
        known_fids = self.friend_id_list() + \
                     self.friend_id_list("former")

        # So that nobody can tell which friends are the most recent ones
        random.shuffle( known_fids)

        self.array_to_db_csv("known_contacts_tmp", known_fids)
        return known_fids
  def post(self):
    args = random_strings_parser.parse_args()
    n = int(args["length"])

    rand_string = [s for s in string.printable]
    shuffle(rand_string)

    data = {
      'random': ''.join([str(x) for x in rand_string[:n]])
    }

    return jsonify(data)
Esempio n. 26
0
def password(text, notice):
    """[length [types]] - generates a password of <length> (default 10). [types] can include 'alpha', 'no caps',
    'numeric', 'symbols' or any combination: eg. 'numbers symbols'"""
    okay = []

    # find the length needed for the password
    numb = text.split(" ")

    try:
        length = int(numb[0])
    except ValueError:
        length = 12

    if length > 50:
        notice("Maximum length is 50 characters.")
        return

    # add alpha characters
    if "alpha" in text or "letter" in text:
        okay += list(string.ascii_lowercase)
        # adds capital characters if not told not to
        if "no caps" not in text:
            okay += list(string.ascii_uppercase)

    # add numbers
    if "numeric" in text or "number" in text:
        okay += list(string.digits)

    # add symbols
    if "symbol" in text or "special" in text:
        sym = [
            '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_',
            '+', '[', ']', '{', '}', '\\', '|', ';', ':', "'", '.', '>', ',',
            '<', '/', '?', '`', '~', '"'
        ]
        okay += sym

    # defaults to lowercase alpha + numbers password if the okay list is empty
    if not okay:
        okay = list(string.ascii_lowercase) + list(string.digits)

    # extra random lel
    random.shuffle(okay)
    chars = []

    for i in range(length):
        chars.append(random.choice(okay))

    notice("".join(chars))
Esempio n. 27
0
    def take_turn(self):
        self.shuffled_times += 1
        if self.is_first_turn():
            self.share_primes()

        self.cli.log(LogLevel.INFO, "Shuffled deck")
        self.encryptd_by.append(self.cli.ident)
        self.encrypt_deck()
        shuffle(self.shuffle_state)

        self.send_round_message(
            self.SHUFFLE_DECK, {
                self.SHUFFLE_DECK: self.shuffle_state,
                self.ENCRYPTED_BY: self.encryptd_by
            })
        self.end_my_turn()
Esempio n. 28
0
    def next_batch(self, batch_size):
        """Return the next `batch_size` examples from this data set."""
        start = self.index_in_epoch_
        if start == 0:
            shuffle(self.objects_)

        end = int(self.num_examples_ - 1)
        self.index_in_epoch_ += batch_size

        if self.index_in_epoch_ >= self.num_examples:
            #Finished epoch
            self.epochs_completed_ += 1
            self.index_in_epoch_ = 0
        else:
            end = int(self.index_in_epoch_)
        return self.read_input_and_label(start, end)
Esempio n. 29
0
def keyGen(
):  # creates the public and private keys and stores them in puKey and piKey
    reset = 1  # will be used to test if any part of the keygen brakes and start over
    reset2 = 1
    reset3 = 1
    while reset or reset2 or reset3:  # used to prevent errors by regenerating keys if needed. was more useful when collisions were more likely

        minSize = 0
        for k in range(0, keyLength):  # generate the super increasing sequence

            temp = random.randint(
                minSize, (minSize * 2) + 100
            )  # the minsize *2 +100 max is to prevent the first int and others from being to big
            piKey.supSeq[k] = temp
            minSize += temp

        piKey.M = random.randint(minSize, (minSize * 3))  # create M

        # test the super increasing sequence
        hold = 0
        reset = 0
        for L in range(0, keyLength):
            if piKey.supSeq[L] < hold:
                reset = 1
            else:
                hold += piKey.supSeq[L]

        reset2 = 1
        for _ in itertools.count(
                1
        ):  #create W # uses iteratools because number of loops was to big
            piKey.W = random.randint(1, piKey.M + 1)
            if fractions.gcd(piKey.M, piKey.W) == 1:  #test W
                reset2 = 0
                break
        reset3 = 1
        if (1 < piKey.W) and (piKey.W < (piKey.M + 1)):
            reset3 = 0

        for i in range(0, keyLength):  # generate sequence permutation
            piKey.perSeq[i] = i

        random.shuffle(piKey.perSeq)

        for j in range(0, keyLength):  #generate public key
            puKey[j] = (piKey.W * piKey.supSeq[piKey.perSeq[j] - 1]) % piKey.M
Esempio n. 30
0
def password(text, notice):
    """[length [types]] - generates a password of <length> (default 10). [types] can include 'alpha', 'no caps',
    'numeric', 'symbols' or any combination: eg. 'numbers symbols'"""
    okay = []

    # find the length needed for the password
    numb = text.split(" ")

    try:
        length = int(numb[0])
    except ValueError:
        length = 12

    if length > 50:
        notice("Maximum length is 50 characters.")
        return

    # add alpha characters
    if "alpha" in text or "letter" in text:
        okay += list(string.ascii_lowercase)
        # adds capital characters if not told not to
        if "no caps" not in text:
            okay += list(string.ascii_uppercase)

    # add numbers
    if "numeric" in text or "number" in text:
        okay += list(string.digits)

    # add symbols
    if "symbol" in text or "special" in text:
        sym = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '[', ']', '{', '}', '\\', '|', ';',
               ':', "'", '.', '>', ',', '<', '/', '?', '`', '~', '"']
        okay += sym

    # defaults to lowercase alpha + numbers password if the okay list is empty
    if not okay:
        okay = list(string.ascii_lowercase) + list(string.digits)

    # extra random lel
    random.shuffle(okay)
    chars = []

    for i in range(length):
        chars.append(random.choice(okay))

    notice("".join(chars))
Esempio n. 31
0
def main():
    # Normalize arguments
    args = docopt(__doc__)
    word_count = int(args["--length"])

    # Read and transform dictionary file
    if args["--dictionary"]:
        dict_path = args["--dictionary"]
    else:
        dict_path = os.path.join(os.path.dirname(__file__), "words.txt")
    dictionary = [w for w in [l.strip() for l in open(dict_path)] if w]
    if args["--truncate"]:
        dictionary = dictionary[: int(args["--truncate"])]
    elif not args["--dictionary"]:
        # Default truncation for built-in dictionary
        dictionary = dictionary[:8192]

    # Basic entropy calculation
    if args["--uncontrolled"]:
        entropy = math.log(math.pow(len(dictionary), word_count), 2)
    else:
        batch_size = len(dictionary) // word_count
        entropy = math.log(math.pow(batch_size, word_count) * math.factorial(word_count), 2)
    if args["--verbose"]:
        print("Pessimistic password entropy: %.1f bits" % entropy)
        print("Approximate time to crack at 20k/s: %.1f days" % (math.pow(2, entropy) / 20000 / 60 / 60 / 24))

    # Generate password
    if args["--uncontrolled"]:
        # Select random words
        words = [random.choice(dictionary) for i in range(word_count)]
    else:
        # Generate batches in random order
        batches = [dictionary[i * batch_size : (i + 1) * batch_size] for i in range(word_count)]
        random.shuffle(batches)

        # Select word from each batch
        words = [random.choice(batches[i]) for i in range(word_count)]

    # Reveal to user
    print(" ".join(words))
    if args["--complex"]:
        print("Complexified: %s1." % "".join(words).capitalize())
Esempio n. 32
0
File: Pool.py Progetto: crooks/mimix
    def select_subset(self):
        """Pick a random subset of filenames in the Pool and return them as a
        list.  If the Pool isn't sufficiently large, return an empty list.
        """
        files = os.listdir(self.pooldir)
        numfiles = len(files)
        if numfiles > 0:
            self.log.debug("Pool contains %s messages", numfiles)

        if numfiles < self.size:
            # The pool is too small to send messages.
            self.log.debug("Pool is insufficiently populated to trigger "
                           "sending.")
            files = []
            numfiles = 0
        # Without adding the 0.5, a queue containing one message will never
        # send that message.
        process_num = int(numfiles * float(self.rate) / 100 + 0.5)
        if process_num > 0:
            self.log.debug("Attempting to send %s messages from the pool.",
                           process_num)
        assert process_num <= numfiles
        # Shuffle the poolfiles into a random order
        random.shuffle(files)
        # Even though the list is shuffled, pick a random point in the list to
        # slice from/to.  It does no harm, might do some good and doesn't cost
        # a lot!
        startmax = numfiles - process_num
        if startmax == 0:
            start = 0
        else:
            start = random.randint(0, startmax - 1)
        end = start + process_num
        for f in files[start:end]:
            yield os.path.join(self.pooldir, f)
        self.processed += process_num
        # Set the point in the future at which another outbound pool run will
        # occur.
        self.trigger_time = timing.dhms_future(self.interval)
        self.log.debug("Next pool run: %s",
                       timing.timestamp(self.trigger_time))
Esempio n. 33
0
 def get_global_langs_needed(self):
     """
     Returns an unordered list with repetitions of the languages that the 
     user's new global friends should speak
     """
     tokens = self.db_csv_to_array('global_token_str')
     langs = self.db_csv_to_array('lang_str')
     need = []
     # Some people may have lost their lang_str for some reason.
     # Corrupted data etc.
     if len(langs) == 0:
         langs = ["en"] * getattr(self, "NUM_REMOTE_FRIENDS", 6)
         for i, lang in enumerate(tokens):
             if lang == "0":
                 try:
                     need.append(langs[i])
                 except IndexError:
                     need.append(langs[0])
     random.shuffle(need)
     self.array_to_db_csv("global_langs_tmp", need)
     return need
Esempio n. 34
0
def gm_eval_honest(number1, cipher2, pub_key2):
    assert(len(cipher2) == INT_LEN)
    n = pub_key2
    cipher1 = encrypt_gm(number1, n)
    
    neg_cipher1 = map(lambda x: x * (n-1) % n, cipher1)
    c_neg_xor = dot_mod(neg_cipher1, cipher2, n)
    
    cipher1_and = embed_and(cipher1, pub_key2)
    cipher2_and = embed_and(cipher2, pub_key2)
    neg_cipher1_and = embed_and(neg_cipher1, pub_key2)
    c_neg_xor_and = embed_and(c_neg_xor, pub_key2)
    
    res = [ ]
    for l in range(INT_LEN):
        temp = dot_mod(cipher2_and[l], neg_cipher1_and[l], n)        
        for u in range(l):
            temp = dot_mod(temp, c_neg_xor_and[u], n)
        res.append(temp)
    
    random.shuffle(res)
    return res
Esempio n. 35
0
    def symbol_insert(self, passphrase):
        # list of symbols to choose from
        symbol_list = [
            '!', '@', '#', '$', '%', '^', '&'
            '*', '(', ')', '+', '=', '_'
        ]
        # define the amount of symbols to use in a given string based on length >= 8
        symbol_count = round(len(passphrase) / 4)
        count = 0
        while count < symbol_count:  # pick random symbols based on int chosen and append it to passphrase
            rand_int = random.randrange(0, len(symbol_list))
            passphrase += symbol_list[rand_int]
            count += 1

        passphrase = [
            char for char in passphrase
        ]  # no delimiter, no .split(). list comprehension to split characters
        random.shuffle(
            passphrase)  # Pycrypdome shuffle, shuffle the list elements around
        passphrase = ''.join(
            passphrase)  # rejoin the list into the passphrase string

        return passphrase
Esempio n. 36
0
 def runTest(self):
     """Crypto.Random.new()"""
     # Import the Random module and try to use it
     from Crypto import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Crypto.Random import random
     x = random.getrandbits(16*8)
     y = random.getrandbits(16*8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x>y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1,10):
         x = random.randrange(start,stop,step)
         y = random.randrange(start,stop,step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1,2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start,stop)
     y = random.randint(start,stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1,1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = list(range(10000))
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
     self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = list(range(500))
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
        self.assertEqual(seq[i] in x, True)
        self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "1")
     self.assertRaises(TypeError, random.shuffle, (1,2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
         # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1,2,3), 1)
     self.assertEqual(z[0] in (1,2,3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(list(range(3)), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
             z = random.sample(b("123"), 1)
             self.assertEqual(z[0] in b("123"), True)
             z = random.sample(bytearray(b("123")), 1)
             self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
Esempio n. 37
0
def generate_key(alpha):
    copy = list(alpha)
    random.shuffle(copy)
    return tuple(copy)
Esempio n. 38
0
	def shuffle(self):
		'''Creates a new deck and uses PyCrypto to shuffle it.'''
		self.deck = range(52)
		shuffle(self.deck)
		return
 def runTest(self):
     """Crypto.Random.new()"""
     # Import the Random module and try to use it
     from Crypto import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Crypto.Random import random
     x = random.getrandbits(16 * 8)
     y = random.getrandbits(16 * 8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x > y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1, 10):
         x = random.randrange(start, stop, step)
         y = random.randrange(start, stop, step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1, 2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start, stop)
     y = random.randint(start, stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1, 1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = list(range(10000))
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1, 2, 3)) in (1, 2, 3), True)
     self.assertEqual(random.choice([1, 2, 3]) in [1, 2, 3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(
             random.choice(bytearray(b('123'))) in bytearray(b('123')),
             True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = list(range(500))
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
         self.assertEqual(seq[i] in x, True)
         self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "1")
     self.assertRaises(TypeError, random.shuffle, (1, 2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
     # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1, 2, 3), 1)
     self.assertEqual(z[0] in (1, 2, 3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(list(range(3)), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
         z = random.sample(b("123"), 1)
         self.assertEqual(z[0] in b("123"), True)
         z = random.sample(bytearray(b("123")), 1)
         self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
Esempio n. 40
0
from Crypto.Random import random

print('random.randint: ', random.randint(10, 20))
print('random.randrange: ', random.randrange(10, 20, 2))
print('random.randint: ', random.getrandbits(3))
print('random.choice: ', random.choice([1, 2, 3, 4, 5]))
print('random.sample: ', random.sample([1, 2, 3, 4, 5], 3))
list = [1, 2, 3, 4, 5]
random.shuffle(list)
print('random.shuffle: ', list)
Esempio n. 41
0
 def __init__(self, numofplayer):
     "Constructor of new faras game"
     assert numofplayer > 1 and numofplayer <= 17, "Error: must have between 2 and 17 players"
     self.numofplayer = numofplayer
     self.deck = getNewDeck()
     random.shuffle(self.deck)
Esempio n. 42
0
from Crypto.PublicKey import RSA
import binascii

# import helper's list
helpers_list = []
with open("santa.pub", "r") as f:
    for line in f:
        helper = line.split("\t")
        helper_name = helper[0]
        helper_key = RSA.importKey(helper[1])
        helpers_list.append((helper_name, helper_key))

# create santa's suffled list
santas_list = [helper[0] for helper in helpers_list]
while True:
    random.shuffle(santas_list)
    santas_choice = dict(zip(santas_list, helpers_list))
    # skip x gives to x
    if reduce(lambda x, y: x or (y[0] == y[1][0]), santas_choice.items(), False):
        continue
    # skip x give to y and y gives to x
    if reduce(lambda x, y: x or (y[0] == santas_choice[y[1][0]][0]), santas_choice.items(), False):
        continue
    break

max_name_len = reduce(lambda x, y: y if x < y else x, [len(helper[0]) for helper in helpers_list], 0)
for choice in santas_choice.items():
    helper_name = choice[1][0]
    helper_key = choice[1][1]
    secret_name = choice[0]
    secret_msg = "Mosul a decis sa iei un cadou pentru %*s. Urmeaza un numar aleator secret %32x." % (
Esempio n. 43
0
def garble_circuit(circuit, myinputs):
    """Garble a circuit

    :param circuit: circuit to garble
    :type circuit: logic_circuit.Circuit
    :param myinputs: already known inputs, to be hidden
    :type myinputs: dictionnary {gate_id: 0/1}
    :return: Garbled circuit, ungarbling keys associated to myinputs and OT
        senders for other inputs.
    :rtype: (garbled_table, input_keys, ot_senders)

    - garbled_table: dictionnary {gate_id: 4*[AES_key]}
    - input_keys: dictionnary {input_gate_id: AES_key}
    - ot_senders: dictionnary {input_gate_id: OT.Sender}
    """
    # @students: What are the key steps in this function that make it such that
    #             the inputs of Alice are not revealed to Bob ?

    # Garbling keys (k_0, k_1) for each gate => secret
    output_table = {}
    # Garbled table for each gate => public
    garbled_table = {}
    # Ungarbling keys associated to my inputs => public
    input_keys = {}
    # OT senders for inputs of the other guy => public
    ot_senders = {}

    # ---- Input validation ----
    for g_id, g_value in six.iteritems(myinputs):
        assert circuit.g[g_id].kind == "INPUT"
        assert g_value in (0, 1)

    # ---- Garbling keys generation ----
    for g_id in circuit.g:
        # For output gates, we encrypt the binary output instead of an AES key.
        if not g_id in circuit.output_gates:
            k_0 = AES_key.gen_random()
            k_1 = AES_key.gen_random()
            output_table[g_id] = (k_0, k_1)

    # ---- Garbled tables generation ----
    for g_id, gate in six.iteritems(circuit.g):
        # We already retrieved the values for all the input gates.
        if gate.kind != "INPUT":
            K_0 = output_table[gate.in0_id]  # K_0 = k_00, k_01
            K_1 = output_table[gate.in1_id]  # K_1 = k_10, k_11
            c_list = []
            for i in range(2):
                for j in range(2):
                    # 'real' evaluation of the gate on i,j
                    alpha = Gate.compute_gate(gate.kind, i, j)
                    if g_id in circuit.output_gates:
                        m = _encode_int(alpha)  # 0 or 1
                    else:
                        K = output_table[g_id]
                        m = _encode_key(K[alpha])  # k_0 or k_1 (see above)
                    c = K_1[j].encrypt(m)
                    c_ij = K_0[i].encrypt(c)
                    c_list.append(c_ij)
            # @students: Why is it important to shuffle the list?
            # ANSWER: to avoid leaking keys due to the ordering of c_ij's (the
            #          Garbled Circuit Table values)
            random.shuffle(c_list)
            garbled_table[g_id] = c_list

    # ---- Ungarbling keys generation for my inputs ----
    for g_id, input_val in six.iteritems(myinputs):
        K = output_table[g_id]
        key = K[input_val]  # key = K[i] where i in [0,1] is my input
        input_keys[g_id] = key

    # ---- Oblivious transfer senders ----
    for g_id, gate in six.iteritems(circuit.g):
        if gate.kind == "INPUT" and g_id not in myinputs:
            k0, k1 = output_table[g_id]
            ot_senders[g_id] = OT.Sender(k0, k1)
    return (garbled_table, input_keys, ot_senders)
Esempio n. 44
0
def main(target, tgt_port, src_ip, nsubflows, path, first_src_port,
         payloadFile, portShuffled, randomSrcPorts):
    conf = {"printanswer": False, "debug": 1, "check": False}
    t = ProtoTester(conf)
    s = MPTCPState()
    m = MPTCPTest(tester=t, initstate=s)
    timeout = .3
    fileBufferSize = 1024

    if not randomSrcPorts:
        ports = range(first_src_port, first_src_port + nsubflows)
    else:
        ports = [random.randrange(1, 65534) for i in range(nsubflows)]

    if portShuffled:
        shuffle(ports)

    t.toggleKernelHandling(src_ip, enable=False)
    try:
        #TODO:s abstract this into a function
        firstSubflow = True
        for port in ports:
            print "Opening connection from port", port
            if firstSubflow:
                conn_open = [m.CapSYN, m.Wait, m.CapACK]
                firstSubflow = False
            else:
                conn_open = [m.JoinSYN, m.Wait, m.JoinACK]
            sub = s.registerNewSubflow(dst=target,
                                       src=src_ip,
                                       dport=tgt_port,
                                       sport=port)
            t.sendSequence(conn_open,
                           initstate=s,
                           sub=sub,
                           waitAck=True,
                           timeout=timeout)

        print "Splitting payload across", len(ports), "subflows"
        if not payloadFile:
            payload = "GET {} HTTP/1.1 \r\nHost: {}\r\n\r\n".format(
                path, target)
            snt = m.send_data(s=s, data=path, waitAck=True, timeout=timeout)

        else:
            f = open(payloadFile)
            for data in read_file_chunks(f, fileBufferSize):
                snt = m.send_data(s=s,
                                  data=data,
                                  waitAck=True,
                                  timeout=timeout)

        #This acks data on every subflow 20 times
        #TODO: Abstract this into a function
        for i in range(1, 5):
            j = 0
            for sflow in s.sub:
                #print "Subflow ", j, " cycling..."
                ackDss = [m.DSSACK]
                t.sendSequence(ackDss,
                               initstate=s,
                               sub=sflow,
                               waitAck=True,
                               timeout=timeout)
                j += 1
            #print " ------- Heartbeat Number", str(i)

        j = 0
        for sflow in s.sub:
            data_fin = [m.DSSFIN, m.DSSACK]
            t.sendSequence(data_fin,
                           initstate=s,
                           sub=sflow,
                           waitAck=True,
                           timeout=timeout)
            print "Subflow", j, "closed FIN"
            j += 1

    except PktWaitTimeOutException:
        print("Waiting has timed out, test exiting with failure")
        sys.exit(1)
    except IOError:
        print("IO Error Occured - Does file exist?")
    finally:
        t.toggleKernelHandling(
            src_ip,
            enable=True)  # or manually with iptables -X  && iptables -F
Esempio n. 45
0
def main(target, tgt_port, src_ip, nsubflows, path, first_src_port, payloadFile, portShuffled, randomSrcPorts):
    conf = {"printanswer":False, "debug":1, "check": False}
    t = ProtoTester(conf)
    s = MPTCPState()
    m = MPTCPTest(tester=t, initstate=s)
    timeout = .3
    fileBufferSize = 1024

    if not randomSrcPorts:
        ports = range(first_src_port, first_src_port + nsubflows)
    else:
        ports = [random.randrange(1,65534) for i in range(nsubflows)]

    if portShuffled:
        shuffle(ports)
    
    t.toggleKernelHandling(src_ip, enable=False)
    try:
        #TODO:s abstract this into a function
        firstSubflow = True
        for port in ports:
            print "Opening connection from port", port
            if firstSubflow:
                conn_open = [m.CapSYN, m.Wait, m.CapACK]
                firstSubflow=False
            else:
                conn_open = [m.JoinSYN, m.Wait, m.JoinACK]
            sub = s.registerNewSubflow(dst=target, src=src_ip, dport=tgt_port, sport=port)
            t.sendSequence(conn_open, initstate=s, sub=sub, waitAck=True,timeout=timeout)

        print "Splitting payload across", len(ports), "subflows"
        if not payloadFile:
            payload = "GET {} HTTP/1.1 \r\nHost: {}\r\n\r\n".format(path, target)
            snt = m.send_data(s=s, data=path, waitAck=True, timeout=timeout)

        else:
            f = open(payloadFile)
            for data in read_file_chunks(f, fileBufferSize):
                snt = m.send_data(s=s, data=data, waitAck=True, timeout=timeout)

        #This acks data on every subflow 20 times
        #TODO: Abstract this into a function
        for i in range(1, 5):
            j = 0
            for sflow in s.sub:
                #print "Subflow ", j, " cycling..."
                ackDss=[m.DSSACK]
                t.sendSequence(ackDss, initstate=s, sub=sflow,waitAck=True, timeout=timeout)
                j += 1
            #print " ------- Heartbeat Number", str(i)

        j = 0
        for sflow in s.sub:
            data_fin = [m.DSSFIN, m.DSSACK]
            t.sendSequence(data_fin, initstate=s, sub=sflow, waitAck=True, timeout=timeout)
            print "Subflow", j, "closed FIN"
            j += 1

    except PktWaitTimeOutException:
        print("Waiting has timed out, test exiting with failure")
        sys.exit(1)
    except IOError:
        print("IO Error Occured - Does file exist?")
    finally:
        t.toggleKernelHandling(src_ip, enable=True) # or manually with iptables -X  && iptables -F
Esempio n. 46
0
    def complete_trade(self, trade_id, other_trade_id, other_pub_key):
        # First generate new pallier key-pair to maintain volume-secrecy

        # Now create bit representation of trade volume
        volume = self.waiting_trades[trade_id][
            'amt']  #Note: Max volume checked during trade send
        print("ORIG VOL: {}".format(volume))
        lower_vol = 0
        other_pub_key = construct(other_pub_key)
        perf_time = time.clock()
        # Buyer initiates (i.e. volume > 0)
        if volume > 0:
            pall_pub, pall_priv = paillier.generate_paillier_keypair()
            table = self.generate_table(volume, pall_pub)
            #print("DEBUG: volume_bits = {}\n table = {}".format(volume_bits, table))
            msg = {
                'method':
                'send_table',
                'params': [(other_pub_key.n, other_pub_key.e),
                           (trade_id, other_trade_id), table]
            }

            # Wait to recieve dummy table
            print("DEBUG: Sending table")
            self.send_message(msg)

            # Send fake c vector
            print("DEBUG: Sending fake_c")
            fake_c = [
                pall_pub.encrypt(
                    random.randint(-pall_pub.n // 3, pall_pub.n // 3))
                for i in range(VOLUME_NUM_BITS)
            ]
            msg = {'method': 'send_c', 'params': [fake_c]}

            # Recieve real result vector
            c = self.send_message(msg)

            # Decrypt c vector
            greater = False
            vals = []
            for i in range(VOLUME_NUM_BITS):
                # In this case we don't care about overflow, only values that lead to 0
                try:
                    vals.append(pall_priv.decrypt_encoded(c[i]).decode())
                except OverflowError as e:
                    pass

            print("DEBUG: vals = {}".format(vals))
            for val in vals:
                if val == 0:
                    greater = True
                    break

            print("DEBUG: Sending volume")
            if greater == True:
                # Buy > Sell (i.e. x > y)
                # Send 0 to indicate that y should send the lower value
                msg = {
                    'method': 'notify_volume',
                    'params': [other_pub_key.encrypt(0, None)[0]]
                }
                self.send_message(msg)
                print("Buy is greater")
            else:
                # Send the lower value to the other client
                msg = {
                    'method': 'notify_volume',
                    'params': [other_pub_key.encrypt(volume, None)[0]]
                }
                self.send_message(msg)
                lower_vol = volume
                print("Sell is greater")

            # Send fake volume notification
            msg = {
                'method': 'send_min_volume',
                'params': [other_pub_key.encrypt(lower_vol, None)[0]]
            }
            resp = self.send_message(msg)
            if lower_vol == 0:
                lower_vol = self.rsa_priv.decrypt(resp)

            print("CLIENT: (buyer) Completed trade {} with final volume = {}".
                  format(self.waiting_trades[trade_id], lower_vol))
        else:
            # Seller waits for buyer to send table, sends fake table to hide selling
            fake_pall_pub, fake_pall_priv = paillier.generate_paillier_keypair(
            )
            fake_table = self.generate_table(random.randint(-1000000, 1000000),
                                             fake_pall_pub)
            msg = {
                'method':
                'send_table',
                'params': [(other_pub_key.n, other_pub_key.e),
                           (trade_id, other_trade_id), fake_table]
            }

            #Wait to recieve real table
            table = self.send_message(msg)
            pall_pub = table[0][0].public_key

            # Compute c vector
            y_volume_bits = auth_getvolumebits(abs(volume))
            c = []  #[None]*VOLUME_NUM_BITS
            zero_enc = zero_encode(y_volume_bits)
            for t in zero_enc:
                n = len(y_volume_bits) - 1
                x = None
                k = paillier.EncodedNumber.encode(
                    pall_pub, random.randint(-pall_pub.n // 3,
                                             pall_pub.n // 3))
                for i in range(len(t)):
                    if x is None:
                        x = table[t[0]][i]
                    else:
                        x += table[t[i]][i]
                c.append(x * k)

            while len(c) < len(y_volume_bits):
                c.append(
                    pall_pub.encrypt(
                        random.randint(-pall_pub.n // 3, pall_pub.n // 3)))

            #for i in range(VOLUME_NUM_BITS):
            #    if y_volume_bits[i] == 0:
            #        val = table[1][i]
            #        k = random.randint(-pall_pub.n//3, pall_pub.n//3)
            #        for j in range(i+1, VOLUME_NUM_BITS):
            #            val += table[y_volume_bits[j]][j]
            #        val *= k
            #        c[i] = val
            #    else:
            #        c[i] = pall_pub.encrypt(random.randint(-pall_pub.n//3, pall_pub.n//3))

            random.shuffle(c)

            msg = {'method': 'send_c', 'params': [c]}
            # Recieve fake c vector
            fake_c = self.send_message(msg)
            # Send fake volume notification to get response from other client
            msg = {
                'method': 'notify_volume',
                'params': [other_pub_key.encrypt(0, None)[0]]
            }
            buyer_notify = self.rsa_priv.decrypt(self.send_message(msg))

            # Send minimum volume if we need to
            if buyer_notify == 0:
                msg = {
                    'method': 'send_min_volume',
                    'params': [other_pub_key.encrypt(abs(volume), None)[0]]
                }
                lower_vol = abs(volume)
                self.send_message(msg)
                print("(seller) Buy is Greater")
            else:
                msg = {
                    'method': 'send_min_volume',
                    'params': [other_pub_key.encrypt(0, None)[0]]
                }
                lower_vol = self.rsa_priv.decrypt(self.send_message(msg))
                print("(seller) Sell is Greater")

            print("CLIENT: (seller) Completed trade {} with final volume = {}".
                  format(self.waiting_trades[trade_id], lower_vol))
            print("PERF: Volume Calc time: {}".format(time.clock() -
                                                      perf_time))

        if lower_vol != 0:
            msg = {'method': 'finish_trade', 'params': [trade_id]}
            self.send_message(msg)
            return

        raise RuntimeError("Trade Matched, but not completed")