def operator(self, data, start) -> int: length_type_id = data[start] start = start + 1 if length_type_id == 0: bit_length = ba2int(data[start: start + 15]) start = start + 15 packets_start = start while start - packets_start < bit_length: p = BitsMessage.Packet() start = p.parse(data, start) self.packets.append(p) return start if length_type_id == 1: packet_count = ba2int(data[start: start + 11]) start = start + 11 while len(self.packets) < packet_count: p = BitsMessage.Packet() start = p.parse(data, start) self.packets.append(p) return start
def decode(in_file, out_file): entry_index = 1 dictionary = [bytearray()] output_buffer = bytearray() input_buffer = bitarray() input_buffer.fromfile(in_file) k = ba2int(input_buffer[:5]) n = 2 ** k if k > 0 else inf input_buffer = input_buffer[5:] input_len = len(input_buffer) current_index = 0 while input_len - current_index > 0: index_len = int(log2(entry_index - 1 if entry_index > 1 else 1)) + 1 # 1 - 0, 2 - 0,1, 3-0,1,2, 4-0,1,2,3. # 1,2 - 1 bit, 3,4 - 2 bits, 5,6,7,8-3 bits, 9,10,11,12,13,14,15,16 - 4 bits index = ba2int(input_buffer[current_index:current_index + index_len]) entry = bytearray() entry.extend(dictionary[index]) if (input_len - current_index) - index_len > 8: word = input_buffer[current_index + index_len:current_index + index_len + 8] entry.append(ba2int(word)) current_index = current_index + index_len + 8 entry_index = entry_index + 1 else: current_index = input_len if n is inf or len(dictionary) <= n: dictionary.append(entry) output_buffer.extend(entry) out_file.write(output_buffer) print(f"FILE <{in_file.name}> DECOMPRESSED TO <{out_file.name}>")
def mangling_function(self, right_side, key): expanded_bitstring = self.permute(right_side, EXPANSION_FUNCTION) xor = expanded_bitstring ^ key b_list = [] begin = 0 for end in range(6, len(xor) + 1, 6): b_list.append(xor[begin:end]) begin = end c_of_j_list = [] for i, b in enumerate(b_list): row = bitarray(2) row[0] = b[0] row[1] = b[-1] row_num = ba2int(row) column = bitarray(4) for j in range(1, 5): column[j - 1] = b[j] col_num = ba2int(column) c_of_j_list.append(int2ba(S_BOXES[i][row_num * 16 + col_num], 4)) big_c = bitarray() for i in c_of_j_list: big_c += i # print(f'S-BOX outputs = {big_c}') return self.permute(big_c, PERMUTATION)
def send_response( self, request: TicketGrantingServerRequest ) -> tp.Optional[TicketGrantingServerResponse]: ticket_granting_ticket = request.encrypted_ticket_granting_ticket ticket_granting_ticket.decrypt_data(self._cipher, self._as_tgs_key) authentication_block = request.encrypted_authentication_block authentication_block.decrypt_data(self._cipher, self._c_tgs_key) max_valid_timestamp = ba2int(ticket_granting_ticket.current_timestamp) + \ ba2int(ticket_granting_ticket.valid_period_seconds) if ticket_granting_ticket.client_id == authentication_block.client_id and \ max_valid_timestamp > ba2int(authentication_block.current_timestamp): current_timestamp = int(datetime.datetime.utcnow().timestamp()) ticket_granting_service = TicketGrantingService( ba2int(ticket_granting_ticket.client_id), request.service_server_id, current_timestamp, self._valid_period_seconds, self._c_ss_key) ticket_granting_service.encrypt_data(self._cipher, self._tgs_ss_key) logger.info('Sending ticket granting server response') return TicketGrantingServerResponse(self._cipher, self._c_tgs_key, ticket_granting_service, self._c_ss_key) else: logger.error( 'Different client id in ticket granting ticket and authentication block or authentication time expired' ) return None
def generate_mem_content(code, initial: bitarray, delta: bitarray, N=100): initial = bit_util.ba2int(initial) delta = bit_util.ba2int(delta) overlap = 2**(code.k) data = [x % overlap for x in range(initial, initial + N * delta, delta)] ba_data = [bit_util.int2ba(d, length=code.k) for d in data] codewords = [code.encode_word(word) for word in ba_data] return codewords
def __init__(self, bits: bitarray) -> None: self.original_bits = bits self.version = util.ba2int(bits[:3]) self.packet_type_id = util.ba2int(bits[3:6]) self.literal_value = None self.length_type_id = None self.children = [] self.extra_bits = bitarray() self._parse_packet(bits[6:])
def parse(self, data: bitarray, start) -> int: self.version = ba2int(data[start: start + 3]) start = start + 3 self.type = ba2int(data[start: start + 3]) match self.type: case 4: # Literal return self.literal(data, start + 3) case _: # Operator return self.operator(data, start + 3)
def decode(ba): dict_length = ba2int(ba[0:16]) de_dict_encoded = ba[16:16 + dict_length] payload_length = ba2int(ba[16 + dict_length:16 + dict_length + 64]) payload = ba[16 + dict_length + 64:16 + dict_length + 64 + payload_length] de_dict = deserialize_dict(de_dict_encoded) if payload: return b"".join(payload.decode(de_dict)) else: return b""
def test_explicit(self): _set_default_endian('big') for i, sa in [(0, '0'), (1, '1'), (2, '10'), (3, '11'), (25, '11001'), (265, '100001001'), (3691038, '1110000101001000011110')]: ab = bitarray(sa, 'big') al = bitarray(sa[::-1], 'little') self.assertEQUAL(int2ba(i), ab) self.assertEQUAL(int2ba(i, endian='big'), ab) self.assertEQUAL(int2ba(i, endian='little'), al) self.assertEqual(ba2int(ab), ba2int(al), i)
def s_block(b: bitarray, i: int) -> bitarray: assert len(b) == 6 row_bits = bitarray(2) row_bits[0] = b[0] row_bits[1] = b[5] row = ba2int(row_bits) assert 0 <= row < 4 col = ba2int(b[1:4]) assert 0 <= col < 16 return int2ba(S[i][row][col], length=4)
def test_random_signed(self): for a in self.randombitarrays(start=1): i = ba2int(a, signed=True) b = int2ba(i, len(a), a.endian(), signed=True) self.assertEQUAL(a, b) j = ba2int(a, signed=False) # unsigned if i >= 0: self.assertEqual(i, j) self.assertEqual(i, self.twos_complement(j, len(a)))
def _make_s_box_conversion( block: bitarray, s_boxes: tp.List[tp.List[tp.List[int]]]) -> bitarray: result_bitarray = bitarray() for i in range(8): current_six_bits = block[i * 6:(i + 1) * 6] s_box_conversion_result = int2ba(s_boxes[i][ba2int( current_six_bits[:2])][ba2int(current_six_bits[2:])], length=4) result_bitarray += s_box_conversion_result return result_bitarray
def hidden_image(image, chans, testing_multiple): img = imageio.imread(image) height, width, channels = img.shape print("Height:", height, "Width:", width, "Number of Channels:", channels) hidden_height = get_header(image, chans, 0, 32, 1) hidden_width = get_header(image, chans, 32, 32, 1) print("Hidden height:", hidden_height, "Hidden width:", hidden_width) if testing_multiple: if input("Continue?") in ["n", "N"]: return count = 0 chars = [] for r in range(height): for c in range(width): if count < hidden_height * hidden_width * 32 + 64: previous_length = len(chars) if 0 in chans: chars.append(str(img[r, c, 0] & 1)) if 1 in chans: chars.append(str(img[r, c, 1] & 1)) if 2 in chans: chars.append(str(img[r, c, 2] & 1)) if 3 in chans: chars.append(str(img[r, c, 3] & 1)) count += len(chars) - previous_length chars = chars[64:] # output = bitarray("".join(chars)) # print(output) for r in range(hidden_height): for c in range(hidden_width): # print("R:", chars[0:8], "G:", chars[8:16], "B:", chars[16:24]) red = ba2int(bitarray("".join(chars[0:8]))) green = ba2int(bitarray("".join(chars[8:16]))) blue = ba2int(bitarray("".join(chars[16:24]))) # alpha = ba2int(bitarray("".join(chars[24:32]))) # print("R:", red, "G:", green, "B:", blue) img[r, c][0] = red img[r, c][1] = green img[r, c][2] = blue # img[r,c][3] = alpha chars = chars[24:] percent_done = ( (r * hidden_width) + c) / (hidden_width * hidden_height) if percent_done % 10 == 0: print(percent_done, "percent done") print("100.0 percent done. Writing...") imageio.imwrite("altered_" + image, img)
def installDistributionInCPAndGeneratePacketOutMessages(self, weightDistribution, firstTimeFlag=False): weightDistribution = self.getAccumulatedDistribution(weightDistribution) lastPositionCheckerBitMask = ba.bitarray(self.bitMaskLength) lastPositionCheckerBitMask.setall(0) lastPositionCheckerBitMask[len(lastPositionCheckerBitMask)-1] =1 #TODO : from the weight distribution we must have to identify who can be our possible next block of a group. # that's why we will use the isEmptyBlock member #Iterate over the distribution and set eachblocks isEmpty for l in range(0, len(weightDistribution)) : e= weightDistribution[l] newWeightGroup = e[1] newBitMaskArrayIndex = int(newWeightGroup/self.bitMaskLength) self.isBitMaskBlockEmpty[newBitMaskArrayIndex] = False for l in range(0, len(weightDistribution)) : e= weightDistribution[l] link = e[0] if(firstTimeFlag == False): # At the first time we do not need to delete any distribution. If we delet link i+1 may delete Link i th newly installed distribution oldWeightGroup = self.linkToCurrentWeightGroupMap.get(link) bitMaskArrayIndex = int(oldWeightGroup/ self.bitMaskLength) positionInbitMask = oldWeightGroup % self.bitMaskLength self.bitMaskArray[bitMaskArrayIndex][positionInbitMask] = 0 if (bautil.ba2int((self.bitMaskArray[bitMaskArrayIndex] and lastPositionCheckerBitMask)) ==0): print("last position empty") print(self.bitMaskArray[bitMaskArrayIndex]) self.nextBlockIndex[bitMaskArrayIndex] = self.getNextBlock(currenntIndex = bitMaskArrayIndex) else: print("last position non-empty") print(self.bitMaskArray[bitMaskArrayIndex]) #Generate a message here for delete newWeightGroup = e[1] self.linkToCurrentWeightGroupMap[link] = newWeightGroup newBitMaskArrayIndex = int(newWeightGroup/self.bitMaskLength) newPositionInbitMask = newWeightGroup % self.bitMaskLength self.bitMaskArray[newBitMaskArrayIndex][newPositionInbitMask] = 1 oldNextBlock = self.nextBlockIndex[newBitMaskArrayIndex] newNextblock = self.getNextBlock(currenntIndex = newBitMaskArrayIndex) print("oldNextBlock is ", oldNextBlock, "newNextblock is ",newNextblock) if (oldNextBlock != newNextblock): self.nextBlockIndex[newBitMaskArrayIndex] = newNextblock if (bautil.ba2int((self.bitMaskArray[newBitMaskArrayIndex] & lastPositionCheckerBitMask)) ==0): print("last position empty") print(self.bitMaskArray[newBitMaskArrayIndex]) else: print("last position non-empty") print(self.bitMaskArray[newBitMaskArrayIndex])
def flat_score( strategies: BinaryStrategies, history_func: BinaryHistoryFunc, score: Callable[[int, int], int], ) -> BinaryUtilityScore: window_size = get_window_size(strategies) history = history_func() scores = { uuid: Score({ "score": 0, "prediction": -1 }) for uuid in strategies.keys() } for i in range(len(history)): if i + window_size >= len(history): return scores encoded_seq = bitarray_util.ba2int(history[i:window_size + i]) next_state = history[window_size + i] for uuid, strategy in strategies.items(): prediction = strategy.binary_seq_map[encoded_seq] scores[uuid]["prediction"] = prediction scores[uuid]["score"] = scores[uuid]["score"] + score( prediction, next_state) return scores
def read_int(self, n: int) -> int: """Reads certain number of bits from the pointer position and returns the value as integer. :param n: Number of bits to retrieve and transform into int. """ return ba2int(self.read_bits(n))
def get(self, index: int, size: int = 1) -> int: start = max(len(self._value) - (index + 1) * size, 0) finish = max(len(self._value) - index * size, 0) bits = self._value[start:finish] if len(bits) == 0: return 0 return util.ba2int(bits)
def get_header_not_lsb(image, chans, header_start, header_length, bits): img = imageio.imread(image) height, width, _ = img.shape chars = [] count = 0 for r in range(height): for c in range(width): if count < header_start + header_length: previous_length = len(chars) if 0 in chans: chars.extend( list( str((int2ba((img[r, c, 0] & bits) >> (bits / 2)).item())).split('\'')[1])) if 1 in chans: chars.extend( list( str((int2ba((img[r, c, 1] & bits) >> (bits / 2)).item())).split('\'')[1])) if 2 in chans: chars.extend( list( str((int2ba((img[r, c, 2] & bits) >> (bits / 2)).item())).split('\'')[1])) if 3 in chans: chars.extend( list( str((int2ba((img[r, c, 3] & bits) >> (bits / 2)).item())).split('\'')[1])) count += len(chars) - previous_length output = "".join(chars)[header_start:header_start + header_length] return ba2int(bitarray(output))
def code_point(u): print('character:', u) b = u.encode('utf-8') print('hexadecimal:', ' '.join('%02x' % i for i in bytearray(b))) a = bitarray(endian='big') a.frombytes(b) pprint(a) # calculate binary code point from binary UTF-8 representation if a[0:1] == bitarray('0'): c = a[1:8] assert len(a) == 8 elif a[0:3] == bitarray('110'): c = a[3:8] + a[10:16] assert a[8:10] == bitarray('10') assert len(a) == 16 elif a[0:4] == bitarray('1110'): c = a[4:8] + a[10:16] + a[18:24] assert a[8:10] == a[16:18] == bitarray('10') assert len(a) == 24 elif a[0:5] == bitarray('11110'): c = a[5:8] + a[10:16] + a[18:24] + a[26:32] assert a[8:10] == a[16:18] == a[24:26] == bitarray('10') assert len(a) == 32 else: raise code_point = ba2int(c) print('code point:', hex(code_point)) print()
def apply(self, val): bt = bt_util.int2ba(val, length=36, endian="big") debug(f"Input: {bt}") bt &= self.and_mask bt |= self.or_mask debug(f"Masked: {bt}") return bt_util.ba2int(bt)
def s(k_1, k_2, val): k_2 = ba2int(k_2) if k_2 not in available[k_1]: available[k_1][k_2] = [] available[k_1][k_2].append(val)
def instruction_decoder(bits): instr = {'version': None, 'type': None, 'value': None} version, type_ = ba2int(bits[0:3]), ba2int(bits[3:6]) instr['version'] = version instr['type'] = type_ remaining = bits[6:] if instr['type'] == 4: remaining, value = decode_literal(remaining) instr['value'] = value else: length_type = bits[6] bits = bits[7:] instr['value'] = [] if not length_type & 1: read_bits = ba2int(bits[:15]) bits = bits[15:] actual_read_bits = bits[:read_bits] remaining = bits[read_bits:] while read_bits >= 0: orig_length = len(actual_read_bits) value, actual_read_bits = instruction_decoder(actual_read_bits) instr['value'].append(value) if actual_read_bits is None: break eaten = orig_length - len(actual_read_bits) read_bits -= eaten else: packets = ba2int(bits[:11]) bits = bits[11:] for _ in range(packets): value, bits = instruction_decoder(bits) instr['value'].append(value) remaining = bits if not remaining or len(remaining) == 0 or ba2int(remaining) == 0: return instr, None return instr, remaining
def afiseaza_generatie(generatie): for i in range(0, nr_populatie): val_intreaga = util.ba2int(generatie[i]) val_intreaga = ((domeniu[1] - domeniu[0]) / (2**lungime_cromozom - 1)) * val_intreaga + domeniu[0] g.write("{}: {}, x={}, f={}\n".format(i + 1, generatie[i].to01(), val_intreaga, functiepoz(val_intreaga)))
def decode_literal(ba): value = bitarray() while ba[0] == 1: value += ba[1:5] ba = ba[5:] value += ba[1:5] return ba[5:], ba2int(value)
def get_hash(self,chain): result = hashlib.md5(chain.encode('utf-8')) ba = bitarray.bitarray() ba.frombytes(result.hexdigest().encode()) i = ba2int(ba[:self.BA_SIZE]) # print(i) return i
def calculate_graye_code(): result = [] for item in range(0, 32): bits = bitarray(int2ba(item)) gray_code = bitarray(bits >> 1) gray_code ^= bits result.append(Number(bits, gray_code, ba2int(bits))) return result
def read_elias(bits, start_index): ''' Reads an Elias Omega encoded integer from the given bits starting at the given index. Returns the decoded integer and the index after reading. This function modifies the given bit array. bits: Array of bits to read from. start_index: Index to start reading. ''' length = 1 index = start_index while bits[index] == 0: # read length components bits[index] = not bits[index] # flip left-most bit end_index = index + length length = util.ba2int(bits[index:end_index]) + 1 index = end_index end_index = index + length n = util.ba2int(bits[index:end_index]) return n, end_index
def test_bitwise_inplace(self): for a in self.randombitarrays(start=1): b = urandom(len(a), a.endian()) bb = b.copy() i = ba2int(a) j = ba2int(b) c = a.copy() c &= b self.assertEqual(ba2int(c), i & j) c = a.copy() c |= b self.assertEqual(ba2int(c), i | j) c = a.copy() c ^= b self.assertEqual(ba2int(c), i ^ j) self.assertEQUAL(b, bb) n = randint(0, len(a)) if a.endian() == 'big': c = a.copy() c >>= n self.assertEqual(ba2int(c), i >> n) c = zeros(len(a)) + a c <<= n self.assertEqual(ba2int(c), i << n)
def check_round_trip(self, i): for endian in 'big', 'little': a = int2ba(i, endian=endian) self.assertEqual(a.endian(), endian) self.assertTrue(len(a) > 0) # ensure we have no leading zeros if a.endian == 'big': self.assertTrue(len(a) == 1 or a.index(1) == 0) self.assertEqual(ba2int(a), i) if i > 0 and sys.version_info[:2] >= (2, 7): self.assertEqual(i.bit_length(), len(a)) # add a few / trailing leading zeros to bitarray if endian == 'big': a = zeros(randint(0, 3), endian) + a else: a = a + zeros(randint(0, 3), endian) self.assertEqual(a.endian(), endian) self.assertEqual(ba2int(a), i)
def test_hex(self): for i in range(1000): s = hex(i) self.assertEqual(s[:2], '0x') a = hex2ba(s[2:], 'big') self.assertEqual(ba2int(a), i) t = '0x%s' % ba2hex(a) self.assertEqual(t, s) self.assertEqual(eval(t), i)