コード例 #1
0
def decryptFromCmd(ct, key):
    ct = ct.strip()
    ctbv = BitVector(hexstring = ct)
    key = BitVector(hexstring = key)
    pt = decrypt(ctbv, key)
    pt = pt.getTextFromBitVector()
    return pt
コード例 #2
0
ファイル: generator-proc.py プロジェクト: e1ven/HaShrink
 def generate(self,id):
     validhash = 0
     validmp3 = 0
     while self.queue.qsize() > 0:
         bitlist = self.queue.get()
         bv = BitVector(bitlist=bitlist)
         newpath = self.path + 'testfile.mp3'
         testfile = open(newpath,'wb')
         bv.write_to_file(testfile)
         testfile.close()
         newhash = self.hashfile(newpath)
         if newhash == self.originalhash:
             goodpath = self.path + 'candidate' + str(validhash) +  '.mp3'
             print("Possible Candidate at " + goodpath)
             os.rename(newpath,goodpath)
             if idmp3.isMp3Valid(goodpath):
                 mp3path = self.path + '-validmp3-' + str(validmp3) +  '.mp3'
                 print("Possible mp3 at " + mp3path)
                 os.rename(goodpath,mp3path)
                 validmp3 += 1
             else:
                 print(" but, alas, no.")
             validhash += 1
         else:
             print(newhash + " does not match " + originalhash + "; deleting " + newpath )
             os.remove(newpath)
コード例 #3
0
def division(divident, divisor):
    remainder = BitVector(intVal=1, size=32)
    quotient = BitVector(size=32)
    print("divident:", divident)
    print("divisor: ", divisor)
    print("Step by step calculation:")
    print("Searching for the first 1 in divident")
    i = 0
    while not divident[i]:
        i += 1
    print("Position of first 1:", i)
    print("Writing remainder as first half of result register")
    while i != len(divident):
        print(remainder, quotient)
        print("Checking if divisor is greater than remainder")
        if divisor >= remainder:
            print("If true, expanding remainder with next divident symbol")
            remainder.shift_left_by_one()
            remainder[-1] = divident[i + 1]
        else:
            print(
                "If false, subtracking divisor from remainder and shift remainder to the left"
            )
            print("and set 1 in quotient in the according divident index")
            remainder = subtraction(remainder, divisor)
            remainder.shift_left_by_one()
            quotient[i - 32] = 1
        i += 1
    print("Final result:", remainder, quotient)
    print("Final result in decimal: quotient:", quotient.int_val(),
          ", remainder:", remainder.int_val())
コード例 #4
0
def GenerateKeys(eVAL):
    ## Setup the prime generator
    pg = PrimeGenerator(bits=128, debug=0)
    while (True):
        p = pg.findPrime()
        q = pg.findPrime()
        ## Check p and q are different
        if p == q: continue
        ## Check left two MSB's are 1 (bin command returns 0b appended at front)
        if not (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): continue
        ## Check that the totients of p and q are co-prime to e
        if (GCD(p - 1, eVAL) != 1) or (GCD(q - 1, eVAL) != 1): continue
        break
    ## Calculate modulus
    n = p * q
    ## Calculate totient of n
    tn = (p - 1) * (q - 1)
    modBV = BitVector(intVal=tn)
    eBV = BitVector(intVal=eVAL)
    ## Calculate multiplicative inverse
    d = eBV.multiplicative_inverse(modBV)
    d = int(d)
    ## Create public and private sets
    public, private = [eVAL, n], [d, n]
    ## Return items
    return public, private, p, q, eVAL
コード例 #5
0
ファイル: average.py プロジェクト: kbokka/rocket-science
def crypt_modified(inputf_name, key, which_block, which_bit):
    # Modified crypt for test with plain txt changes
    # which_block: to toggle `which_bit` in which block

    allblocks = []
    bvfile = BitVector(filename=inputf_name)
    round_keys = [get_round_key(key, rnum) for rnum in xrange(0, 16)]

    block = 0  # Keep count of 64 Bit Blocks
    while (bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(64)
        if block == which_block:
            bit_block[which_bit] = bit_block[which_bit] ^ 1
        # pad if bit_block size is less than 64 bits
        bit_block.pad_from_right(64 - len(bit_block))

        # Perform 16 rounds
        for round in xrange(0, 16):
            bit_block = crypt_round(bit_block, round_keys[round])

        LE, RE = bit_block.divide_into_two()
        bit_block = RE + LE
        allblocks.append(bit_block)
        block += 1

    bvfile.close_file_object()
    return allblocks
コード例 #6
0
 def __init__(self, length, clock_bits, taps, majority_bits=None, negated_bit=None, bitstring=None, int_value=None):
     """
         :param length: size (number of bits) of the lfsr
         :param clock_bits: position of bits which indicate
                            clocking for A5/1
         :param taps: position of bits to calculate the first
                      position in a clocking cycle
         :param majority_bits: Optional parameter, positions of
                               bits for the majority function A5/2
         :param negated_bit: Optional parameter, position of the
                             bit that is negated in the majority
                             function (for A5/2)
         :param bitstring: register value as bitstring
         :param int_value: register value as integer
     """
     if bitstring:
         self.register = BitVector(bitstring=bitstring)
     elif int_value:
         self.register = BitVector(size=length, intVal=int_value)
     else:
         self.register = BitVector(size=length)
     self.length = length
     self.taps = taps
     self.majority_bits = majority_bits
     self.negated_bit = negated_bit
     self.clock_bits = []
     for clock_bit in clock_bits:
         self.clock_bits.append(length - clock_bit - 1)
def encrypt(outfile, blocks, n):
    e_hex_str = ""
    for b in blocks:
        e_num = pow(int(b), e, n)
        e_numbv = BitVector(intVal=e_num, size=256)
        e_hex_str = e_hex_str + e_numbv.get_hex_string_from_bitvector()
    return e_hex_str
コード例 #8
0
def multiplication(multiplicand, multiplier):
    carry = 0
    register = BitVector(intVal=multiplier.int_val(), size=64)
    print("Initial register:", register)
    for i in range(30, -1, -1):
        if register[-1]:
            for y in range(31, -1, -1):
                if carry:
                    if register[y + 1] & multiplicand[y]:
                        register[y + 1] = 1
                        carry = 1
                    elif register[y + 1] | multiplicand[y]:
                        register[y + 1] = 0
                        carry = 1
                    else:
                        register[y + 1] = 1
                        carry = 0
                else:
                    if register[y + 1] & multiplicand[y]:
                        register[y + 1] = 0
                        carry = 1
                    elif register[y + 1] | multiplicand[y]:
                        register[y + 1] = 1
                    else:
                        register[y + 1] = 0
            print("Add multiplicand to register:", register)
        print("Shift register by one:", register)
        register.shift_right_by_one()
    print("Final result:", register)
    print("Final result in decimal:", register.int_val())
コード例 #9
0
def decryptFromFile(ctfile, ptfile, keyfile):
    if os.path.exists(ctfile):
        cipherTexts = readcipherTextFile(ctfile)
    else:
        print("Cipher File not found. Try again later")
        sys.exit()

    if os.path.exists(keyfile):
        key = open(keyfile).read()
    else:
        print("Key File not found. Try again later")
        sys.exit()

    plaintexts = list()
    keybv = BitVector(hexstring = key)

    for ct in cipherTexts:
        ctbv = BitVector(hexstring = ct.strip(" \n\t"))
        decrypted = decrypt(ctbv, keybv)
        plaintexts.append(decrypted)

    with open(plainfile, "w", newline="") as kf:
        for pt in plaintexts:
            pt = pt.getTextFromBitVector()
            kf.write(pt)

    print("Your cipher texts is written into file {}".format(ptfile))
    return plaintexts
コード例 #10
0
    def decrypt(self, ciphertext: bytes) -> bytes:
        """Decryption of a ciphertext.

        Args:
            ciphertext:  Must be a bytearray of length self.__blocksize_bytes

        Returns:
            bytearray containing the plaintext of length self.__blocksize_bytes

        """
        assert (len(ciphertext) == self.__blocksize_bytes), \
            "Ciphertext has length != blocksize"
        assert (self.__priv_key is not None), "Private key not set"

        self.__state = BitVector(rawbytes=ciphertext)

        for i in range(self.__number_rounds, 0, -1):
            self.__key_addition(i)
            self.__state = self.__state ^ self.__round_consts[i - 1]
            self.__multiply_with_lin_mat_inv(i - 1)
            self.__apply_sbox_inv()

        self.__key_addition(0)

        result = bytes.fromhex(self.__state.get_bitvector_in_hex())
        self.__state = None
        return result
コード例 #11
0
ファイル: AES.py プロジェクト: kbokka/rocket-science
def invmix_cols(state):
    mod = BitVector(bitstring='100011011')

    brw0 = [
        BitVector(hexstring='0e'),
        BitVector(hexstring='0b'),
        BitVector(hexstring='0d'),
        BitVector(hexstring='09')
    ]

    brw1 = [brw0[3]] + brw0[1:4]
    brw2 = [brw1[3]] + brw1[1:4]
    brw3 = [brw2[3]] + brw2[1:4]

    for j in xrange(0, 4):  # to select col
        s = [state[0][j], state[1][j], state[2][j], state[3][j]]

        sp0 = reduce(
            lambda x, y: x ^ y,
            [brw0[i].gf_multiply_modular(s[i], mod, 8) for i in xrange(0, 4)])
        sp1 = reduce(
            lambda x, y: x ^ y,
            [brw1[i].gf_multiply_modular(s[i], mod, 8) for i in xrange(0, 4)])
        sp2 = reduce(
            lambda x, y: x ^ y,
            [brw2[i].gf_multiply_modular(s[i], mod, 8) for i in xrange(0, 4)])
        sp3 = reduce(
            lambda x, y: x ^ y,
            [brw3[i].gf_multiply_modular(s[i], mod, 8) for i in xrange(0, 4)])

        state[0][j] = sp0
        state[1][j] = sp1
        state[2][j] = sp2
        state[3][j] = sp3
コード例 #12
0
 def __init__(self, k):
     self.k = k
     self.k2 = k * k
     self.n = 0
     self.h = 0
     self.T = BitVector(size=0)
     self.L = BitVector(size=0)
コード例 #13
0
ファイル: AES.py プロジェクト: kbokka/rocket-science
def decrypt(keyschedule):
    # place to store state array
    rstate = [[0 for i in xrange(0, 4)] for i in xrange(0, 4)]

    bvfile = BitVector(filename=encout)
    fout = open(dectxt, "w")

    while (bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(128)
        bit_block.pad_from_right(128 - len(bit_block))

        # init state array
        for i in xrange(0, 4):
            for j in xrange(0, 4):
                sp = (i * 32) + (j * 8)
                rstate[j][i] = bit_block[sp:sp + 8]

        add_round_key(rstate, keyschedule[56:60])

        for i in xrange(1, 14):
            invshift_rows(rstate)
            invsub_bytes(rstate)
            add_round_key(rstate, keyschedule[i * 4:((i + 1) * 4)])
            invmix_cols(rstate)

        invshift_rows(rstate)
        invsub_bytes(rstate)
        add_round_key(rstate, keyschedule[0:4])

        for i in xrange(0, 4):
            for j in xrange(0, 4):
                rstate[i][j].write_to_file(fout)

    fout.close()
コード例 #14
0
    def verify(self, test_idx, bit_predictions, true_input):
        hash_algo = self.config['hash']
        difficulty = self.config['difficulty']

        pred_input = bit_predictions.clone().detach()
        pred_input = torch.clamp(torch.round(pred_input), 0, 1)
        pred_input = pred_input.squeeze()[:self.n_input]

        true_in = int(BitVector(bitlist=true_input.squeeze()))
        pred_in = int(BitVector(bitlist=pred_input))

        fmt = '{:0%dX}' % (self.n_input // 4)
        true_in = fmt.format(true_in).lower()
        pred_in = fmt.format(pred_in).lower()
        print('TEST CASE %d' % (test_idx + 1))
        print('Hash input: %s' % true_in)
        print('Pred input: %s' % pred_in)

        cmd = ['python', '-m', 'dataset_generation.generate',
            '--num-input-bits', str(self.n_input),
            '--hash-algo', hash_algo, '--difficulty', str(difficulty),
            '--hash-input']

        true_out = subprocess.run(cmd + [true_in],
                                stdout=subprocess.PIPE).stdout.decode('utf-8')
        pred_out = subprocess.run(cmd + [pred_in],
                                stdout=subprocess.PIPE).stdout.decode('utf-8')

        if true_out == pred_out:
            print('Hashes match: {}'.format(true_out))
        else:
            print('Expected:\n\t{}\nGot:\n\t{}'.format(true_out, pred_out))
コード例 #15
0
def multiplication(multiplicand, multiplier):
    carry = 0
    register = BitVector(intVal=multiplier.int_val(), size=64)
    print("Початковий регістр:", register)
    for i in range(30, -1, -1):
        if register[-1]:
            for y in range(31, -1, -1):
                if carry:
                    if register[y + 1] & multiplicand[y]:
                        register[y + 1] = 1
                        carry = 1
                    elif register[y + 1] | multiplicand[y]:
                        register[y + 1] = 0
                        carry = 1
                    else:
                        register[y + 1] = 1
                        carry = 0
                else:
                    if register[y + 1] & multiplicand[y]:
                        register[y + 1] = 0
                        carry = 1
                    elif register[y + 1] | multiplicand[y]:
                        register[y + 1] = 1
                    else:
                        register[y + 1] = 0
            print("Додавання першого множника в регістр:", register)
        print("Здвиг регістру на один:", register)
        register.shift_right_by_one()
    print("Результат:", register)
    print("Результат у десятковому:", register.int_val())
コード例 #16
0
ファイル: picnic.py プロジェクト: ThorKn/Python-Picnic
    def run_mpc_verify(self, t, tapes, tmp_view_raw, chal_trit):

        key_shares = []
        states = []
        roundkeys = []

        # Create empty roundkeys and states
        # Fill key_shares with views
        for i in range(2):
            roundkeys.append(BitVector(intVal=0, size=self.blocksize))
            states.append(BitVector(intVal=0, size=self.blocksize))
            key_shares.append(self.__views[t][i].i_share)

        # Init states by xor'ing plaintext and roundkeys
        states = self.mpc_xor_constant_verify(states, self.__pub_key.p,
                                              chal_trit)
        roundkeys = self.lowmc.mpc_matrix_mul_keys(roundkeys, key_shares, 0, 2)
        states = self.mpc_xor(states, roundkeys, 2)

        for r in range(self.rounds):

            states = self.mpc_sbox_verify(states, tapes, r, t)
            states = self.lowmc.mpc_matrix_mul_lin(states, states, r, 2)
            states = self.lowmc.mpc_xor_rconsts_verify(states, r, chal_trit)
            roundkeys = self.lowmc.mpc_matrix_mul_keys(roundkeys, key_shares,
                                                       r + 1, 2)
            states = self.mpc_xor(states, roundkeys, 2)

        for i in range(2):
            self.__views[t][i].o_share = states[i]
コード例 #17
0
	def __init__(self, n, p):
		self.m = int(-(n*np.log(p))/(np.log(2)**2))
		self.bitarray = BitVector(size = self.m)
		self.markarry = BitVector(size = self.m)
		self.n = n
		self.k = int(-np.log2(p))
		self.p = p
コード例 #18
0
    def encrypt(self, plaintext: bytes) -> bytes:
        """Encryption of a plaintext.

        Args:
            plaintext:  Must be a bytearray of length self.__blocksize_bytes

        Returns:
            A bytearray containing the ciphertext of
            length self.__blocksize_bytes

        """
        assert (len(plaintext) == self.__blocksize_bytes), \
            "Plaintext has length != blocksize"
        assert (self.__priv_key is not None), "Private key not set"

        self.__state = BitVector(rawbytes=plaintext)

        self.__key_addition(0)

        for i in range(self.__number_rounds):
            self.__apply_sbox()
            self.__multiply_with_lin_mat(i)
            self.__state = self.__state ^ self.__round_consts[i]
            self.__key_addition(i + 1)

        result = bytes.fromhex(self.__state.get_bitvector_in_hex())
        self.__state = None
        return result
コード例 #19
0
    def verifyMessage(self, msg):
        '''
        Verify the given message content and mark it as received. The message have to be one of created by the
        :func:`generateMessage` generator.

        :param msg: message to verify
        '''
        sender = msg[0]['sender']
        number = msg[0]['number']
        expectedMsg = data.createData(sender, self.size, number, self.house,
                                      self.queue)
        equal = expectedMsg == msg[0]

        if sender not in self.received:
            self.received[sender] = (
                BitVector(size=self.count),  # received
                BitVector(size=self.count),  # duplicated
                BitVector(size=self.count))  # wrong content

        if self.received[sender][0][number]:  # duplicate
            self.received[sender][1][number] = 1
        else:  # first time received
            self.received[sender][0][number] = 1
        if not equal:
            self.received[sender][2][number] = 1
def getPQD(n123):
    c = True
    generator1 = PrimeGenerator(bits=128, debug=0)
    generator2 = PrimeGenerator(bits=128, debug=0)
    count = 0
    while c == True:
        p = generator1.findPrime()
        q = generator2.findPrime()
        pbv = BitVector(intVal=p, size=128)
        qbv = BitVector(intVal=q, size=128)
        #print p, q
        if (not (p != q)):
            c = True
        elif (not ((pbv[0] == 1) and (qbv[0] == 1))):
            c = True
        elif (not ((int(BitVector(intVal=p - 1).gcd(ebv)) == 1) and
                   (int(BitVector(intVal=q - 1).gcd(ebv)) == 1))):
            c = True
        else:
            nbv = BitVector(intVal=p * q, size=256)
            n = int(nbv)
            if (int(n123[0].gcd(nbv)) == 1) and (int(
                    n123[1].gcd(nbv)) == 1) and (int(n123[2].gcd(nbv)) == 1):
                #print count
                n123[count] = nbv
                count = count + 1
                if count >= 3:
                    c = False
                else:
                    c = True

    return n123
コード例 #21
0
 def get_bit_vector(self, bucket: numpy.ndarray) -> BitVector:
     bit_vector = BitVector(self.size_of_bucket)
     for i in range(self.size_of_bucket):
         if bucket[
                 i] >= self.support:  # if the bucket count meets the threshold set vector
             bit_vector.set_bit(i)  # set the bit vector to true
     return bit_vector
コード例 #22
0
ファイル: lowmc.py プロジェクト: ThorKn/Python-Picnic
    def __apply_sbox(self):
        result = BitVector(size=self.blocksize)
        state_copy = self.__state.deep_copy()

        # Copy the identity part of the message
        result_ident = state_copy[(3 * self.number_sboxes):self.blocksize]

        # Substitute the rest of the message with the sboxes
        # ----------------------------------------------------
        # ATTENTION: The 3-bit chunks seem to be reversed
        # in the Picnic-Ref-Implementation, compared to the
        # LowMC-Ref-Implementation and the original LowMC-paper.
        # Example: state[0:3]='001' becomes '100' then gets sboxed
        # to '111' and reversed again for the state-update.
        # ----------------------------------------------------
        state_copy = self.__state[0:(3 * self.number_sboxes)]
        result_sbox = BitVector(size=0)
        for i in range(self.number_sboxes):
            state_index = (3 * i)
            state_3_bits = state_copy[state_index:state_index + 3].reverse()
            sbox_3_bits = BitVector(intVal=self.__sbox[int(state_3_bits)],
                                    size=3).reverse()
            result_sbox = result_sbox + sbox_3_bits

        result = result_sbox + result_ident
        self.__state = result
コード例 #23
0
ファイル: fcs.py プロジェクト: cburkert/fuzzy-commitment
    def _commit_raw(self, message: bytes, witness: BitVector) -> 'Commitment':
        """Commit on a raw binary message.

        Args:
            message: A binary message to commit to.
            witness: A witness to the commitment.

        Returns:
            A Commitment.

        Raises:
            ValueError: Witness is too long.
        """
        if len(witness) > self._witlen:
            raise ValueError("Witness exceeds the given maximum length "
                             f"({len(witness)}>{self._witlen}).")
        ecc = self._bch.encode(message)
        codeword = message + ecc
        codeword_bv = BitVector(hexstring=codeword.hex())
        # The codeword needs to be larger than or equally long as the witness
        # to maintain the HIDE property of the commitment.
        assert len(codeword_bv) >= len(witness)
        # Reverse BitVectors for xor-ing to achieve right-padding
        # of the witness. This is to minimize the errors introduced
        # to the parity (ecc) which leads to indeterministic
        # false-positive verifications.
        commitment = Commitment(
            hashlib.sha256(message).digest(),
            (codeword_bv.reverse() ^ witness.reverse()).reverse(),
        )
        return commitment
コード例 #24
0
ファイル: AES.py プロジェクト: sransara/rocket-science
def decrypt(keyschedule):
    # place to store state array
    rstate = [[0 for i in xrange(0, 4)] for i in xrange(0, 4)] 

    bvfile = BitVector(filename=encout)
    fout = open(dectxt, "w")

    while (bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(128)
        bit_block.pad_from_right(128 - len(bit_block))

        # init state array
        for i in xrange(0, 4):
            for j in xrange(0, 4):
                sp = (i * 32) + (j * 8)
                rstate[j][i] = bit_block[sp:sp + 8]

        add_round_key(rstate, keyschedule[56:60])

        for i in xrange(1, 14):
            invshift_rows(rstate)
            invsub_bytes(rstate)
            add_round_key(rstate, keyschedule[i*4:((i+1)*4)])
            invmix_cols(rstate)

        invshift_rows(rstate)
        invsub_bytes(rstate)
        add_round_key(rstate, keyschedule[0:4])

        for i in xrange(0, 4):
            for j in xrange(0, 4):
                rstate[i][j].write_to_file(fout)

    fout.close()
コード例 #25
0
def ais6tobitvecSLOW(str6):
    """Convert an ITU AIS 6 bit string into a bit vector.  Each character
    represents 6 bits.  This is for text sent within ais messages


    @note: If the original BitVector had ((len(bitvector) % 6 > 0),
    then there will be pad bits in the str6.  This function has no way
    to know how many pad bits there are.

    @bug: Need to add pad bit handling

    @param str6: ASCII that as it appears in the NMEA string
    @type str6: string
    @return: decoded bits (not unstuffed... what do I mean by
    unstuffed?).  There may be pad bits at the tail to make this 6 bit
    aligned.
    @rtype: BitVector
    """
    bvtotal = BitVector(size=0)

    for c in str6:
	c = ord(c)
	val = c - 48
	if val>=40: val -= 8
	bv = None
	#print 'slow: ',c,val
	if 0==val:
	    bv = BitVector(size=6)
	else:
	    bv = setBitVectorSize(BitVector(intVal=val),6)
	    #bv = BitVector(intVal=val,size=6)  # FIX: I thought this would work, but it is more than 6 bits?
	bvtotal += bv
    return bvtotal
コード例 #26
0
ファイル: city_ctrl.py プロジェクト: theGreenJedi/freeciv-bot
    def handle_city_info(self, packet):
        """
          The city_info packet is used when the player has full information about a
          city, including it's internals.

          It is followed by web_city_info_addition that gives additional
          information only needed by Freeciv-web. Its processing will therefore
          stop while it waits for the corresponding web_city_info_addition packet.
        """
        #/* Decode the city name. */
        packet['name'] = urllib.unquote(packet['name'])

        #/* Decode bit vectors. */
        packet['improvements'] = BitVector(bitlist = byte_to_bit_array(packet['improvements']))
        packet['city_options'] = BitVector(bitlist = byte_to_bit_array(packet['city_options']))

        if packet['id'] not in self.cities:
            self.cities[packet['id']] = packet
            """
            if (C_S_RUNNING == client_state() and !observing and benchmark_start == 0
                and client.conn.playing != None and packet['owner'] == client.conn.playing.playerno) {
              show_city_dialog_by_id(packet['id'])
            }
            """
        else:
            self.cities[packet['id']].update(packet)


        self.map_ctrl.set_tile_worked(packet)
コード例 #27
0
def is_palindrome_perm_bitvector(phrase: str) -> bool:
    ''' Uses a bitvector to trace the odd or eveness of
    the frequency count for each char '''

    phrase = phrase.replace(' ', '').lower()
    print(phrase)

    # E.g. using intVal (integer value) of 7 would give 00...111
    bv = BitVector(intVal=0, size=26)

    for char in phrase:
        # Calculate the place in alphabet for the char,
        # and flip/xor 1 the bit at that place
        ordinal = ord(char) - 96 - 1
        bv[ordinal] = bv[ordinal] ^ 1
    ''' Some binary number Fu... if there is only one bit set to 1, then
    the value of that vector when ANDed (&) with that vector minus 1 will be 0. 
    E.g. 01000 - 00001 = 00111;  01000 & 00111 = 00000'''

    # max(..) is needed as the entire vector may be all zeros
    bv_minus_one = BitVector(intVal=max(int(bv) - 1, 0), size=26)
    ''' Or you could just use the built-in count_bits() method, but where's 
    the fun that. Either random selection should always pass the tests here '''
    ''' For readability, define two booleans for random selection '''
    one_or_zero = bv.count_bits() in (0, 1)
    bv_and_minus_one = int(bv & bv_minus_one) == 0

    return random.choice([one_or_zero, bv_and_minus_one])
コード例 #28
0
ファイル: base.py プロジェクト: nessdoor/RVlyzer
        def __init__(self, size, symbol: str = None, value: int = None):
            """
            Instantiate an immediate constant of the specified size and value, identified by a symbol.

            :param size: the size in bits of the constant
            :param symbol: the symbol identifying the constant, if any
            :param value: the integer value of the constant, if any
            :raise ValueError: when both symbol and value are left unspecified
            """

            if symbol is None and value is None:
                raise ValueError("Constant must be symbolic or have a value")

            self._size = size
            self._symbol = symbol

            if value is not None:

                # Prepare the mask for cutting the supplied value's bit representation to the specified size
                mask = 0
                for f in range(0, size):
                    mask += 2**f

                value = value & mask
                self._value = BitVector(intVal=value, size=size)

                # Sizes must be coherent
                assert self._size == len(self._value)
            else:
                self._value = None
コード例 #29
0
    def encode(self, image_path, message):
        """
        Encode message into image, save it to same directory, and return modified image
        :param image_path: Path to target image
        :param message: Message to encode
        :return: Modified image converted to RGB values
        """
        if image_path.strip()[-1] is '\\' or image_path.strip(
        )[-1] is '/':  # Strip trailing slashes ( \ or / )
            image_path = image_path[:-1]

        head, tail = os.path.split(image_path)
        image_name, file_type = tail.split(".")
        image = Image.open(image_path)

        if self.__can_fit__(image, message):
            image_rgb = image.convert("RGB")
            message_bits = BitVector(textstring=message)
            message_bits.pad_from_right(
                16)  # Add 0x0000 as padding to represent NULL

            self.__swap_bits__(image_rgb, message_bits)
            image_rgb.save(head + "/" + image_name + "encoded." +
                           file_type)  # Save new image to original directory
            return image_rgb
        else:
            raise EncodingError("The image not big enough for message")
コード例 #30
0
ファイル: dacm.py プロジェクト: SARAD-GmbH/data_collector
 def _read_cycle_continue(self):
     """Get description of subsequent cycle intervals."""
     reply = self.get_reply([b"\x07", b""], 16)
     if reply and not len(reply) < 16:
         logger().debug("Get information about cycle interval successful.")
         try:
             seconds = int.from_bytes(reply[0:4],
                                      byteorder="little",
                                      signed=False)
             bit_ctrl = BitVector(rawbytes=reply[4:8])
             value_ctrl = BitVector(rawbytes=reply[8:12])
             rest = BitVector(rawbytes=reply[12:16])
             return {
                 "seconds": seconds,
                 "bit_ctrl": bit_ctrl,
                 "value_ctrl": value_ctrl,
                 "rest": rest,
             }
         except TypeError:
             logger().error("TypeError when parsing the payload.")
             return False
         except ReferenceError:
             logger().error("ReferenceError when parsing the payload.")
             return False
         except LookupError:
             logger().error("LookupError when parsing the payload.")
             return False
         except Exception:  # pylint: disable=broad-except
             logger().error("Unknown error when parsing the payload.")
             return False
     logger().debug("Get info about cycle interval failed.")
     return False
コード例 #31
0
def Encode(string, bit_size=None):
    """Convert a string to a BitVector.
  
    TODO(schwehr): Pad with "@" to reach requested bitSize.
  
    Args:
      string: str to encode.
      bit_size: integer: multiple of 6 size of the resulting bits.
  
    Returns:
      String representing the bits encoded as an AIS VDM armored characters.
    """
    if bit_size:
        assert bit_size % 6 == 0
    bv = BitVector(size=0)
    for i in range(len(string)):
        bv += character_bits[string[i]]
    if bit_size:
        if bit_size < len(bv):
            logging.error('ERROR:  Too many bits in string: "%s %s %s"',
                          string, bit_size, len(bv))
            assert False
        extra = bit_size - len(bv)
        bv += BitVector(size=extra)

    return bv
コード例 #32
0
def bvFromSignedInt(intVal, bitSize=None):
    '''
    Create a twos complement BitVector from a signed integer.  Not that 110 and 10 are both -2.

    Positives must have a '0' in the left hand position.

    Negative numbers must have a '1' in the left hand position.

    @param intVal: integer value to turn into a bit vector
    @type intVal: int
    @param bitSize: optional size to flush out the number of bits
    @type bitSize: int
    @return: A Bit Vector flushed out to the right size
    @rtype: BitVector
    '''
    bv = None
    if None == bitSize:
        bv = BitVector(intVal=abs(intVal))
    else:
        bv = setBitVectorSize(BitVector(intVal=abs(intVal)), bitSize - 1)
        if (bitSize - 1 != len(bv) and bv[0] != 1 and bv[-1] != 0):
            print('ERROR: bitsize not right')
            print('  ', bitSize - 1, len(bv))
            assert (False)
        if len(bv) == bitSize and bv[0] == 1:
            return bv
    if intVal >= 0:
        bv = BitVector(intVal=0) + bv
    else:
        bv = subone(bv)
        bv = ~bv
        bv = BitVector(intVal=1) + bv
    return bv
コード例 #33
0
ファイル: average.py プロジェクト: sransara/rocket-science
def crypt_modified(inputf_name, key, which_block, which_bit):
    # Modified crypt for test with plain txt changes
    # which_block: to toggle `which_bit` in which block

    allblocks = []
    bvfile = BitVector(filename=inputf_name)
    round_keys = [get_round_key(key, rnum) for rnum in xrange(0, 16)]

    block = 0 # Keep count of 64 Bit Blocks
    while(bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(64)
        if block ==  which_block:
            bit_block[which_bit] = bit_block[which_bit] ^ 1
        # pad if bit_block size is less than 64 bits 
        bit_block.pad_from_right(64 - len(bit_block))

        # Perform 16 rounds 
        for round in xrange(0, 16):
            bit_block = crypt_round(bit_block, round_keys[round])

        LE, RE = bit_block.divide_into_two()
        bit_block = RE + LE
        allblocks.append(bit_block)
        block += 1

    bvfile.close_file_object()
    return allblocks
コード例 #34
0
ファイル: AES.py プロジェクト: sransara/rocket-science
def mix_cols(state):
    mod = BitVector(bitstring='100011011')
    bv2 = BitVector(hexstring='2')
    bv3 = BitVector(hexstring='3')
    for j in xrange(0, 4): # to select col
        s0 = state[0][j]
        s1 = state[1][j]
        s2 = state[2][j]
        s3 = state[3][j]

        sp0 = bv2.gf_multiply_modular(s0, mod, 8) ^ bv3.gf_multiply_modular(s1, mod, 8) ^ s2 ^ s3 
        sp1 = s0 ^ bv2.gf_multiply_modular(s1, mod, 8) ^ bv3.gf_multiply_modular(s2, mod, 8) ^ s3
        sp2 = s0 ^ s1 ^ bv2.gf_multiply_modular(s2, mod, 8) ^ bv3.gf_multiply_modular(s3, mod, 8)
        sp3 = bv3.gf_multiply_modular(s0, mod, 8) ^ s1 ^ s2 ^ bv2.gf_multiply_modular(s3, mod, 8)

        state[0][j] = sp0
        state[1][j] = sp1
        state[2][j] = sp2
        state[3][j] = sp3
コード例 #35
0
ファイル: average.py プロジェクト: sransara/rocket-science
def crypt(inputf_name, key):
    allblocks = []
    bvfile = BitVector(filename=inputf_name)
    round_keys = [get_round_key(key, rnum) for rnum in xrange(0, 16)]
    while(bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(64)
        
        # pad if bit_block size is less than 64 bits 
        bit_block.pad_from_right(64 - len(bit_block))

        # Perform 16 rounds 
        for round in xrange(0, 16):
            bit_block = crypt_round(bit_block, round_keys[round])

        LE, RE = bit_block.divide_into_two()
        bit_block = RE + LE
        allblocks.append(bit_block)

    bvfile.close_file_object()
    return allblocks
コード例 #36
0
ファイル: hw06.py プロジェクト: sransara/rocket-science
def encrypt(inputf_name, outputf_name):
    bvfile = BitVector(filename=inputf_name)
    outf = open(outputf_name, "wb")

    while(bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(128)
        
        # pad if bit_block size is less than 128 bits 
        if len(bit_block) != 128:
            b_newline = '00001010'
            b_string = str(bit_block) + b_newline * ((128 - len(bit_block)) / 8)
            bit_block = BitVector(bitstring=b_string)
            assert (len(bit_block) == 128), "Bitvec bitstring error"

        # prepend with 0s
        bit_block.pad_from_left(128)
        out = mod_exp(int(bit_block), e, n) 
        bit_out = BitVector(intVal=out, size=256)
        bit_out.write_to_file(outf)

    outf.close()
    bvfile.close_file_object()
コード例 #37
0
ファイル: bloom_filter.py プロジェクト: michael-ruan/crawler
class BloomFilter(object):
    def __init__(self, array_size, hash_count):
        self.size = array_size                  #the size of bit array
        self.hash_count = hash_count            #the number of probes for each item
        self.bit_array = BitVector(size = array_size)

    def add(self, item):
        exist = True
        for seed in xrange(self.hash_count):
            result = mmh3.hash(item, seed) % self.size
            if self.bit_array[result] == 0:
                self.bit_array[result] = 1
                exist = False
        return exist

    def lookup(self, item):
        for seed in xrange(self.hash_count):
            result = mmh3.hash(item, seed) % self.size
            if self.bit_array[result] == 0:
                return False
        return True

    def __contains__(self, item):
        self.lookup(item)

    def __add__(self, bf):
        self.bit_array = self.bit_array | bf.bit_array
        return self

    def clear_all(self):
        self.bit_array.reset(0)

    def set_bit_array(self, ba):
        self.bit_array = ba

    def export_bloom(self, filename):
        with open(filename, 'wb') as f:
            f.write(str(self.size) + ":" + str(self.hash_count) + ":" + self.bit_array.get_bitvector_in_hex())
コード例 #38
0
ファイル: average.py プロジェクト: sransara/rocket-science
def feistal(bitblock, key):
    # Expansion Permutaion
    bits = []
    for i in xrange(0, 32, 4):
        bits.append(bitblock[i - 1])
        bits.extend(bitblock[i + j] for j in xrange(0, 4))
        bits.append(bitblock[(i + 4) % 32])
    bitblock = BitVector(bitlist=bits)

    # XOR with Round key 
    bitblock = bitblock ^ key

    # Sub with S-Box 
    bits = ''
    for sbnum in xrange(0, 8):
        word  = bitblock[(sbnum * 6):(sbnum * 6) + 6]
        row = BitVector(bitlist=[word[-1], word[0]]).intValue()
        col = word[1:-1].intValue()
        bits += str(BitVector(intVal=sboxes[sbnum][row][col], size=4))
    bitblock = BitVector(bitstring=bits)

    bitblock = bitblock.permute(pbox)
    return bitblock
コード例 #39
0
ファイル: a51.py プロジェクト: 0x0d/TWILIGHTVEGETABLE
 def __init__(self, length, taps, middle_bit, name=""):
     """
     length - length of the register in bits
     taps - feedback taps, for clocking the shift register.
            These correspond to the primitive polynomial
            Example polynomials from A5/1:
            x**19 + x**5 + x**2 + x + 1, x**22 + x + 1,
            or x**23 + x**15 + x**2 + x + 1
     middle_bit - middle bit of each of the three shift registers, for clock control
     name - name of LSFR - for print()
     """
     self.taps = taps
     self.length = length
     self.name = name
     self.value = BitVector(size = length);
     self.clk_bit_nr = length-middle_bit-1
コード例 #40
0
ファイル: hw06.py プロジェクト: sransara/rocket-science
def decrypt(inputf_name, outputf_name):
    bvfile = BitVector(filename=inputf_name)
    outf = open(outputf_name, "wb")

    while(bvfile.more_to_read):
        bit_block = bvfile.read_bits_from_file(256)
        assert (len(bit_block) == 256), "Bitblock is not long enough"
        out = super_power(int(bit_block), d, n, p, q)
        bit_out = BitVector(intVal=out, size=256)
        # remove prepended 0s
        bit_out = bit_out[128:]
        bit_out.write_to_file(outf)

    outf.close()
    bvfile.close_file_object()
コード例 #41
0
ファイル: a51.py プロジェクト: 0x0d/TWILIGHTVEGETABLE
class lsfr:
    def __init__(self, length, taps, middle_bit, name=""):
        """
        length - length of the register in bits
        taps - feedback taps, for clocking the shift register.
               These correspond to the primitive polynomial
               Example polynomials from A5/1:
               x**19 + x**5 + x**2 + x + 1, x**22 + x + 1,
               or x**23 + x**15 + x**2 + x + 1
        middle_bit - middle bit of each of the three shift registers, for clock control
        name - name of LSFR - for print()
        """
        self.taps = taps
        self.length = length
        self.name = name
        self.value = BitVector(size = length);
        self.clk_bit_nr = length-middle_bit-1

    def mix(self, liczba):
        """Read value from LSB to MSB and add each bit to LSFR's feedback"""
        for key_bit in reversed(liczba):
            bit = key_bit
            self.clock(bit)

    def clock(self, bit=False):
        """Clock LSFR. Can add value of bit to feedback."""
        for tap in self.taps:
            bit_nr = self.length - tap - 1
            bit = bit ^ self.value[bit_nr]
        self.value << 1
        self.value[self.length-1] = bit

    def out(self):
        """Clock LSFR. Can add value of bit to loopback."""
        return self.value[0]

    def clk_bit(self):
        """Return clocking bit."""
        return self.value[self.clk_bit_nr]

    def set_value(self, value):
        """Set internal state of LSFR."""
        self.value = BitVector(size=self.length, intVal=value)

    def __str__(self):
        return "%s:%X" %  (self.name, self.value.intValue())
コード例 #42
0
ファイル: bloom_filter.py プロジェクト: michael-ruan/crawler
 def __init__(self, array_size, hash_count):
     self.size = array_size                  #the size of bit array
     self.hash_count = hash_count            #the number of probes for each item
     self.bit_array = BitVector(size = array_size)
コード例 #43
0
ファイル: a51.py プロジェクト: 0x0d/TWILIGHTVEGETABLE
 def gen_block(self,size):
     out = BitVector(size=0)
     for i in xrange(0, size):
         self._clock_regs()
         out =   out + BitVector(intVal = int(self._out_bit()))
     return out.intValue()
コード例 #44
0
ファイル: a51.py プロジェクト: 0x0d/TWILIGHTVEGETABLE
 def set_value(self, value):
     """Set internal state of LSFR."""
     self.value = BitVector(size=self.length, intVal=value)
コード例 #45
0
ファイル: hw06.py プロジェクト: sransara/rocket-science
# Samodya Abeysiriwardane
# ECE 404 HW #6
# RSA block cipher

import sys
from BitVector import BitVector


# P, Q generated using modified PrimeGenerator.py
# PrimeGenerator.py was modified to generate prime-1 coprime e
p = 332302551650268460897954734536272420319
q = 258222644969751264151459428110328891689
e = 65537
# d = 51045946630242965074234865575892110109352763218080182137347987188415402400657

bv_p = BitVector(intVal=p)
bv_q = BitVector(intVal=q)
bv_pi = bv_p.multiplicative_inverse(bv_q)
bv_qi = bv_q.multiplicative_inverse(bv_p)
pi = int(bv_pi) # p inverse mod q
qi = int(bv_qi) # q inverse mod p

n = p * q
bv_n = BitVector(intVal=n)
tn = (p - 1) * (q - 1)
bv_tn = BitVector(intVal=tn)
bv_e = BitVector(intVal=e)
bv_d = bv_e.multiplicative_inverse(bv_tn)
d = int(bv_d)

def mod_exp(a, b, n):
コード例 #46
0
ファイル: generator.py プロジェクト: e1ven/HaShrink
filename = 'sinewave.mp3'

originalhash = hashfile(path + filename)
originalbytesize = os.path.getsize(path + filename)
originalbitsize = originalbytesize * 8

print("Looking for files of size: " + str(originalbitsize))


#iterate through each combination

validhash = 0
validmp3 = 0

for bitlist in itertools.product([0,1],repeat=originalbitsize):
	bv = BitVector(bitlist=bitlist)
	newpath = path + 'testfile.mp3'
	testfile = open(newpath,'wb')
	bv.write_to_file(testfile)
	testfile.close()
	newhash = hashfile(newpath)
	if newhash == originalhash:
		goodpath = path + 'candidate' + str(validhash) +  '.mp3'
		print("Possible Candidate at " + goodpath)
		os.rename(newpath,goodpath)
                if idmp3.isMp3Valid(goodpath):
                    mp3path = path + '-validmp3-' + str(validmp3) +  '.mp3'
                    print("Possible mp3 at " + mp3path)
                    os.rename(goodpath,mp3path)
                    validmp3 += 1
                else:
コード例 #47
0
ファイル: sbox.py プロジェクト: PSOCER/de2i150_ECCDH3DES
with open('s-box-tables.txt') as f:
    array = []

    for line in f:                                          # for every line in file
        if len(line) > 6:                                   # if its a line with entries we care about
            array.append([int(x) for x in line.split()])    # add to giant array

s_box = []
for i in range(0, 32, 4):
    s_box.append([array[k] for k in range(i, i + 4)])       # form into usable sboxes



for chunk in range(8):
    print ("case(input_wires[%d:%d])" % (6*chunk , 6*(chunk+1) - 1 ))
    
    for i in range(64):
        i_bv = BitVector(intVal=i,size=6)
        two_bit = i_bv.permute([0, 5])                           # row index
        four_bit = i_bv[1:5]    

        row = int(two_bit)
        col = int(four_bit)

        s_box_val = s_box[chunk][row][col]

        print ("    6'b%06s: output_wires[%d:%d] = 4'd%d;"%(i_bv, chunk*4,(chunk+1)*4 - 1,  s_box_val))
    print ("endcase\n")