Exemple #1
0
def InvShiftRows(bv):
    # The first row is left unchanged,
    # the second row is shifted to the right by one byte,
    # the third row to the right by two bytes,
    # and the last row to the right by three bytes
    #[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    # -> [0,13,10,7, 4,1,14,11, 8,5,2,15, 12,9,6,3]
    bv_out = BitVector(size=0)
    for i in range(4):
        a = 4 * i
        for j in range(4):
            b = a - 3 * j
            if b >= 0:
                bv_out += bv[b * 8:b * 8 + 8]
            else:
                bv_out += bv[(b + 15 + 1) * 8:(b + 15 + 1) * 8 + 8]
    return bv_out
Exemple #2
0
def InversemixColumns(matrix):
    MIXCOLUMNSD = [[0x0E, 0x0B, 0x0D, 0x09], [0x09, 0x0E, 0x0B, 0x0D],
                   [0x0D, 0x09, 0x0E, 0x0B], [0x0B, 0x0D, 0x09, 0x0E]]
    mixColumns = intToBitVector(MIXCOLUMNSD)
    endMatrix = BitVector(size=0)
    for i in range(4):
        for j in range(4):
            int0 = mixColumns[i][0]
            int1 = mixColumns[i][1]
            int2 = mixColumns[i][2]
            int3 = mixColumns[i][3]
            bitvec0 = int0.gf_multiply_modular(matrix[0][j], AES_modulus, 8)
            bitvec1 = int1.gf_multiply_modular(matrix[1][j], AES_modulus, 8)
            bitvec2 = int2.gf_multiply_modular(matrix[2][j], AES_modulus, 8)
            bitvec3 = int3.gf_multiply_modular(matrix[3][j], AES_modulus, 8)
            endMatrix += (bitvec0 ^ bitvec1 ^ bitvec2 ^ bitvec3)
    return endMatrix
Exemple #3
0
    def encrypt(self):

        # Encrypt input and add encrypted blocks to Object
        self.encrypted_blocks = self.encrypt_decrypt(range(16), self.plain_text_blocks)

        encrypted_bits = BitVector(size=0)

        # Put all the blocks into one long bitvector
        for block in self.encrypted_blocks:
            encrypted_bits = encrypted_bits + block

        self.encrypted_bits = encrypted_bits

        # Write out to the appropriate file
        FILEOUT = open(self.encrypted_file, 'wb')
        encrypted_bits.write_to_file(FILEOUT)
        FILEOUT.close()
Exemple #4
0
def gf_multiply(a, b):
    '''
    Using the arithmetic of the Galois Field GF(2^n), this function multiplies
    the bit pattern 'a' by the bit pattern 'b'.
    '''
    a_highest_power = a.length() - a.next_set_bit(0) - 1
    b_highest_power = b.length() - b.next_set_bit(0) - 1
    result = BitVector(size=a.length() + b.length())
    a.pad_from_left(result.length() - a.length())
    b.pad_from_left(result.length() - b.length())
    for i, bit in enumerate(b):
        if bit == 1:
            power = b.length() - i - 1
            a_copy = a.deep_copy()
            a_copy.shift_left(power)
            result ^= a_copy
    return result
Exemple #5
0
def shiftRows(bv):
    #(i) not shifting the first row of the state array;
    #(ii) circularly shifting the second row by one byte to the left;
    #(iii) circularly shifting the third row by two bytes to the left;
    #(iv) circularly shifting the last row by three bytes to the left.
    #[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    # -> [0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11]
    bv_out = BitVector(size=0)
    for i in range(4):
        a = 4 * i
        for j in range(4):
            b = a + 5 * j
            if b <= 15:
                bv_out += bv[b * 8:b * 8 + 8]
            else:
                bv_out += bv[(b - 15 - 1) * 8:(b - 15 - 1) * 8 + 8]
    return bv_out
Exemple #6
0
    def __init__(self, m, k):

        # Define global variables
        # m = size of the bloom filter
        # k = # of hashing functions

        self.m = m
        self.k = k

        # bit vector of 0 and 1
        self.bloom_filter = BitVector.BitVector(size=m)

        # number of elements added in the filter
        self.n_elements = 0

        # numberof probably duplicates found
        self.n_duplicates = 0
Exemple #7
0
def mix_columns(sa):
    ''' Mix columns on state array sa to return new state array '''
    # SEE LEC SLIDES 33-35
    state_array = copy.deepcopy(sa)
    new_sa = []
    matrix = [[2, 3, 1, 1], [1, 2, 3, 1], \
              [1, 1, 2, 3], [3, 1, 1, 2]]
    for i in range(4):
        col_collector = []
        for j in range(4):
            row_collector = BitVector.BitVector(intVal=0, size=8)
            for k in range(4):
                after_mult = gf_mult(state_array[i][k], matrix[j][k])
                row_collector = Xor(after_mult, row_collector)
            col_collector.append(row_collector)
        new_sa.append(col_collector)
    return new_sa
Exemple #8
0
def get_key_from_user():
    key = keysize = None
    if sys.version_info[0] == 3:
        keysize = int(input("\nAES Key size:  "))
        assert any(x == keysize for x in [128,192,256]), \
                                    "keysize is wrong (must be one of 128, 192, or 256) --- aborting"
        key = input("\nEnter key (any number of chars):  ")
    else:
        keysize = int(raw_input("\nAES Key size:  "))
        assert any(x == keysize for x in [128,192,256]), \
                                    "keysize is wrong (must be one of 128, 192, or 256) --- aborting"
        key = raw_input("\nEnter key (any number of chars):  ")
    key = key.strip()
    key += '0' * (keysize // 8 -
                  len(key)) if len(key) < keysize // 8 else key[:keysize // 8]
    key_bv = BitVector(textstring=key)
    return keysize, key_bv
Exemple #9
0
def GenerateSubTable(modeChar):
    #Table Generation Variables
    modulus_poly = BitVector(
        bitstring='100011011'
    )  #irreducible polynomial used in AES --> (x^8 + x^4 + x^3 + x + 1)
    byte_c = BitVector(bitstring='01100011')  #Encryption Mangle-Byte
    byte_d = BitVector(bitstring='00000101')  #Decryption Mangle-Byte
    scrambledBV = BitVector(size=8)
    #Initialize 16x16 Sub-Table with all 0 Bit-Vectors
    zeroBV = BitVector(size=8)
    LookUpTable = [[zeroBV.deep_copy() for x in range(16)] for y in range(16)]
    #Set Each Table Entry to Multiplicative Inverse (in GF(2^8)) of Bit-Vector Concatenation of Row and Column 4-bit Bit-Vectors
    for x in range(16):
        for y in range(16):
            rowBV = BitVector(intVal=x,
                              size=4)  #Creat Bit Vector for Row Value
            colBV = BitVector(intVal=y,
                              size=4)  #Creat Bit Vector for Column Value
            tableBV_entry = rowBV + colBV
            #Perform MI & Bit-Mangling on Table Entries
            #If Mode is Encryption...
            if modeChar == 'E':
                #Only find MI of all bit-vectors except 0
                if (x != 0) or (y != 0):
                    tableBV_entry = tableBV_entry.gf_MI(
                        modulus_poly,
                        8)  #Determine MI of table entry Bit-Vector
                for bit_ind in range(0, 8):
                    newBit = tableBV_entry[bit_ind] ^ tableBV_entry[
                        (bit_ind + 1) %
                        8] ^ tableBV_entry[(bit_ind + 2) % 8] ^ tableBV_entry[
                            (bit_ind + 3) % 8] ^ tableBV_entry[
                                (bit_ind + 4) % 8] ^ byte_c[bit_ind]
                    scrambledBV[bit_ind] = newBit
            #If Mode is Decryption...
            else:
                for bit_ind in range(0, 8):
                    newBit = tableBV_entry[(bit_ind + 6) % 8] ^ tableBV_entry[
                        (bit_ind + 3) % 8] ^ tableBV_entry[(bit_ind + 1) %
                                                           8] ^ byte_d[bit_ind]
                    scrambledBV[bit_ind] = newBit
                #Only find MI of all bit-vectors except 0
                if int(scrambledBV) != 0:
                    scrambledBV = scrambledBV.gf_MI(
                        modulus_poly,
                        8)  #Determine MI of table entry Bit-Vector
            LookUpTable[x][y] = copy.deepcopy(scrambledBV)
    return LookUpTable
Exemple #10
0
def generate_key(key):
    key64 = BitVector(hexstring=key)  # original 64-bit key
    key56 = key64.permute(pc_1)  #56-bit permutation by pc-1
    global k  #key container
    k = []  # instantiate array k
    rno = 1  #round no
    [c, d] = key56.divide_into_two()
    while (rno <= 16):
        if (rno == 1 or rno == 2 or rno == 9 or rno == 16):
            c << 1
            d << 1
        else:
            c << 2
            d << 2
        key56 = c + d
        key48 = key56.permute(pc_2)  #48-bit permutation by pc-2
        k.append(key48)  #add key to array k
        rno += 1  #increment round number
Exemple #11
0
def gen_key_schedule_192(key_bv):
    byte_sub_table = gen_subbytes_table()
    #  We need 52 keywords (each keyword consists of 32 bits) in the key schedule for
    #  192 bit AES.  The 192-bit AES uses the first four keywords to xor the input
    #  block with.  Subsequently, each of the 12 rounds uses 4 keywords from the key
    #  schedule. We will store all 52 keywords in the following list:
    key_words = [None for i in range(52)]
    round_constant = BitVector(intVal=0x01, size=8)
    for i in range(6):
        key_words[i] = key_bv[i * 32:i * 32 + 32]
    for i in range(6, 52):
        if i % 6 == 0:
            kwd, round_constant = gee(key_words[i - 1], round_constant,
                                      byte_sub_table)
            key_words[i] = key_words[i - 6] ^ kwd
        else:
            key_words[i] = key_words[i - 6] ^ key_words[i - 1]
    return key_words
Exemple #12
0
def lfsr(p_conexion, semilla, size_out):
    """Implementación de un LFSR
       
       Los coefs del p_conexión se introducen de mayor a menor y no el 1 final
    """

    # La semilla no debe tenerl el 1 final del c(D)
    out = bv.BitVector(size=size_out)
    r = 0

    while (r < size_out):
        out[0] = (p_conexion & semilla).count_bits() % 2
        semilla <<= 1
        semilla[-1] = out[0]
        out <<= 1
        r += 1

    return out
    def __init__(self,
                 size,
                 createAdjacency=False,
                 createSparseAdjacency=True):
        self.size = size
        self.board = biv.BitVector(size=size**2)
        if (createAdjacency):
            self.adjacencyMatrix = np.zeros((2**(size**2), 2**(size**2)),
                                            dtype=bool)
        else:
            self.adjacencyMatrix = None
        if (createSparseAdjacency):
            self.sparseAdjacencyMatrix = sparse.lil_matrix(
                (2**(size**2), 2**(size**2)), dtype=bool)
        else:
            self.sparseAdjacencyMatrix = None

        self.ID = BitBoard.getCounter()
Exemple #14
0
def gen_key_schedule_128(key_bv):
    byte_sub_table = gen_subbytes_table()
    #  We need 44 keywords in the key schedule for 128 bit AES.  Each keyword is 32-bits
    #  wide. The 128-bit AES uses the first four keywords to xor the input block with.
    #  Subsequently, each of the 10 round_nums uses 4 keywords from the key schedule. We will
    #  store all 44 keywords in the following list:
    key_words = [None for i in range(44)]
    round_num_constant = BitVector(intVal=0x01, size=8)
    for i in range(4):
        key_words[i] = key_bv[i * 32:i * 32 + 32]
    for i in range(4, 44):
        if i % 4 == 0:
            kwd, round_num_constant = gee(key_words[i - 1], round_num_constant,
                                          byte_sub_table)
            key_words[i] = key_words[i - 4] ^ kwd
        else:
            key_words[i] = key_words[i - 4] ^ key_words[i - 1]
    return key_words
Exemple #15
0
def substitute(right, key):
    mright = right.deep_copy()
    mright = mright.permute(exp_perm)
    mright = mright ^ key
    count = 0
    sv = []
    for i in range(0, 43, 6):
        t = mright[i:i + 6]
        r = str(t[0]) + str(t[5])
        c = t[1:5]
        x = s_boxes[count][int(r, 2)][int(c)]
        sv.append(BitVector(intVal=x, size=4))
        count += 1
    rsv = sv[0]
    for i in range(1, len(sv)):
        rsv = rsv + sv[i]
    rsv = rsv.permute(perm)
    return rsv
Exemple #16
0
    def __init__(self, amount=1 << 26):
        self.containerSize = (-1) * amount * cmath.log(0.001) / (
            cmath.log(2) * cmath.log(2))  #计算最佳空间大小
        self.containerSize = int(self.containerSize.real)  #取整

        self.hashAmount = cmath.log(2) * (self.containerSize) / (amount)
        self.hashAmount = int(self.hashAmount.real)

        self.container = BitVector.BitVector(size=int(
            self.containerSize))  #分配内存

        self.hashSeeds = find_prime(self.hashAmount)

        self.hash = []
        for i in range(int(self.hashAmount)):  #生成哈希函数
            self.hash.append(SimpleHash(self.containerSize, self.hashSeeds[i]))

        return
Exemple #17
0
def smarts_to_vector(tmp_lst):
    train_lst = []
    for template in tqdm(tmp_lst):
        express = template.split('>')
        # try:
        #     arr_tgt = preprocess(express[0].lstrip('(').rstrip(')'))
        #     arr_src = preprocess(express[-1])
        #     arr = np.concatenate((arr_tgt, arr_src))
        #     smiles_dict[arr] = template
        #     train_lst.append(arr)
        # except:
        #     wrong_cnt += 1

        arr_tgt = preprocess(express[0].lstrip('(').rstrip(')'))
        arr_src = preprocess(express[-1])
        arr = np.concatenate((arr_tgt, arr_src))
        train_lst.append(BitVector.BitVector(bitlist=arr))
    return train_lst
Exemple #18
0
 def __init__(self,
              capacity=1000000000,
              error_rate=0.00000001,
              conn=None,
              key='BloomFilter'):
     self.m = math.ceil(capacity * math.log2(math.e) *
                        math.log2(1 / error_rate))  # 需要的总bit位数
     self.k = math.ceil(math.log1p(2) * self.m / capacity)  # 需要最少的hash次数
     self.mem = math.ceil(self.m / 8 / 1024 / 1024)  # 需要的多少M内存
     self.blocknum = math.ceil(
         self.mem / 512)  # 需要多少个512M的内存块,value的第一个字符必须是ascii码,所有最多有256个内存块
     self.seeds = self.SEEDS[0:self.k]
     self.key = key
     self.N = 2**31 - 1
     self.redis = conn
     if not self.redis:
         # 默认如果没有redis连接,在内存中使用512M的内存块去重
         self.bitset = BitVector.BitVector(size=1 << 32)
Exemple #19
0
def subBytes(state):
	if(len(state)!=128):
		print "CRITICAL ERROR: State subsitution error in subBytes: vector is incorrect length"
	for x in range(16):
		j=x*8
		k=(x+1)*8		
		tempbyte = state[j:k]
		z = tempbyte.intValue()

		##Find substitution in rijndael sbox table
		subbyte = sbox[z]

		##Make a bitvector out of the sbox result
		temp2 = BitVector(intVal=subbyte, size=8)

		##Replace the byte
		state[j:k] = temp2
	return state
Exemple #20
0
def input_plaintext(is_file_input):
    global AES_input, pad_count_input

    if is_file_input:
        plaintext_file = open("./inputs/plaintext.in", "r")
        plaintext = plaintext_file.read()
        plaintext_file.close()
    else:
        plaintext = input("Enter plaintext: ")
        
    if (len(plaintext) % 16) != 0:
        pad_count_input = 16 - len(plaintext) % 16
        plaintext = plaintext + " " * pad_count_input
    elif len(plaintext) == 0:
        return False

    AES_input += BitVector(textstring=plaintext)
    return True
def newCSVtoBV(baseName, numFiles, numColumns):
    header = []
    for i in range(numColumns):
        title = "Column " + str(i + 1)
        header.append(title)
    toCompare = []
    for j in range(numFiles):
        csvName = "C:\\Users\Brielle\Documents\internship\Tables\\" + str(
            baseName) + str(j) + ".csv"
        if j == 0:
            head = header
        else:
            head = random.sample(header, random.randint(0, len(header)))
        with open(csvName, "w", newline="") \
                as f:
            writer = csv.writer(f)
            writer.writerow(head)
            f.close()
        toCompare.append(str(csvName))
    universalColumns = {}
    for table in toCompare:
        with open(table, "r") as f:
            reader = csv.reader(f)
            k = next(reader)
        for column in k:
            if column not in universalColumns:
                universalColumns[column] = len(universalColumns)
    allBVs = []
    for table in toCompare:
        bv = BitVector(size=len(universalColumns))
        with open(table, "r") as f:
            reader = csv.reader(f)
            k = next(reader)
        for column in k:
            bv[universalColumns[column]] = 1
        allBVs.append(bv)
    pklName = "C:\\Users\Brielle\Documents\internship\Tables\\" + str(
        baseName) + ".pkl"
    output = open(pklName, 'wb')
    pickle.dump(allBVs, output)
    output.close()
    #with open(pklName, 'rb') as f:
    #    allBVs = pickle.load(f)
    return allBVs
Exemple #22
0
def mixCols(statearray):
    mixed = [[0 for x in range(4)] for x in range(4)]

    for j in range(4):
        bv1 = statearray[0][j].gf_multiply_modular(BitVector(hexstring='02'), AES_modulus, 8)
        bv2 = statearray[1][j].gf_multiply_modular(BitVector(hexstring='03'), AES_modulus, 8)
        mixed[0][j] = bv1 ^ bv2 ^ statearray[2][j] ^ statearray[3][j]
    for j in range(4):
        bv1 = statearray[1][j].gf_multiply_modular(BitVector(hexstring='02'), AES_modulus, 8)
        bv2 = statearray[2][j].gf_multiply_modular(BitVector(hexstring='03'), AES_modulus, 8)
        mixed[1][j] = bv1 ^ bv2 ^ statearray[0][j] ^ statearray[3][j]
    for j in range(4):
        bv1 = statearray[2][j].gf_multiply_modular(BitVector(hexstring='02'), AES_modulus, 8)
        bv2 = statearray[3][j].gf_multiply_modular(BitVector(hexstring='03'), AES_modulus, 8)
        mixed[2][j] = bv1 ^ bv2 ^ statearray[0][j] ^ statearray[1][j]
    for j in range(4):
        bv1 = statearray[3][j].gf_multiply_modular(BitVector(hexstring='02'), AES_modulus, 8)
        bv2 = statearray[0][j].gf_multiply_modular(BitVector(hexstring='03'), AES_modulus, 8)
        mixed[3][j] = bv1 ^ bv2 ^ statearray[1][j] ^ statearray[2][j]
    return mixed
Exemple #23
0
def des(s_box, input_file, output_file, keys):
    FILEOUT = open(output_file, 'ab')
    bv = BitVector(filename=input_file)
    while (bv.more_to_read):
        bitvec = bv.read_bits_from_file(
            64)  ## assumes that your file has an integral
        leng = bitvec.length(
        )  ## multiple of 8 bytes. If not, you must pad it.
        pad = 64 - leng
        bitvec.pad_from_right(pad)
        [LE, RE] = bitvec.divide_into_two()
        for i in range(16):
            righty = RE.permute(expansion_permutation)
            resultxor = righty ^ keys[i]
            #s substitution
            temp_bv = BitVector(size=6)
            row_bv = BitVector(size=2)
            col_bv = BitVector(size=4)
            ini = 0
            fin = 6
            inf = 0
            fif = 4
            final_bv = BitVector(size=32)
            for k in range(8):
                temp_bv = resultxor[ini:fin]
                row_bv[0:1] = temp_bv[0:1]
                row_bv[1:2] = temp_bv[5:6]
                col_bv = temp_bv[1:5]
                row = row_bv.int_val()  #get row
                col = col_bv.int_val()  #get column
                #get stuff from sbox
                newd = s_box[k][row][col]
                temp = BitVector(intVal=newd)
                temp_leng = temp.length()
                lpad = 4 - temp_leng
                temp.pad_from_left(lpad)
                final_bv[inf:fif] = temp
                inf = inf + 4
                fif = fif + 4
                ini = ini + 6  #increase to the next thing
                fin = fin + 6  #increase to th next chunck
                #permutation with p box
            last_p = final_bv.permute(p_box_permutation)
            #xor with le result = RE
            temporal = RE
            RE = last_p ^ LE
            LE = temporal  #le equals old re
            #for loop done
            #put left + right on output file
        file_writebv = RE + LE
        file_writebv.write_to_file(FILEOUT)
Exemple #24
0
def crack(enc1Name, enc2Name, enc3Name, n_1_2_3Name, crackedName):
    with open(n_1_2_3Name) as file:
        nVal = []
        for _ in range(3):
            nVal.append(int(file.readline().strip()))

    fileNames = [enc1Name, enc2Name, enc3Name]
    message = []
    for each in fileNames:
        with open(each) as file:
            fromFile = file.read().strip()
            message.append(BitVector(hexstring=fromFile))
    # N values
    bigN_total = nVal[0] * nVal[1] * nVal[2]
    bigN = []
    bigN_vec = []

    bigN.append(nVal[1] * nVal[2])
    bigN_vec.append(BitVector(intVal=bigN[0]))

    bigN.append(nVal[0] * nVal[2])
    bigN_vec.append(BitVector(intVal=bigN[1]))

    bigN.append(nVal[0] * nVal[1])
    bigN_vec.append(BitVector(intVal=bigN[2]))

    # calculate inverse
    inverse = []
    for index in range(3):
        inverse.append(
            int(bigN_vec[index].multiplicative_inverse(
                BitVector(intVal=nVal[index]))))

    outputVec = BitVector(size=0)
    for index in range(0, len(message[0]), blockSize):
        cipher = []
        for lcv in range(3):
            cipher.append(int(message[lcv][index:index + blockSize]))
        m_3 = 0
        for lcv in range(3):
            m_3 += cipher[lcv] * bigN[lcv] * inverse[lcv]
        m_3 = int(m_3) % int(bigN_total)
        decrypted = solve_pRoot(3, m_3)
        outputVec += BitVector(intVal=decrypted, size=128)
    with open(crackedName, 'wb') as file:
        outputVec.write_to_file(file)
Exemple #25
0
def ErrorHandlingBB():
    errorFile = open("errorBB.txt", 'w')
    bvSize = len(paramset.BB)
    bitVect = BitVector.BitVector(size=bvSize)
    bitVect[-1] = 1
    for i in range(bvSize):
        bitVect >>= 1
        for trace in paramset.TEMPTRACE:
            num = 0
            BT = bitVect & trace
            if BT.count_bits() == 1:
                num += 0
        if num > ((paramset.BBPERC/100)*paramset.TEMPTRACE) \
            and paramset.BB[i] not in paramset.BBWITHOUTERR:
            paramset.BBWITHERR.add(paramset.BB[i])
    for errs in paramset.BBWITHERR:
        errorFile.write("0x%x \n" % (errs, ))
    del bitVect
    del BT
Exemple #26
0
    def take_input(self, plainText):
        ch_list = []
        # plainText = input("Give Text to encrypt: ")
        for ch in plainText:
            word_bits = BitVector(textstring=ch)
            ch_list.append(word_bits.get_bitvector_in_hex())

        if len(ch_list) < 16:
            for _ in range(0, 16 - len(ch_list)):
                ch_list.append('0')

        w0 = ch_list[0:4]
        w1 = ch_list[4:8]
        w2 = ch_list[8:12]
        w3 = ch_list[12:16]

        # print("IN HEX: ", ch_list)

        self.state_mat = {0: w0, 1: w1, 2: w2, 3: w3}
Exemple #27
0
def inv_mix_columns(sa):
    ''' Inverse mix columns on state array sa to return new state array '''
    # ADD YOUR CODE HERE - SEE LEC SLIDE 36
    state_array = copy.deepcopy(sa)
    new_sa = []
    matrix = [[14, 11, 13, 9], \
              [9, 14, 11, 13], \
                     [13, 9, 14, 11], \
              [11, 13, 9, 14]]
    for i in range(4):
        col_collector = []
        for j in range(4):
            row_collector = BitVector.BitVector(intVal=0, size=8)
            for k in range(4):
                after_mult = gf_mult(state_array[i][k], matrix[j][k])
                row_collector = Xor(after_mult, row_collector)
            col_collector.append(row_collector)
        new_sa.append(col_collector)
    return new_sa
Exemple #28
0
 def write_bit_array_to_packed_binary_file(self, file_out):  #(S1)
     '''
     This creates a packed disk storage for your bit array.  But for
     this to work, the total number of bits in your bit array must be a
     multiple of 8 since all file I/O is byte oriented.  Also note that
     now you cannot use any byte as a row delimiter.  So when reading
     such a file back into a bit array, you have to tell the read
     function how many rows and columns to create.
     '''
     err_str = '''Only a bit array whose total number of bits
         is a multiple of 8 can be written to a file.'''          #(S2)
     if self.rows * self.columns % 8:  #(S3)
         raise ValueError(err_str)  #(S4)
     FILEOUT = open(file_out, 'wb')  #(S5)
     bitstring = ''  #(S6)
     for bitvec in self.rowVectors:  #(S7)
         bitstring += str(bitvec)  #(S8)
     compositeBitVec = BitVector.BitVector(bitstring=bitstring)  #(S9)
     compositeBitVec.write_to_file(FILEOUT)  #(S10)
Exemple #29
0
 def test01(self):
     x = BitVector.BitVector()
     r = x.get(3)
     self.assertEqual(r, False)
     r = x.get(0)
     self.assertEqual(r, False)
     x.set(0, True)
     r = x.get(0)
     self.assertEqual(r, True)
     x.reset()
     r = x.get(0)
     self.assertEqual(r, False)
     x.set(4, True)
     r = x.get(3)
     self.assertEqual(r, False)
     r = x.get(4)
     self.assertEqual(r, True)
     r = x.get(5)
     self.assertEqual(r, False)
Exemple #30
0
	def decrypt_RSA(self):
		fileSize = os.path.getsize(self.inputFileName) #determine size of input file to be decrypted
		numBitBlocks = fileSize / (self.modSize / 8) #determine size of decryption bit blocks
		bitBlockInd = 1 #bit block index counter to know when to check for new line characters to be stripped from decrypted text
		self.OpenFiles() #Open I/O files
		#scan in bits from input file and perform decryption algorithm
		while(self.inputFile_bv.more_to_read):
			nextBitBlock_bv = self.inputFile_bv.read_bits_from_file(self.modSize)	#Scan in bit block
			nextBitBlock_bv = self.CRT(nextBitBlock_bv) #Perform modular exponentiation using CRT to speed up process
			[zeros_pad, nextBitBlock_bv] = nextBitBlock_bv.divide_into_two() #remove padded zeros
			if (bitBlockInd == numBitBlocks):
				#Strip appended new line characters
				outputTextHex = nextBitBlock_bv.get_hex_string_from_bitvector()
				outputTextHex = outputTextHex.strip("0a")
				nextBitBlock_bv = BitVector(hexstring = outputTextHex)
			nextBitBlock_bv.write_to_file(self.outputFile) #write bit block to output file
			bitBlockInd = bitBlockInd + 1 #increment bit block index counter
		self.CloseFiles() #Close I/O Files
		return