def compress(text): tree = HuffmanTree(text) b = bitarray() for letter in text: code = tree.codes[letter] b += bitarray(code) return b, tree
def __hash__(self): "Return hash(self)." if getattr(self, '_hash', None) is None: # ensure hash is independent of endianness a = bitarray(self, 'big') if self.endian() == 'little' else self self._hash = hash((len(a), a.tobytes())) return self._hash
def __hash__(self): "Return hash(self)." if getattr(self, '_hash', None) is None: # ensure hash is independent of endianness, also the copy will be # mutable such that .tobytes() can zero out the pad bits a = bitarray(self, 'big') self._hash = hash((len(a), a.tobytes())) return self._hash
def right_shift(array, n): res = bitarray(len(array)) for i in range(len(array)): res[i] = array[i] for j in range(n): for i in reversed(range(1, len(array))): res[i] = array[i - 1] res[0] = 0 array = res return res
def left_shift(array, n): res = bitarray(len(array)) for i in range(len(array)): res[i] = array[i] for j in range(n): for i in range(len(array) - 1): res[i] = array[i + 1] res[-1] = 0 array = res return res
def encrypt_CBC(plaintext, key, IV, n=2, size_block=64): res = bitarray() for index_of_block in range(len(plaintext) // size_block): block = plaintext[size_block * index_of_block:size_block * (index_of_block + 1)] if index_of_block == 0: block = block ^ IV else: block = block ^ res[size_block * (index_of_block - 1):size_block * index_of_block] encrypted_block = encrypt_block(block, key, n) res += encrypted_block return res
def decrypt_CBC(plaintext, key, IV, n=2, size_block=64): res = bitarray() for index_of_block in range(len(plaintext) // size_block): block = plaintext[size_block * index_of_block:size_block * (index_of_block + 1)] decrypted_block = decrypt_block(block, key, n) if index_of_block == 0: decrypted_block = decrypted_block ^ IV else: decrypted_block = decrypted_block ^ plaintext[size_block * ( index_of_block - 1):size_block * index_of_block] res += decrypted_block return res
def decrypt_CFB(plaintext, key, IV, n=2, size_block=64): res = bitarray() for index_of_block in range(len(plaintext) // size_block): block = plaintext[size_block * index_of_block:size_block * (index_of_block + 1)] if index_of_block == 0: decrypted_block = encrypt_block(IV, key, n) ^ block else: decrypted_block = encrypt_block( plaintext[size_block * (index_of_block - 1):size_block * index_of_block], key, n) ^ block res += decrypted_block return res
def decrypt_block(block, key, n=2): size_block = len(block) for i in range(n): res = bitarray() k_i = get_K_i(key, n - i - 1) left = block[0:size_block // 2] right = block[size_block // 2:size_block] temp = F(left, k_i) ^ right if i == n - 1: new_block = left + temp else: new_block = temp + left res += new_block block = res return block
def decrypt(plaintext, key, n=2, size_block=64): for i in range(n): res = bitarray() k_i = get_K_i(key, n - i - 1) for index_of_block in range(len(plaintext) // size_block): block = plaintext[size_block * index_of_block:size_block * (index_of_block + 1)] left = block[0:size_block // 2] right = block[size_block // 2:size_block] temp = F(left, k_i) ^ right if i == n - 1: new_block = left + temp else: new_block = temp + left res += new_block plaintext = res return plaintext
def lzw_decompress(self, input_path, output_path): """ decompress input_file :param input_path: the file to decompress using lzw :return: output_path. file decompressed saved to filename + "_decompressed" + ".bmp" """ with open(input_path, 'rb') as file, open(output_path, 'wb') as output: tempBuffer = bitarray() decoded_text = b'' word = b'' previous = -1 encoded_text = "" padding = int.from_bytes(file.read(1), byteorder="big", signed=False) tempBuffer.fromfile(file, 1) del tempBuffer[:padding] scanned_bytes = commons.yield_bytes_from_stream(file) for chunk in scanned_bytes: tempBuffer.frombytes(chunk) encoded_text += tempBuffer.to01() del tempBuffer[:] while len(encoded_text) >= self.n_bits: code = encoded_text[0:self.n_bits] # reading n_bits at the time key = int(code, 2) # convert to code if previous == -1: previous = int(code, 2) elif self.rev_keys == self.dict_max_size: if key != self.rev_keys: word += self.reverse_lzw_mapping[previous] + self.reverse_lzw_mapping[key][0:1] else: word += self.reverse_lzw_mapping[previous] + self.reverse_lzw_mapping[previous][0:1] previous = key else: if key != self.rev_keys: word += self.reverse_lzw_mapping[previous] + self.reverse_lzw_mapping[key][0:1] else: word += self.reverse_lzw_mapping[previous] + self.reverse_lzw_mapping[previous][0:1] self.reverse_lzw_mapping[self.rev_keys] = word self.rev_keys += 1 previous = key decoded_text += self.reverse_lzw_mapping[key] word = b'' encoded_text = encoded_text[self.n_bits:] # skip n_bits output.write(decoded_text) # write to file print("LZW Decompressed")
def bytestring2bitarray(input_string): bits_input_string = bitarray() for char in input_string: aa = ''.join(['0'] * (8 - len(bin(char)[2:]))) bits_input_string += aa + bin(char)[2:] return bits_input_string
def check_alg_for_root_comp(comp_index, words, c: bitarray): global WD_TIME, COPY_TIME, NR_COMP_EVALS root_comp = ALL_COMPS[comp_index] root_node = generate_algorithm(root_comp) if DEBUG: print("({}) Starting checking of algorithms with root value {}".format( strftime("%Y-%m-%d %H:%M:%S", gmtime()), root_comp)) # Note: We do not want to manipulate the root - different root-values will be checked in other executions # Compute three subsets of the words and of the tree runtime_start = time.time() bigger_list, equal_list, smaller_list = MY_UTIL.divide_words( root_comp, words) NR_COMP_EVALS += len(words) WD_TIME += (time.time() - runtime_start) c[comp_index] = False runtime_start = time.time() c_smaller = c.copy() c_equal = c.copy() c_bigger = c.copy() COPY_TIME += (time.time() - runtime_start) # union-find datastructure that is used to keep track if the underlying ordering graph is yet weakly connected # cc = UF(n) # cc.union(root_comp[0], root_comp[1]) # # # graph that keeps track of transitive dependencies # G = nx.DiGraph() # G.add_nodes_from(range(n)) # # G_smaller = G.copy() # G_equal = G.copy() # G_bigger = G.copy() # # G_smaller.add_edge(root_comp[0], root_comp[1]) # G_equal.add_edge(root_comp[0], root_comp[1]) # G_equal.add_edge(root_comp[1], root_comp[0]) # G_bigger.add_edge(root_comp[1], root_comp[0]) # # # If, for a word w=a_1 a_2 ... a_n, we already know that the max_suffix is in the subword a_i ... a_n and we # # conduct a comparison between the a_i and a_j which yields a_i < a_j we can subsequently only # # investigate the subword a_{i+1} a_{i+2} ... a_n if root_comp[0] == 0: c_smaller[0:n - 1:1] = False first_rel_char_smaller = 1 else: first_rel_char_smaller = 0 #flags that are True when an incoming edge exists for vertex i inc = bitarray() inc.extend(False for _ in range(n)) #flags that are True when an outgoing edge exists for vertex i outg = bitarray() outg.extend(False for _ in range(n)) #flags that are True when a vertex is blocked for optim 3 (when it has two inc. or two outg. edges) blocked = bitarray() blocked.extend(False for _ in range(n)) if (check_alg(root_node.children[0], smaller_list, c_smaller, first_rel_char_smaller, inc, outg, blocked) and check_alg(root_node.children[1], equal_list, c_equal, 0, inc, outg, blocked) and check_alg(root_node.children[2], bigger_list, c_bigger, 0, inc, outg, blocked)): return root_node else: return
runtimes = [] wdtimes = [] words_with_max_suffix = MY_UTIL.generate_all_words() for i in range(10): working_algs = [] if NR_WORKERS > 1: # worker pool - each worker is responsible for a single root value workers = Pool(processes=NR_WORKERS) runtime_start = time.time() try: results = [] for comp_index in range(NR_COMPS): c = bitarray() c.extend(True for _ in range(len(MY_UTIL.comp_pairs))) r = workers.apply_async(check_alg_for_root_comp, (comp_index, words_with_max_suffix, c), callback=MY_UTIL.check_valid) results.append(r) for r in results: r.wait() except (KeyboardInterrupt, SystemExit): print("except: attempting to close pool") workers.terminate() print("pool successfully closed") finally: print("finally: attempting to close pool") workers.terminate()
if b > 255: b = 255 draw.point((x, y), (r, g, b)) image.save("temp_with_secret.png", "PNG") print('Скрытие информации завершено') image = Image.open("temp_with_secret.png") pix = image.load() random.seed(K0) width = image.size[0] height = image.size[1] res = bitarray() for i in range(sigma, width - sigma): for j in range(sigma, height - sigma): x = random.uniform(sigma, width - sigma) y = random.uniform(sigma, height - sigma) temp_b = 0 b = pix[x, y][2] for k in range(1, sigma + 1): bt = pix[x, y + k][2] bd = pix[x, y - k][2] bl = pix[x - k, y][2] br = pix[x, y + k][2] temp_b += bt + bd + bl + br temp_b /= 4 * sigma