def build(n, l, p, q):
            c = BitVector(size=0)
            for i in range(self.k):
                for j in range(self.k):
                    if l == self.h - 1:
                        c = c + BitVector(intVal=graph[p + i][q + j])
                    else:
                        c = c + build(n / self.k, l + 1, p + i *
                                      (n / self.k), q + j * (n / self.k))

            if c == BitVector(size=self.k2):
                return BitVector(intVal=0)

            temp[l] += c
            return BitVector(intVal=1)
Beispiel #2
0
 def RSA_encrypt(self):
     f = open("encrypt_hex.txt", 'a')
     FILEOUT = open(sys.argv[3], 'a')
     self.fix_file(sys.argv[2])
     bv = BitVector(filename=sys.argv[2])
     while bv.more_to_read:
         bit_block = bv.read_bits_from_file(128)
         bit_block.pad_from_right(128 - len(bit_block))
         bit_block.pad_from_left(128)
         encrypted_int = pow(int(bit_block), self.e, self.n)
         encrypted = BitVector(intVal=encrypted_int, size=256)
         encrypted.write_to_file(FILEOUT)
         f.write(encrypted.get_hex_string_from_bitvector())
     FILEOUT.close()
     return
Beispiel #3
0
def gee(keyword, round_num_constant, byte_sub_table):
    '''
    This is the g() function you see in Figure 4 of Lecture 8.
    '''
    rotated_word = keyword.deep_copy()
    rotated_word << 8
    newword = BitVector(size=0)
    for i in range(4):
        newword += BitVector(intVal=byte_sub_table[rotated_word[8 * i:8 * i +
                                                                8].intValue()],
                             size=8)
    newword[:8] ^= round_num_constant
    round_num_constant = round_num_constant.gf_multiply_modular(
        BitVector(intVal=0x02), AES_modulus, 8)
    return newword, round_num_constant
Beispiel #4
0
    def __read_constants(self):
        with open(self.filename, 'r') as matfile:
            const_data = matfile.read()

        const_data_split = const_data.split('\n')

        # Check for correct parameters and file length
        params = const_data_split[0:3]
        assert params[0] == str(
            self.blocksize), "Wrong blocksize in data file!"
        assert params[1] == str(self.keysize), "Wrong keysize in data file!"
        assert params[2] == str(
            self.number_rounds), "Wrong number of rounds in data file!"
        assert (len(const_data_split) - 1) == \
        3 + (((self.number_rounds * 2) + 1) * self.blocksize) + self.number_rounds,\
        "Wrong file size (number of lines)"

        # Linear layer matrices
        lines_offset = 3
        lines_count = self.number_rounds * self.blocksize
        lin_layer = const_data_split[lines_offset:(lines_offset + lines_count)]
        for r in range(self.number_rounds):
            mat = []
            for s in range(self.blocksize):
                bv = BitVector(bitstring=lin_layer[(r * self.blocksize) + s])
                mat.append(bv)
            self.__lin_layer.append(mat)

        # Round constants
        lines_offset += lines_count
        lines_count = self.number_rounds
        round_consts = const_data_split[lines_offset:(lines_offset +
                                                      lines_count)]
        for line in round_consts:
            self.__round_consts.append(BitVector(bitstring=line))

        # Round key matrices
        lines_offset += lines_count
        lines_count = (self.number_rounds + 1) * self.blocksize
        round_key_mats = const_data_split[lines_offset:(lines_offset +
                                                        lines_count)]
        for r in range(self.number_rounds + 1):
            mat = []
            for s in range(self.blocksize):
                mat.append(
                    BitVector(bitstring=round_key_mats[(r * self.blocksize) +
                                                       s]))
            self.__round_key_mats.append(mat)
    def __init_edges_attributes(self):
        """
        Initializes the edges attributes.

        Before the compression process, all the edges in the graph are
        deductive and have color 0.

        The bit vector of each edge has size equal to the number of
        sub-formulas in the proof.
        """
        for (u, v) in self.graph.get_edges():
            try:
                color = self.graph.get_edge_attribute(u, v, ProofGraph.COLOR)
            except EdgeAttributeGraphError:
                color = None
            if color:
                self.graph.remove_edge(u, v)

        qty_formulas = len(self.formulas_index)
        for (u, v) in self.graph.get_edges():
            self.graph.set_edge_attribute(u, v, ProofGraph.COLOR, 0)
            self.graph.set_edge_attribute(u, v, ProofGraph.ANCESTOR, False)
            self.graph.set_edge_attribute(u, v, ProofGraph.COLLAPSED, False)
            self.graph.set_edge_attribute(u, v, ProofGraph.LAMBDA_COLORS, [])
            vector = BitVector(size=qty_formulas)
            self.graph.set_edge_attribute(u, v, ProofGraph.DEPENDENCIES,
                                          vector)
Beispiel #6
0
    def __init__(self, bits, size=None, unknown=False):
        self.bits = None
        self.is_tensor = False

        if isinstance(bits, list):
            self.bits = bits
        elif isinstance(bits, int):
            if size is None:
                err = '"size" must be provided when initializing with int'
                raise RuntimeError(err)
            if SymBitVec.tensor_mode:
                bits = self._int_to_tensor(bits, size, unknown)
            else:
                bits = BitVector(intVal=bits, size=size)

        if isinstance(bits, torch.Tensor):
            self.bits = bits
            self.is_tensor = True
        elif isinstance(bits, BitVector):
            self.bits = [
                Bit(bits[i], unknown, unknown) for i in range(len(bits))
            ]

        if self.bits is None:
            err = 'SymBitVec: Unsupported type {}'.format(type(bits))
            raise RuntimeError(err)
Beispiel #7
0
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
Beispiel #8
0
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()
Beispiel #9
0
    def encrypt(self, message):

        message = self.add_encoding(message)

        columns = [
            BitVector(size=self.key_length,
                      intVal=self.random.getrandbits(self.key_length))
            for _ in range(self.key_length)
        ]

        # compute the noiseless mask
        y = matrix_vector_multiply(columns, self.key)

        # mask the message
        print(y.int_val())
        y ^= message
        print(y.int_val())

        # add noise: make a third of all equations false
        for i in range(self.key_length // 3):
            noise_index = self.random.randrange(inverse_error_probability)
            y[i * 3 + noise_index] ^= 1

        columns = [bitvector_to_bytes(c) for c in columns]
        columns = b"".join(columns)

        return columns + bitvector_to_bytes(y)
Beispiel #10
0
    def fromSeq(self, seq):
        #run berlekamp massey to determine primitive polynomial
        L, c = berlekamp_massey(seq)

        #return Fibonacci LFSR parameters
        init_state = BitVector(bitlist=seq[:L][::-1])
        return init_state, Fibonacci(L, c[:L + 1])
Beispiel #11
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())
Beispiel #12
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
Beispiel #13
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
Beispiel #14
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
Beispiel #15
0
    def __call__(self):
        fixed_bit_vector = BitVector(size=self.length)

        for i in range(self.length):
            fixed_bit_vector[i] = random.random() < self.value_distribution

        return fixed_bit_vector
def gentable(min_code, max_code, data):
    actual_min = max_code
    actual_max = min_code

    for x in data:
        tokenrange = x[0].split('..')
        rangestart = int(tokenrange[0], base=16)
        rangeend = int(
            tokenrange[0] if len(tokenrange) == 1 else tokenrange[1], base=16)

        for code in range(rangestart, rangeend + 1):
            if code >= min_code and code <= max_code:
                if code < actual_min:
                    actual_min = code
                if code > actual_max:
                    actual_max = code
    numbits = (actual_max + 1) - actual_min
    if (numbits % 8) != 0:
        numbits += 8 - (numbits % 8)

    bits = BitVector(size=numbits)

    for x in data:
        tokenrange = x[0].split('..')
        rangestart = int(tokenrange[0], base=16)
        rangeend = int(
            tokenrange[0] if len(tokenrange) == 1 else tokenrange[1], base=16)

        for code in range(rangestart, rangeend + 1):
            if code >= min_code and code <= max_code:
                bit = code - actual_min
                bits[bit] = 1

    return printtable(actual_min, actual_max, bits)
Beispiel #17
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())
Beispiel #18
0
def invsub_bytes(state):
    for i in xrange(0, 4):
        for j in xrange(0, 4):
            [row, col] = state[i][j].divide_into_two()
            row = row.int_val()
            col = col.int_val()
            return BitVector(intVal=INVSBOX[row][col])
def findDuplicate(array: List[int]):
    vec = BitVector(size=32000)
    for num in array:
        if vec[num] != 0:
            print(num)
        else:
            vec[num] = 1
Beispiel #20
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")
Beispiel #21
0
        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
Beispiel #22
0
def ais6tobitvec(str6):
    '''Convert an ITU AIS 6 bit string into a bit vector.  Each character
    represents 6 bits.  This is the NMEA !AIVD[MO] message payload.

    @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.

    >>> print ais6tobitvec('6')
    000110

    >>> print ais6tobitvec('6b')
    000110101010

    >>> print ais6tobitvec('6bF:R')
    000110101010010110001010100010

    @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=6*len(str6))

    for pos in range(len(str6)):
	bv = decode[str6[pos]]
	start = pos*6
	for i in range(6):
	    bvtotal[i+start] = bv[i]
    return bvtotal
Beispiel #23
0
def float2bitvec(floatval):
    '''
    Get the IEEE floating point bits for a python float

    @bug: May have bite order backwards
    @type floatval: number
    @param floatval: number to convert to bits
    @rtype: BitVector
    @return: 32 bits
    @todo: Is there a faster way to do this?
    @see: U{struct module<http://www.python.org/doc/current/lib/module-struct.html>}
    '''
    s = struct.pack(
        '!f', floatval
    )  # FIX: Is this the right bight order?  Could easily be wrong!!!!
    i = struct.unpack('!I', s)[0]
    # print 'unpacked:',i
    # return setBitVectorSize(BitVector(intVal=i),32)

    # Old way...  since BitVector can't encode large intVals (>2^31)
    # FIX: make this go in one step now that bitvector 1.3 is out.
    bvList = []
    for i in range(4):
        bv1 = setBitVectorSize(BitVector(intVal=ord(s[i])), 8)
        # bv2 = BitVector(intVal=ord(s[i]),size=8)
        bvList.append(bv1)
    return joinBV(bvList)
def convert_solution_to_lfsrs(solution):
    """
        Converts the values from the Gauss algorithm to LFSR objects.
        :param solution: array with the values from the gauss algorithm
        :return register 1, 2 and 3 as LFSR object
    """
    r1_value = solution[R1_START_IN_SOLUTION:R1_END_IN_SOLUTION]
    r2_value = solution[R2_START_IN_SOLUTION:R2_END_IN_SOLUTION]
    r3_value = solution[R3_START_IN_SOLUTION:R3_END_IN_SOLUTION]
    r1 = LFSR(R1_SIZE, [], R1_TAPS, R1_MAJORITY_BITS, R1_NEGATED_BIT)
    r2 = LFSR(R2_SIZE, [], R2_TAPS, R2_MAJORITY_BITS, R2_NEGATED_BIT)
    r3 = LFSR(R3_SIZE, [], R3_TAPS, R3_MAJORITY_BITS, R3_NEGATED_BIT)
    r1.register = BitVector(bitlist=r1_value)
    r2.register = BitVector(bitlist=r2_value)
    r3.register = BitVector(bitlist=r3_value)
    return r1, r2, r3
def getEncBlocksFromHexString(h_str):
    cipher_sas = []
    for i in range(len(h_str) / 64):
        hex_str = h_str[i * 64:(i + 1) * 64]
        bv = BitVector(hexstring=hex_str)
        cipher_sas = cipher_sas + [bv]
    return cipher_sas
Beispiel #26
0
def constructBitVector(chromosome_coord_map, chromosome_length_map, chr_num):
    """Constructs a bit vector for an individual chromosome.

    Args:
        chromosome_coord_map (dict): map of chromosomes and desired coordinates. Key: (str) chromosome number. Value: (list) Desired coordinates 
        chromosome_length_map (dict): map of chromosomes to their lengths. Key: (str) chromosome number. Value: (int) Length of chromosome. 
        chr_num (str): chromosome number 

    Returns:
        BitVector: a bit vector representing regions in chromosome that exhibited unusual growth activity.
        0 for coordinates not associated with cell growth, 1 for coordinates associated with cell growth
    """

    #visual indicator for running purposes
    print("CHR NUM = " + str(chr_num))
    print("CHR Length = " + str(chromosome_length_map[chr_num]))

    currIndex = 0

    bv = BitVector(
        size=chromosome_length_map[chr_num]
    )  # initializes a bit vector of 0's of size of chromosome + 1

    coord_lst = chromosome_coord_map[chr_num]

    for i in range(0, len(coord_lst) - 1, 2):  #going through coordinate list
        start = coord_lst[i]  #start coordinate
        print(start)
        stop = coord_lst[i + 1]  #stop coordinate
        for i in range(start, stop + 1):
            bv[i] = 1

    return bv
Beispiel #27
0
def main(memsPath, refPath, gtfPath, errRate, outPath):
    RefSeq = list(SeqIO.parse(refPath, "fasta"))[0]

    ref, refLen, text, exPos = extractFromInfoFile(gtfPath + ".sg")
    bv = BitVector(text)

    out = open(outPath, "w")
    out.write("@HD\tVN:1.4\n")
    out.write("@SQ\tSN:{}\tLN:{}\n".format(ref, refLen))

    lastID = ""
    lastStart = -1
    lastCigar = ""
    for line in open(memsPath).readlines():
        strand, readID, err, mems, read = readLine(line)
        mems = extractMEMs(mems)

        start = getStart(mems[0], bv, exPos)
        flag = getFlag(strand, readID, lastID)

        cigar = getCIGAR(mems, RefSeq, bv, exPos, read, errRate, err)
        #Same alignment is not output twice
        if readID != lastID or start != lastStart or cigar != lastCigar:
            lastID = readID
            lastStart = start
            lastCigar = cigar
            out.write(
                "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\tNM:i:{}\n".format(
                    readID, flag, ref, start, 255, cigar, "*", 0, 0, read, "*",
                    err))

    out.close()
def make128BitVector(bv):
    l = int(len(bv))
    nbv = BitVector(textstring="\n")
    for i in range((128 - l) / 8):
        bv = bv + nbv
        #print len(nbv), len(bv)
    return bv
Beispiel #29
0
    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
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