def ttl_read(self): sp = self.create_WASYNC_PAR() sp.s_Type = L_ASYNC_TTL_INP self.io_async(sp) ret = BitArray(uint=sp.Data[0], length=16) ret.reverse() return ret
def main(): """ 1. Get file. 2. Convert from base64 to hex string representation. 3. Convert hex string representation to BitArray. 4. Feed into Repeating_XOR_Breaker """ cipher_source = "https://cryptopals.com/static/challenge-data/6.txt" cipher_reader = Data_reader(cipher_source) data = cipher_reader.get_data() data = ''.join(data) converted = Base64_To_Hex(data).convert() data_to_break = BitArray(hex=converted) breaker = Repeating_XOR_Breaker(data_to_break) candidate_keys = breaker.solve() print "Candidate Keys:", candidate_keys for key_set in candidate_keys: whole_key = BitArray(hex='0x00') for key in key_set: whole_key.append(BitArray(int=key, length=8)) print "whole_key:", whole_key decrypter = ExtendedKeyDecrypter() decrypter.set_decrypt_key(whole_key.hex) print decrypter.decrypt()
def get_bits(length, mode=-1): """生成指定长度的位串. length -- 位串长度 mode -- 0 返回全0 1 返回全1 -1 返回随机位串 """ # 生成指定长度的位串的最大值 bits = BitArray(length) bits.set(1) bin_str = '' if mode == 0: bits.set(0) bin_str = '0b' + bits.bin elif mode == 1: bin_str = '0b' + bits.bin else: # print 'all_1_bit:bin:' + bits.bin # print 'all_1_bit:uint:' + bits.uint.__str__() # 生成随机数,0到最大值 random_num = random.randint(0, bits.uint) # print 'random_num:' + random_num.__str__() bin_str = bin(random_num) # print 'created bit:' + bin_str[2:] return bin_str
def render(self, ctx=None): ''' :param ctx: rendering context in which the method was called :rtype: `Bits` :return: rendered value of the container ''' self._initialize() if ctx is None: ctx = RenderContext() ctx.push(self) self.set_offset(self._offset, ctx) if self.is_default(): self._current_rendered = self._default_rendered ctx.pop() return self._default_rendered rendered = BitArray() offset = 0 for field in self._fields: frendered = field.render(ctx) if not isinstance(frendered, Bits): raise KittyException('the field %s:%s was rendered to type %s, you should probably wrap it with appropriate encoder' % ( field.get_name(), type(field), type(frendered))) rendered.append(frendered) offset += len(frendered) self.set_current_value(rendered) ctx.pop() return self._current_rendered
def initFile(self): file_name = self.file_to_stream['name'] fout = open(file_name, "wb") data = BitArray(int(self.file_to_stream_length)*8) data = data.tobytes() fout.write(data) fout.close()
def generate_coded_symbol(generator_row, message_symbol_list): selected_list = [message_symbol_list[i] for i, g in enumerate(generator_row) if g == 1] coded_symbol = BitArray( [0] * len(message_symbol_list[0]) ) for s in selected_list: coded_symbol = coded_symbol.__xor__(s) return coded_symbol
def testCopyMethod(self): s = BitArray(9) t = s.copy() self.assertEqual(s, t) t[0] = True self.assertEqual(t.bin, '100000000') self.assertEqual(s.bin, '000000000')
class MasterKey(object): def __init__(self, master_key_hex_string="0x3cc849279ba298b587a34cabaeffc5ecb3a044bbf97c516fab7ede9d1af77cfa"): self.key = BitArray(master_key_hex_string) self.session_keys_amount = 8 self.current_cycle_index = 0 self.master_key_round_shift_bits = 24 def get_round_keys(self): """ :return: list of round keys :rtype: list[RoundKey] """ if self.current_cycle_index: round_master_key = self.key.copy() round_master_key.ror(self.master_key_round_shift_bits * self.current_cycle_index) else: round_master_key = self.key.copy() round_keys = [] round_key_size = round_master_key.length / self.session_keys_amount for key_index in range(0, self.session_keys_amount): round_key = round_master_key[key_index * round_key_size:key_index * round_key_size + round_key_size] round_keys.append(RoundKey(round_key)) if self.current_cycle_index < 8: self.current_cycle_index += 1 else: self.current_cycle_index = 0 return round_keys
def huff_encode(text): freq = defaultdict(int) for s in text: freq[s] += 1 tree = [ [f, [s, ""]] for s,f in freq.items() ] heapify(tree) while len(tree) > 1: l = heappop(tree) h = heappop(tree) for n in l[1:]: n[1] = '0' + n[1] for n in h[1:]: n[1] = '1' + n[1] heappush(tree, [l[0] + h[0]] + l[1:] + h[1:]) root = heappop(tree)[1:] codes = dict([(s, "0b"+c) for s,c in root]) # Header enc = BitArray() for s,c in root: enc += BitArray(bytes=s) enc += BitArray(uint=len(c), length=8) enc += BitArray("0b"+c) enc.prepend(BitArray(uint=len(root), length=8)) for s in text: enc += BitArray(codes[s]) return enc
def p_expression_concat(p): "expression : expression CONCAT expression" s1=BitArray(p[1]) s2=BitArray(p[3]) # print str(s2) s1.append('0b' + s2.bin) p[0] = '0b' + s1.bin
def pointer_to_binary (self, pointer, configuration, thread = None): """Convert a Pointer object to the binary init load value for a Programmed Offset entry.""" # Add the Default Offset for each thread, so we point to the correct per-thread instance of the pointed-to variable # None thread means a shared variable holds the init data, or other unique location identical to all threads. if thread is not None: default_offset = configuration.default_offset.offsets[thread] else: default_offset = 0 # Addresses wrap around when the offset is added, # so express negative values as the modular sum value # Read and write pointers have different address ranges and offset bit widths if "D" in pointer.memory: # write pointer offset = (pointer.base + pointer.offset - pointer.address + default_offset) % configuration.memory_depth_words_write offset = BitArray(uint=offset, length=configuration.po_write_offset_bit_width) else: # read pointer offset = (pointer.base + pointer.offset - pointer.address + default_offset) % configuration.memory_depth_words offset = BitArray(uint=offset, length=configuration.po_read_offset_bit_width) # The increment is a signed magnitude number (absolute value and sign bit) increment = BitArray(uint=abs(pointer.incr), length=configuration.po_increment_bits) increment_sign = self.to_sign_bit(pointer.incr) increment_sign = BitArray(uint=increment_sign, length=configuration.po_increment_sign_bits) # Now pack them into the Programmed Offset entry binary configurations pointer_bits = BitArray() for entry in [increment_sign, increment, offset]: pointer_bits.append(entry) return pointer_bits
def team(self): c = BitArray() c.append("uint:8=%s" % self.player_slot) if c[0] == 0: return "radiant" else: return "dire"
def booth(m, r, x, y): # Initialize totalLength = x + y + 1 mA = BitArray(int = m, length = totalLength) rA = BitArray(int = r, length = totalLength) A = mA << (y+1) S = BitArray(int = -m, length = totalLength) << (y+1) P = BitArray(int = r, length = y) P.prepend(BitArray(int = 0, length = x)) P = P << 1 print "Initial values" print "A", A.bin print "S", S.bin print "P", P.bin print "Starting calculation" for i in range(1,y+1): if P[-2:] == '0b01': P = BitArray(int = P.int + A.int, length = totalLength) print "P + A:", P.bin elif P[-2:] == '0b10': P = BitArray(int = P.int +S.int, length = totalLength) print "P + S:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin P = arith_shift_right(P, 1) print "P >> 1:", P.bin return P.int
def prime_sieve(top=10005): b = BitArray(top) # bitstring of ’0’ bits for i in range(2, top): if not b[i]: yield i # i is prime, so set all its multiples to ’1’. b.set(True, range(i * i, top, i))
def carryDigits(digits): bits = BitArray(bin='000') for digit in digits: bits = bits ^ digit bits.rol(1) return bits
def booths(m,r): x=len(bin(m)) y=len(bin(r)) totallength = x+y+1 if m<0 and r<0 or r<0: bugbit = 1 else: bugbit = 0 A = BitArray(int = m,length = totallength) << (y+1) compliment = BitArray(int = -m,length = totallength) << (y+1) P = BitArray(int = r, length = totallength) P = P<<1 for i in range(1,y+1): if P[-2:]=='0b01': P = BitArray(int = P.int + A.int, length = totallength) elif P[-2:]=='0b10': P = BitArray(int = P.int + compliment.int, length = totallength) P = BitArray(int = P.int>>1, length = totallength) P = P[:-1] P.int = P.int + bugbit steps ="" return '<h1>RESULT</h1><br>'+steps+'<br><h3>decimal value: '+str(P.int)+'</br><br> binary value: '+str(P.bin)+"</h3>"
def _ensure_padding(self, cipher_stream): stream = BitArray(hex=cipher_stream) stream_len = stream.len while stream_len % 8: stream.insert('0b0', 0) stream_len = stream_len + 1 return stream
def encode(self, value): ''' :param value: value to encode ''' kassert.is_of_types(value, Bits) result = BitArray(value) result.reverse() return result
def prime_sieve(top=100000000): b = BitArray(top) # bitstring of ’0’ bits last = int(math.sqrt(top)) + 1 for i in range(2, last): if not b[i]: yield i # i is prime, so set all its multiples to ’1’. b.set(True, range(i * i, top, i))
def branch(self, origin, origin_enable, destination, predict_taken, predict_enable, condition_name): condition_bits = self.conditions[condition_name] origin_bits = BitArray(uint=origin, length=Branch.origin_width) destination_bits = BitArray(uint=destination, length=Branch.destination_width) config = BitArray() for entry in [origin_bits, origin_enable, destination_bits, predict_taken, predict_enable, condition_bits]: config.append(entry) return config
class qubitString: def __init__(self,m): # size of qubit string self.size=m # floats can only be 32 or 64 bits self.canHaveFloat = True if self.size==32 or self.size==64 else False # create BitArray to hold value of qubit string self.arrayVal=BitArray(length=m) # initialization value for qubits initVal=1/np.sqrt(2) quString=list() for i in range(0,self.size): quString.append(qubit(initVal,initVal)) self.quString=quString self.decVal=None self.binVal=None self.floatVal=None def collapse(self): self.bitString=list() for i in range(0,self.size): # observe and collapse qubit to a state self.quString[i].collapse() # save collapsed value to bit array if self.quString[i].value == 1: self.arrayVal.overwrite('0b1',i) else: self.arrayVal.overwrite('0b0',i) # update decimal value self.decVal=self.arrayVal.int self.binVal=self.arrayVal.bin if self.canHaveFloat : self.floatVal = self.arrayVal.float def rotation_gate(self,angle): for i,j in enumerate(quString): quString[i].rotation_gate(angle) def updateDec(self,num): # update array value self.arrayVal.int=num # update binary value self.binVal=self.arrayVal.bin # update qubits values for i in range(0,self.size): self.quString[i].value=int(self.binVal[i])
def decrypt(self): result = BitArray(hex='0x00') skip_by = self.key_len for i in xrange(0, self.cipher_stream.len, skip_by): xor_res = self.cipher_stream[i:skip_by] ^ self.XOR_to_use result.append(xor_res) skip_by += self.key_len return result
def readAmbeFrameFromUDP( self, _sock ): _ambeAll = BitArray() # Start with an empty array for i in range(0, 3): _ambe = self.readSock(_sock,7) # Read AMBE from the socket if _ambe: _ambe1 = BitArray('0x'+h(_ambe[0:49])) _ambeAll += _ambe1[0:50] # Append the 49 bits to the string else: break return _ambeAll.tobytes() # Return the 49 * 3 as an array of bytes
def hamming_search(b, bit, radius, current_radius, H): if current_radius == 0: H[current_radius].append(b.copy()) if current_radius == radius: return for i in range(bit+1, b.length): b2 = BitArray(b.copy()) b2.invert(i) H[current_radius+1].append(b2.copy()) hamming_search(b2, i, radius, current_radius+1, H)
def testCreationFromOct(self): s = BitArray(oct='7') self.assertEqual(s.oct, '7') self.assertEqual(s.bin, '111') s.append('0o1') self.assertEqual(s.bin, '111001') s.oct = '12345670' self.assertEqual(s.length, 24) self.assertEqual(s.bin, '001010011100101110111000') s = BitArray('0o123') self.assertEqual(s.oct, '123')
def split(self, A): IG_list = [] A_count = float(A.count(True)) p_A = self.prob(A) e_A = self.entropy(p_A) # Get decision for node if p_A >= 0.5: d = 1 else: d = 0 # Check entropy of node if e_A < 0.3: print "Node entropy is low enough:", e_A return None,None,d,None,None # Check # elements if A_count < self.count_thresh: print "Node has few elements:", A_count return None,None,d,None,None F = self.X.T for f in range(len(F)): # Sort the relevant column and keep indices indices = F[f].argsort() pairs = zip(indices, F[f][indices]) s = len(pairs)*'0' B = BitArray(bin=s) C = A.copy() i = 0 IG_prev = 0.0 # Threshold emulator loop while i < len(pairs)-1: if A[pairs[i][0]]: B[pairs[i][0]] = 1 C[pairs[i][0]] = 0 if pairs[i][1] < pairs[i+1][1]: t = pairs[i+1][1] # Calculate information gain for the split IG_curr,s_B,s_C = self.info_gain(B,C,e_A,A_count) #print IG_curr if IG_curr < IG_prev: break else: IG_prev = IG_curr # Check if entropy for any branches is below thresh IG_list.append((IG_curr,f,t,d,B.copy(),C.copy(),s_B,s_C)) i += 1 if IG_list == []: #print "Boring decision..." return None,None,d,None,None else: max_val = max(IG[0] for IG in IG_list) IG,f,t,d,B,C,s_B,s_C = [IG for IG in IG_list if IG[0] == max_val][0] return f,t,d,B,C
def testCreationFromOct(self): s = BitArray(oct="7") self.assertEqual(s.oct, "7") self.assertEqual(s.bin, "111") s.append("0o1") self.assertEqual(s.bin, "111001") s.oct = "12345670" self.assertEqual(s.length, 24) self.assertEqual(s.bin, "001010011100101110111000") s = BitArray("0o123") self.assertEqual(s.oct, "123")
def generate_coded_symbol(generator_row, message_symbol_list): assert (len(generator_row) == len(message_symbol_list)) selected_list = [message_symbol_list[i] for i, g in enumerate(generator_row) if g == 1] #coded_symbol = bitarray.bitarray('0' * len(message_symbol_list[0])) #coded_symbol = BitVector(size = len(message_symbol_list[0])) coded_symbol = BitArray( [0] * len(message_symbol_list[0]) ) for s in selected_list: coded_symbol = coded_symbol.__xor__(s) return coded_symbol
def p_expression_and(p): "expression : expression AND expression" # print 'in p_expression_and p1: ' + str(p[1]) # print 'in p_expression_and p3: ' + str(p[3]) s1 = BitArray(p[1]) s2 = BitArray(p[3]) # print 'in p_expression_and s1: ' + str(s1) # print 'in p_expression_and s2: ' + str(s2) s1.__iand__(s2) p[0] = '0b' + s1.bin
def condition_to_binary (self, bdo, branch): condition = branch.condition dyadic = bdo.dyadic condition_bits = BitArray() for entry in [condition.a, condition.b, condition.ab_operator]: field_bits = getattr(dyadic, entry, None) field_bits = getattr(bdo, entry, field_bits) if field_bits is None: print("Unknown branch field value: {0}".format(entry)) self.ask_for_debugger() condition_bits.append(field_bits) return condition_bits
def testInsert(self): s = BitArray('0b00') s.insert('0xf', 1) self.assertEqual(s, '0b011110')
def testInsertParameters(self): s = BitArray('0b111') self.assertRaises(TypeError, s.insert, '0x4')
def xrb_account(address): # Given a string containing an XRB address, confirm validity and # provide resulting hex address if len(address) == 64 and (address[:4] == 'xrb_'): # each index = binary value, account_lookup[0] == '1' account_map = "13456789abcdefghijkmnopqrstuwxyz" account_lookup = {} # populate lookup index with prebuilt bitarrays ready to append for i in range(32): account_lookup[account_map[i]] = BitArray(uint=i ,length=5) # we want everything after 'xrb_' but before the 8-char checksum acrop_key = address[4:-8] # extract checksum acrop_check = address[-8:] # convert base-32 (5-bit) values to byte string by appending each # 5-bit value to the bitstring, essentially bitshifting << 5 and # then adding the 5-bit value. number_l = BitArray() for x in range(0, len(acrop_key)): number_l.append(account_lookup[acrop_key[x]]) # reduce from 260 to 256 bit (upper 4 bits are never used as account # is a uint256) number_l = number_l[4:] check_l = BitArray() for x in range(0, len(acrop_check)): check_l.append(account_lookup[acrop_check[x]]) # reverse byte order to match hashing format check_l.byteswap() result = number_l.hex.upper() # verify checksum h = blake2b(digest_size=5) h.update(number_l.bytes) if (h.hexdigest() == check_l.hex): return result else: return False else: return False
def get_subkeys(seed: BitArray, debug=False): """ Get the set of 16 48-bit subkeys needed for the DES algorithm seed determines the value of these keys :param seed: seed key :param debug: set to true if debugging print statements are needed :return: an array of the 16 subkeys """ # initialize C and D arrays to all zeros C = [[False] * 28 for i in range(0, 17)] D = [[False] * 28 for i in range(0, 17)] # first, get initial values for C and D key_permuted = do_permutation(seed, vals.pc_1) if debug: print('Permuted key value: %s' % str(key_permuted)) C[0] = BitArray(flatten_list(key_permuted[0:4])) D[0] = BitArray(flatten_list(key_permuted[4:])) shift_amnts = vals.keygen_shift_table for i in range(1, 17): C_prev = BitArray(C[i - 1]) C_prev.rol(shift_amnts[i - 1]) C[i] = C_prev D_prev = BitArray(D[i - 1]) D_prev.rol(shift_amnts[i - 1]) D[i] = D_prev # print values of C and D if debug flag is set if debug: print('\nC values:') for i in range(0, len(C)): print('C_%s = %s' % (i, C[i].bin)) print('\nD values:') for i in range(0, len(D)): print('D_%s = %s' % (i, D[i].bin)) # create the subkeys based on the C and D values K = [] for i in range(0, 17): k_temp = BitArray(C[i] + D[i]) K.append(BitArray(flatten_list(do_permutation(k_temp, vals.pc_2)))) if debug: print('\nSubkey values:') for i in range(0, len(K)): print('K_%s = %s' % (i, K[i].bin)) return K
def get_opcode(self): if self.instr_name == "LUI": return (BitArray(uint=55, length=7).bin) elif self.instr_name == "AUIPC": return (BitArray(uint=23, length=7).bin) elif self.instr_name == "JAL": return (BitArray(uint=23, length=7).bin) elif self.instr_name == "JALR": return (BitArray(uint=111, length=7).bin) elif self.instr_name in ["BEQ", "BNE", "BLT", "BGE", "BLTU", "BGEU"]: return (BitArray(uint=103, length=7).bin) elif self.instr_name in ["LB", "LH", "LW", "LBU", "LHU", "LWU", "LD"]: return (BitArray(uint=99, length=7).bin) elif self.instr_name in ["SB", "SH", "SW", "SD"]: return (BitArray(uint=35, length=7).bin) elif self.instr_name in [ "ADDI", "SLTI", "SLTIU", "XORI", "ORI", "ANDI", "SLLI", "SRLI", "SRAI", "NOP" ]: return (BitArray(uint=19, length=7).bin) elif self.instr_name in [ "ADD", "SUB", "SLL", "SLT", "SLTU", "XOR", "SRL", "SRA", "OR", "AND", "MUL", "MULH", "MULHSU", "MULHU", "DIV", "DIVU", "REM", "REMU" ]: return (BitArray(uint=51, length=7).bin) elif self.instr_name in ["ADDIW", "SLLIW", "SRLIW", "SRAIW"]: return (BitArray(uint=27, length=7).bin) elif self.instr_name in [ "MULH", "MULHSU", "MULHU", "DIV", "DIVU", "REM", "REMU" ]: return (BitArray(uint=51, length=7).bin) elif self.instr_name in ["FENCE", "FENCE_I"]: return (BitArray(uint=15, length=7).bin) elif self.instr_name in [ "ECALL", "EBREAK", "CSRRW", "CSRRS", "CSRRC", "CSRRWI", "CSRRSI", "CSRRCI" ]: return (BitArray(uint=115, length=7).bin) elif self.instr_name in [ "ADDW", "SUBW", "SLLW", "SRLW", "SRAW", "MULW", "DIVW", "DIVUW", "REMW", "REMUW" ]: return (BitArray(uint=59, length=7).bin) elif self.instr_name in [ "ECALL", "EBREAK", "URET", "SRET", "MRET", "DRET", "WFI", "SFENCE_VMA" ]: return (BitArray(uint=115, length=7).bin) else: logging.critical("Unsupported instruction %0s", self.instr_name) sys.exit(1)
def rx_bitfield(self): if self._receiver: bits = BitArray(bytes=self._current_buf[1:self._bytes_received]) self._receiver.rx_bitfield(bits)
def validate_checksum_xrb(address: str) -> bool: """Given an xrb/nano/ban address validate the checksum""" if (address[:10] == 'watermelon' and len(address) == 70): # Populate 32-char account index account_map = "13456789abcdefghijkmnopqrstuwxyz" account_lookup = {} for i in range(0, 32): account_lookup[account_map[i]] = BitArray(uint=i, length=5) # Extract key from address (everything after prefix) acrop_key = address[ 4:-8] if address[:10] != 'watermelon' else address[10:-8] # Extract checksum from address acrop_check = address[-8:] # Convert base-32 (5-bit) values to byte string by appending each 5-bit value to the bitstring, essentially bitshifting << 5 and then adding the 5-bit value. number_l = BitArray() for x in range(0, len(acrop_key)): number_l.append(account_lookup[acrop_key[x]]) number_l = number_l[ 4:] # reduce from 260 to 256 bit (upper 4 bits are never used as account is a uint256) check_l = BitArray() for x in range(0, len(acrop_check)): check_l.append(account_lookup[acrop_check[x]]) check_l.byteswap() # reverse byte order to match hashing format # verify checksum h = blake2b(digest_size=5) h.update(number_l.bytes) return h.hexdigest() == check_l.hex return False
#### PROB_THRESHOLD = .7 COUNT_THRESH = 3 #pre-amble and access code data # PREA_AND_ADDR = [PREA_AND_ADDR_STR[st:st+2] for st in range(len(PREA_AND_ADDR_STR)) if st%2==0] # PREA_AND_ADDR_LEN = len(PREA_AND_ADDR); # packet of interest PACKET_BODY_STR = "d373803183ab10953e489039dd3b36236a29f0b0c6f8ba00b9" PACKET_BODY = [ PACKET_BODY_STR[st:st + 2] for st in range(len(PACKET_BODY_STR)) if st % 2 == 0 ] PACKET_BUFFER = BitArray(hex=PACKET_BODY_STR).bin #PARKED_PACKET PACKET_BODY_LEN = len(PACKET_BODY) ##hamming distance map characters = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ] #CHAR_DISTS = {(i,j):bin(int(i,16)^int(j,16)).count('1') for i in characters for j in characters} ##################### ##################### ''' debug and control functions '''
[30, 22, 84, 3], [36, 92, 113, 46], [37, 50, 98, 81], [33, 125, 13, 122], [10, 5, 62, 6], [61, 21, 82, 38], [102, 43, 42, 45], [95, 114, 110, 4], [89, 9, 94, 117], [87, 105, 79, 27], [88, 85, 72, 18], [51, 48, 108, 119], [16, 23, 1, 73], [75, 101, 26, 71], [126, 93, 7, 118], [31, 97, 104, 74], [96, 103, 99, 91], [29, 100, 69, 83], [6, 88, 75, 19], [101, 68, 20, 98], [107, 45, 28, 121], [87, 26, 59, 34], [44, 35, 12, 127], [42, 40, 56, 9], [47, 80, 16, 89], [78, 21, 14, 100], [1, 110, 65, 115], [90, 113, 8, 15], [85, 70, 66, 83], [32, 67, 108, 73], [53, 76, 41, 111], [109, 13, 17, 91], [95, 31, 122, 82], [119, 99, 120, 7], [123, 71, 86, 69], [77, 50, 97, 22], [5, 126, 43, 125], [118, 52, 38, 102], [48, 55, 29, 116], [27, 24, 103, 94], [23, 106, 18, 61], [33, 92, 93, 81], [0, 79, 25, 4], [96, 63, 3, 72], [49, 84, 74, 114], [57, 51, 60, 39], [37, 112, 36, 62], [11, 64, 54, 104], [58, 46, 10, 124], [117, 30, 105, 2]] w = BitArray( '0b01101111110010111001011111001001111111111100101011111000001011111111000110000101010000011011110110100001011101000011001110001010' ) x = encode(K, P, w) assert x == BitArray( '0b011011111100101110010111110010011111111111001010111110000010111111110001100001010100000110111101101000010111010000110011100010101111101110010011110111011101000000000000010100111111000100111101110110001111010100101010011111111100000110011000001111100001001110100110010001100001010010001010100010011100001001100110011010010100001110000111011101110111011011001010111010011101101011011110' ) y = BitArray( '0b000011011100101100000011100000011101101010001000110010000010010111000000000000000000000100001100000000010000000000100001000000100111100110000011010111011001000000000000000000110001000000111101000010001001010000000010000101111000000010011000001110100000000000100100010000000000000000000000000010011100000001000110010000010000000010000011000001000101000011000010000010001001101001001010' ) q = BitArray( '0b111100100011000011011100010011000010010101110110001100000001101000111111101111011110010011110011101110100111111101010010110110001000011001111000101000000100011100001001111110001110000100000010110100100110001110101001111010000111111100000100100001000111011110011011101111110001111010011010110100000011011100101001001010001101111100101100011110110010011000101001111101010110000010010100' ) hat_y = decode(K, P, y, q) assert hat_y is not None hat_w = hat_y[:K] assert hat_w == w
def generate_config_bitstring(self, config_list) -> BitArray: configbits = BitArray(0) if not super().find_block_config(config_list): return configbits db_vector_width = self.db_component["DB_VECTOR_WIDTH"] for i in range(0, 4): value = self.block_config["CONFIGURABLE"]["VALUE_" + f'{i:02d}'] configbits.prepend(BitArray(uint=i, length=db_bitwidths["CHANNEL"])) configbits.prepend( BitArray(uint=self.db_address, length=db_bitwidths["ADDRESS"])) configbits.prepend( BitArray(uint=db_vector_width, length=db_bitwidths["LENGTH"])) configbits.prepend(BitArray(uint=value, length=db_vector_width)) return configbits
def parse_telstatus(stm, b, h): # stm present for debug things, e.g. filter on telescopes tn = stm['telname'] telstatus = {} telstatus['time_mjds'] = b2d(b, 26) # Time stamp [MJD in seconds] # For convenience, also convert directly to MJD telstatus['time_mjd'] = telstatus['time_mjds'] / (24 * 3600.0 ) # Time stamp [MJD] # and to ISO 8601 compliant date-time format “YYYY-MM-DDTHH:MM:SS.sss…” if astropy: telstatus['time_isot'] = at(telstatus['time_mjd'], format='mjd').isot telstatus['jobnum'] = h2s(h, 28) # Job ID number telstatus['jobname'] = b2c(b, 29).replace("\x00", "") # Job ID name telstatus['allocation'] = allocation_to_name(h2s(h, 37)) # Allocation-symbol telstatus['control'] = control_to_name(h2s(h, 38)) # Controller-symbol # Statusflags telstatus['statusflags1'] = BitArray(hex=h2s(h, 39)).bin # See table 4.53 if telstatus['statusflags1'][-2] == '1': telstatus['azmotor'] = True else: telstatus['azmotor'] = False if telstatus['statusflags1'][-3] == '1': telstatus['elmotor'] = True else: telstatus['elmotor'] = False telstatus['statusflags2'] = h2s(h, 40) # See table 4.54 telstatus['statusflags3'] = h2s(h, 41) # See table 4.55 # Read position parts of message: telstatus['actual_azel'] = readpos(b, h, 42) # Actual az/el telstatus['demanded_azel'] = readpos(b, h, 57) # Demanded az/el telstatus['demanded_lonlat'] = readpos(b, h, 72) # Demanded Long/Lat (RA/Dec) telstatus['offsets_azel'] = readoff(b, h) # Read az/el offsets telstatus['source'] = readsource(b, h) # Source data, name etc. telstatus['exp'] = readexp(b, h) # Exp data, exp ID telstatus['receiverstatus'], nextbyte = parse_receivers( b, h) # receiver statuses # Next table should begin at nextbyte telstatus['noisediode_status'], nextbyte = readnoisestatus(b, h, nextbyte) telstatus['DINT_status'], nextbyte = readDINTstatus(b, h, nextbyte) telstatus['tickbox_status'], nextbyte = readtickbox(b, h, nextbyte) telstatus['EDFA_status'], nextbyte = parse_EDFA_status_block( b, h, nextbyte) # TODO: Find why this is needed nextbyte += 1 pherstat, nextbyte = parse_pheripal_status(b, h, nextbyte) pstat, nextbyte = parse_phase_status(b, h, nextbyte) #print("p", pstat, nextbyte) lstat, nextbyte = parse_Lbandlink_status(b, h, nextbyte) #print("l", lstat, nextbyte) optstat, nextbyte = parse_optical_status(b, h, nextbyte) #print('o', optstat, nextbyte) metdata, nextbyte = parse_metdata(b, h, nextbyte) #print('m', metdata, nextbyte) sitestat, nextbyte = parse_sitestatus(b, h, nextbyte) #print('s',sitestat, nextbyte) #print("beforeerror",h[8*nextbyte:]) #print("beforeerror",b[4*nextbyte:]) errors, nextbyte = parse_errors(b, h, nextbyte) #print('e',errors, nextbyte) #print(tn, metdata['drytemp'], metdata['mjds']) return telstatus
def __init__(self, x, y, height, weight, rocky): self.x = BitArray('0b' + bin(x).lstrip('0b').zfill(8)) self.y = BitArray('0b' + bin(y).lstrip('0b').zfill(8)) self.height = BitArray('0b' + bin(height).lstrip('0b').zfill(4)) self.weight = BitArray('0b' + bin(weight).lstrip('0b').zfill(4)) self.rocky = BitArray('0b' + bin(rocky).lstrip('0b').zfill(4))
def testSetItem(self): s = BitArray('0b000100') s[4:5] = '0xf' self.assertEqual(s, '0b000111110') s[0:1] = [1] self.assertEqual(s, '0b100111110')
def testDelSliceErrors(self): a = BitArray(10) del a[5:3] self.assertEqual(a, 10) del a[3:5:-1] self.assertEqual(a, 10)
def hamming_distance(s1, s2): ba1 = BitArray(hex=s1.encode('hex')) ba2 = BitArray(hex=s2.encode('hex')) return (ba1 ^ ba2).count(1)
def main(): # logging.basicConfig(format='%(asctime)s %(filename)s %(funcName)s %(levelname)s %(message)s', # datefmt='%m/%d/%Y %I:%M:%S %p',filename=r'logs/app.log',level=logging.INFO, filemode='w') logging.basicConfig( format= '%(asctime)s %(filename)s %(funcName)s %(levelname)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) logging.info('App started.') parser = argparse.ArgumentParser( description='DNA secret sharing app client') parser.add_argument('-f', help='the full path of the DNA file', required=True, dest='file_name') parser.add_argument('-s', help='server 2 IP - #.#.#.#', required=True, dest='server_ips', nargs=2) parser.add_argument('-d', help='max distance off of the client DNA', dest='dist', required=False, type=int) args = vars(parser.parse_args()) dna = load_file(args['file_name']) try: Client = DNA_App_Client(dna) if args['dist'] is not None: logging.info("Building distance tree") secret_share_tree, seed0, seed1 = Client.build_d_distance_trees( args['dist']) else: logging.info("Building the tree") secret_share_tree, seed0, seed1 = Client.build_secret_share_trees() logging.info("Done building tree") except InvalidDNAException: logging.error( "The input DNA string is invalid, please check DNA string in file") # send server 1 list of tree object, seed, t bit and sec param - thread # send server 2 list of tree object, seed, t bit and sec param - thread # listen to response - should be serialized list of results - both threads # add corresponding items in each thread # try: logging.info("Sending data to servers") comm_client_1 = Comm_client(args['server_ips'][0], tree_root=secret_share_tree, seed=seed0, tbit='0', sec_param=constant.SEC_PARAM) comm_client_2 = Comm_client(args['server_ips'][1], tree_root=secret_share_tree, seed=seed1, tbit='1', sec_param=constant.SEC_PARAM) comm_client_1.start() # comm_client_1.run() # comm_client_2.run() comm_client_2.start() comm_client_1.join() comm_client_2.join() server1_analysis = comm_client_1.analysis server2_analysis = comm_client_2.analysis logging.info("Analyzing results") analysis = (BitArray(bin=server1_analysis) ^ BitArray(bin=server2_analysis)).int if analysis == 0: print "No disease found." else: analysis = log(analysis, 2) print 'The client DNA matches disease # : %d' % (analysis) # for key, index in zip(server1_analysis,range(0,len(server1_analysis))): # analysis1 = BitArray(bin=server1_analysis[key]) # analysis2 = BitArray(bin=server2_analysis[key]) # # print "The risk of being ill of illness # %d is: %d percent. " %(index + 1,(analysis1 ^ analysis2).int) # print analysis1.int # except Exception as e: # logging.error("Something went wrong while communicating with servers") # print sys.exc_info()[0] logging.info('App done.')
def testDelete(self): s = BitArray('0b000000001') del s[-1:] self.assertEqual(s, '0b00000000')
import random import numpy as np import time as tm import estimators_fast_pid as epid n = 5000 a = random.randint(0, 2**(2*n) - 1) b = random.randint(0, 2**n - 1) from bitstring import BitArray A = BitArray(uint=a, length=2*n) B = BitArray(uint=b, length=n) from bitstring import Bits def parity(bytestring): par = 0 string = Bits(bytes=bytestring) for bit in string: par ^= int(bit) return par x = np.zeros((n,), dtype=np.int) y = np.zeros((n,), dtype=np.int) z = np.zeros((n,), dtype=np.int) for i in range(n):
def testReplace(self): s = BitArray('0b01') s.replace('0b1', '0b11') self.assertEqual(s, '0b011')
def testRor(self): s = BitArray('0b1000') s.ror(1) self.assertEqual(s, '0b0100')
def testSliceAssignmentMultipleBitsErrors(self): a = BitArray() self.assertRaises(IndexError, a.__setitem__, 0, '0b00') a += '0b1' a[0:2] = '0b11' self.assertEqual(a, '0b11')
def testOverwriteParameters(self): s = BitArray('0b0000') self.assertRaises(TypeError, s.overwrite, '0b111')
def testSliceAssignmentSingleBitErrors(self): a = BitArray('0b000') self.assertRaises(IndexError, a.__setitem__, -4, '0b1') self.assertRaises(IndexError, a.__setitem__, 3, '0b1') self.assertRaises(TypeError, a.__setitem__, 1, 1.3)
def testOverwrite(self): s = BitArray('0b01110') s.overwrite('0b000', 1) self.assertEqual(s, '0b00000')
def can_2_assemble(vin, v1, v2, v3): seconds, msec = getTime() channel = BitArray(uint=1, length=8) #Channel = 1 1-bytes can_2_segment_type = 66 #0x42 CAN/UPLOAD v = BitArray(bytes=vin, length=17 * 8) # VIN, 17-bytes ts = BitArray(uintbe=seconds, length=4 * 8) # seconds, little-endian 4-bytes tms = BitArray(uintbe=msec, length=2 * 8) # millisecond big-endian 2-bytes st = BitArray(uintbe=can_2_segment_type, length=1 * 8) # Segment Type=0x42 1-bytes can_id = BitArray(uintbe=260, length=4 * 8) #can ID=0x104(260D) 4-bytes dlc = BitArray(uintbe=2, length=1 * 8) #DLC=2 1-bytes d0 = BitArray(8) d1 = BitArray(uint=v1, length=2) d2 = BitArray(uint=v2, length=2) d3 = BitArray(uint=v3, length=2) de = BitArray(2) data = de + d3 + d2 + d1 + d0 # Data 2-bytes data0 = BitArray(bytes=data.bytes[::-1], length=len( data)) # assemble it in reversed order and reverse it to normal later packet = v + ts + tms + st + channel + ts + tms + can_id + dlc + data0 return packet.bytes
print('R_%s = %s' % (i, R[i].bin)) # R_fin = np.array(R[16]) # L_fin = np.array(L[16]) output_pre_permutation = np.concatenate( (split_bitarray(R[16], 4), split_bitarray(L[16], 4)), axis=0) output = do_permutation( BitArray(flatten_list(output_pre_permutation.tolist())), vals.ip_inv) if debug: print('Ciphertext before inverse permutation: ') for element in output_pre_permutation: print(BitArray(element).bin) return BitArray(flatten_list(output)) # The below can be used to validate the functionality of DES_encrypt() as described in # http://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm # x = BitArray('0b 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111') # K = BitArray('0b 00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001') # y = DES_encrypt(x, K, debug=True) # print('\nCiphertext:' + str(y.hex)) # Initialize given values x = BitArray( '0b 00100101 01100111 11001101 10110011 11111101 11001110 01111110 00101010' ) K = BitArray( '0b 11100101 01100111 11001101 10110011 11111101 11001110 01111111 00101010' ) y = DES_encrypt(x, K) print('Ciphertext: %s' % y.hex)
def testPrepend(self): s = BitArray('0b0') s.prepend([1]) self.assertEqual(s, [1, 0])
def testRol(self): s = BitArray('0b0001') s.rol(1) self.assertEqual(s, '0b0010')
def encrypt(self, input_bits): assert(len(input_bits) == BS_BITS) return BitArray(aes.encrypt256(input_bits.bytes))
def __init__(self): # TODO Support for command line argument self.main_program_instr_cnt = 100 # count of main_prog self.sub_program_instr_cnt = [] # count of sub_prog self.debug_program_instr_cnt = 0 # count of debug_rom self.debug_sub_program_instr_cnt = [] # count of debug sub_progrms self.max_directed_instr_stream_seq = 20 # Commenting out for now # self.data_page_pattern = list( # map(lambda dta_pg: dta_pg.name, data_pattern_t)) # dicts for exception_cause_t & interrupt_cause_t Enum classes self.m_mode_exception_delegation = {} self.s_mode_exception_delegation = {} self.m_mode_interrupt_delegation = {} self.s_mode_interrupt_delegation = {} # init_privileged_mode default to MACHINE_MODE self.init_privileged_mode = privileged_mode_t.MACHINE_MODE self.mstatus = BitArray(bin(0b0), length=rcs.XLEN - 1) self.mie = BitArray(bin(0b0), length=rcs.XLEN - 1) self.sstatus = BitArray(bin(0b0), length=rcs.XLEN - 1) self.sie = BitArray(bin(0b0), length=rcs.XLEN - 1) self.ustatus = BitArray(bin(0b0), length=rcs.XLEN - 1) self.uie = BitArray(bin(0b0), length=rcs.XLEN - 1) self.mstatus_mprv = 0 self.mstatus_mxr = 0 self.mstatus_sum = 0 self.mstatus_tvm = 0 self.mstatus_fs = BitArray(bin(0b0), length=2) self.mstatus_vs = BitArray(bin(0b0), length=2) self.mtvec_mode = vsc.rand_enum_t(mtvec_mode_t) self.argv = self.parse_args() self.args_dict = vars(self.argv) self.tvec_alignment = self.argv.tvec_alignment self.fcsr_rm = list(map(lambda csr_rm: csr_rm.name, f_rounding_mode_t)) self.enable_sfence = 0 self.gpr = [] # Helper fields for gpr self.gpr0 = vsc.rand_enum_t(riscv_reg_t) self.gpr1 = vsc.rand_enum_t(riscv_reg_t) self.gpr2 = vsc.rand_enum_t(riscv_reg_t) self.gpr3 = vsc.rand_enum_t(riscv_reg_t) self.scratch_reg = vsc.rand_enum_t(riscv_reg_t) self.pmp_reg = vsc.rand_enum_t(riscv_reg_t) self.sp = vsc.rand_enum_t(riscv_reg_t) self.tp = vsc.rand_enum_t(riscv_reg_t) self.ra = vsc.rand_enum_t(riscv_reg_t) self.check_misa_init_val = 0 self.check_xstatus = 1 self.virtual_addr_translation_on = 0 # Commenting out for now # vector_cfg = riscv_vector_cfg # TODO # pmp_cfg = riscv_pmp_cfg # TODO # self.mem_region = [] # TODO # Self.amo_region = [] # TODO self.stack_len = 5000 # Self.s_mem_region = [] # TODO self.kernel_stack_len = 4000 self.kernel_program_instr_cnt = 400 # list of main implemented CSRs self.invalid_priv_mode_csrs = [] self.num_of_sub_program = self.argv.num_of_sub_program self.instr_cnt = self.argv.instr_cnt self.num_of_tests = self.argv.num_of_tests self.no_data_page = self.argv.no_data_page self.no_branch_jump = self.argv.no_branch_jump self.no_load_store = self.argv.no_load_store self.no_csr_instr = self.argv.no_csr_instr self.no_ebreak = self.argv.no_ebreak self.no_dret = self.argv.no_dret self.no_fence = self.argv.no_fence self.no_wfi = self.argv.no_wfi self.enable_unaligned_load_store = self.argv.enable_unaligned_load_store self.illegal_instr_ratio = self.argv.illegal_instr_ratio self.hint_instr_ratio = self.argv.hint_instr_ratio self.num_of_harts = self.argv.num_of_harts self.fix_sp = self.argv.fix_sp self.use_push_data_section = self.argv.use_push_data_section self.boot_mode_opts = self.argv.boot_mode if self.boot_mode_opts: logging.info("Got boot mode option - %0s", self.boot_mode_opts) if self.boot_mode_opts == "m": self.init_privileged_mode = privileged_mode_t.MACHINE_MODE elif self.boot_mode_opts == "s": self.init_privileged_mode = privileged_mode_t.SUPERVISOR_MODE elif self.boot_mode_opts == "u": self.init_privileged_mode = privileged_mode_t.USER_MODE else: logging.error("Illegal boot mode option - %0s", self.boot_mode_opts) self.enable_page_table_exception = self.argv.enable_page_table_exception self.no_directed_instr = self.argv.no_directed_instr self.asm_test_suffix = self.argv.asm_test_suffix self.enable_interrupt = self.argv.enable_interrupt self.enable_nested_interrupt = self.argv.enable_nested_interrupt self.enable_timer_irq = self.argv.enable_timer_irq self.bare_program_mode = self.argv.bare_program_mode self.enable_illegal_csr_instruction = self.argv.enable_illegal_csr_instruction self.enable_access_invalid_csr_level = self.argv.enable_access_invalid_csr_level self.enable_misaligned_instr = self.argv.enable_misaligned_instr self.enable_dummy_csr_write = self.argv.enable_dummy_csr_write self.randomize_csr = self.argv.randomize_csr self.allow_sfence_exception = self.argv.allow_sfence_exception self.no_delegation = self.argv.no_delegation self.force_m_delegation = self.argv.force_m_delegation self.force_s_delegation = self.argv.force_s_delegation self.support_supervisor_mode = 0 self.disable_compressed_instr = self.argv.disable_compressed_instr self.require_signature_addr = self.argv.require_signature_addr if (self.require_signature_addr): self.signature_addr = int(self.argv.signature_addr, 16) else: self.signature_addr = 0xdeadbeef self.gen_debug_section = self.argv.gen_debug_section self.enable_ebreak_in_debug_rom = self.argv.enable_ebreak_in_debug_rom self.set_dcsr_ebreak = self.argv.set_dcsr_ebreak self.num_debug_sub_program = self.argv.num_debug_sub_program self.enable_debug_single_step = self.argv.enable_debug_single_step self.single_step_iterations = 0 self.set_mstatus_tw = self.argv.set_mstatus_tw self.set_mstatus_mprv = self.argv.set_mstatus_mprv self.min_stack_len_per_program = 10 * (rcs.XLEN / 8) self.max_stack_len_per_program = 16 * (rcs.XLEN / 8) self.max_branch_step = 20 self.reserved_regs = vsc.list_t(vsc.enum_t(riscv_reg_t)) self.enable_floating_point = self.argv.enable_floating_point self.enable_vector_extension = self.argv.enable_vector_extension self.enable_b_extension = self.argv.enable_b_extension self.enable_bitmanip_groups = self.argv.enable_bitmanip_groups self.dist_control_mode = 0 self.category_dist = {} self.march_isa = self.argv.march_isa if (len(self.march_isa) != 0): rcs.supported_isa = self.march_isa if (rcs.supported_isa != 'RV32C'): self.disable_compressed_instr = 1