def _check_hash(self, x, y): x_hash = uhashlib.sha1(x.encode()) y_hash = uhashlib.sha1(y.encode()) x = x_hash.digest() y = y_hash.digest() if str(x) == str(y): return True else: return False
def _check_hash(self, x, y): x_hash = uhashlib.sha1(x.encode()) y_hash = uhashlib.sha1(y.encode()) x = x_hash.digest() y = y_hash.digest() if str(x) == str(y): print("[Senko] No change") return True else: print("[Senko] Changes detected") return False
def __init__(self, fhandle, mode): self.fd = fhandle self.hasher = hashlib.sha1() self.bread = 0 self.bwrite = 0 self.fileno = self.fd.fileno() self.__class__.FD[self.fileno] = self
def handshake(client): print("<handshake>") header = b"" while header.find(b'\r\n\r\n') == -1: header += client.recv(16) if header.startswith(b'MTU='): return header.decode('utf8') lines = header.split(b"\r\n") d = dict() for line in lines[1:]: if not line: continue header, value = line.split(b": ", 1) d[header] = value # compute Response Key GUID = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11' hash = sha1(d[b'Sec-WebSocket-Key'] + GUID) d = hash.digest() response_key = b64encode(d).strip().decode('ASCII') template = 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n' handshake = template % response_key client.send(handshake.encode()) print("</handshake>") return 'ws'
def server_handshake(self): clr = self.s.makefile("rwb", 0) l = clr.readline() #sys.stdout.write(repr(l)) webkey = None while 1: l = clr.readline() if not l: raise OSError("EOF in headers") if l == b"\r\n": break # sys.stdout.write(l) h, v = [x.strip() for x in l.split(b":", 1)] if DEBUG: print((h, v)) if h == b'Sec-WebSocket-Key': webkey = v if not webkey: raise OSError("Not a websocket request") if DEBUG: print("Sec-WebSocket-Key:", webkey, len(webkey)) respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" respkey = hashlib.sha1(respkey).digest() respkey = binascii.b2a_base64(respkey)[:-1] resp = b'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n' % respkey if DEBUG: print(resp) self.s.send(resp)
def make_respkey(webkey): d = uhashlib.sha1(webkey) d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") respkey = d.digest() respkey = ubinascii.b2a_base64(respkey) # [:-1] # Return with trailing "\n". return respkey
async def initiatewebsocket(w, secwebsocketkey): guid = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" acc = uhashlib.sha1(secwebsocketkey + guid).digest() acc = ubinascii.b2a_base64(acc).strip() await w.awrite(b"HTTP/1.1 101 Switching Protocols\r\n") await w.awrite(b"Upgrade: websocket\r\nConnection: Upgrade\r\n") await w.awrite(b"Sec-WebSocket-Accept: %s\r\n\r\n" % acc)
def __generate_hmac(cls, key, message): """ HMAC-SHA1 implementation https://github.com/python/cpython/blob/3.8/Lib/hmac.py """ key = key.encode() message = message.encode() if len(key) > cls.SHA1_BLOCK_SIZE: key = sha1(key).digest() key += (b'\x00' * (cls.SHA1_BLOCK_SIZE - len(key))) outer, inner = sha1(), sha1() inner.update(bytes((x ^ 0x36) for x in key)) outer.update(bytes((x ^ 0x5C) for x in key)) inner.update(message) outer.update(inner.digest()) hmac = outer.digest() return binascii.b2a_base64(hmac).decode()[:-1]
def receive_ota(host, port, remote_hash): import uhashlib sockaddr = usocket.getaddrinfo(host, port)[0][-1] # You need this object even for numeric addresses sock = usocket.socket() sock.connect(sockaddr) f = open('tmp', 'wb') # write the streamed data to a file # as we might not have enough memory for the entire thing # also calculate hash while streaming _hash = uhashlib.sha1() while True: d = sock.recv(1024) if len(d) == 0: break _hash.update(d) f.write(d) sock.close() f.close() local_hash = hexlify(_hash.digest()).decode('ascii') if local_hash != remote_hash: log("Got a bad file transfer? Hash mismatch") log("Local hash: %s, Remote hash: %s" % (local_hash, remote_hash)) return False log("OTA Received correctly") return True
def websocket_handshake(self, req, writer): try: import ubinascii as binascii import uhashlib as hashlib import uwebsocket as websocket except: import binascii import hashlib import websocket if b"Upgrade" in req.headers and b"Sec-WebSocket-Key" in req.headers: d = hashlib.sha1(req.headers[b"Sec-WebSocket-Key"]) d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") respkey = d.digest() respkey = binascii.b2a_base64(respkey)[:-1] yield from writer.awrite(b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: """ + respkey + b"\r\n\r\n") ws = WSWrapper(req.reader.s, writer) yield from self.websocket_loop(ws) else: yield from picoweb.start_response(writer, status="400") yield from writer.awrite( "400 Missing Upgrade or Sec-WebSocket-Key for websocket connection.\r\n\r\n" ) yield from writer.awrite("Your headers: %s\r\n" % req.headers) return True
def make_respkey(webkey): d = uhashlib.sha1(webkey) d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") respkey = d.digest() respkey = ubinascii.b2a_base64(respkey) #[:-1] # Return with trailing "\n". return respkey
def run(): productKey = "K3I5ZkgyZjkydGli" productSecret = "VUFyVE92YVJmSUNQ" rand = "q9f5UdAlh687grFl0JVuyY6095302ehd" imei = modem.getDevImei() VER = '1' h1 = uhashlib.md5() h1.update(imei + "," + productSecret + "," + rand) SIGN = ubinascii.hexlify(h1.digest()).decode() print("MD5: %s" % SIGN) # 8ab41bc1e5e74fbf9cec16a6e0990d89 DATA = imei + ";" + rand + ";" + SIGN print("DATA: %s " %DATA) h1 = uhashlib.sha1(productSecret) res = ubinascii.hexlify(h1.digest()).decode() print(res) res = uhashlib.hash_sha1(res, 20) print("SHA1(PS) : %s" % res) aes_key = res[0:16].upper() print("aes_key : %s" % aes_key) res = uhashlib.aes_ecb(aes_key, DATA) print(res) raw = uhashlib.hash_base64(res) print(raw) data = productKey + ";" + raw + ";" + VER url = "220.180.239.212:8415" # url = "192.168.25.64:30884" response = request.post(url, data=data) print(response.json()) # 获取到密钥 # {'RESPCODE': 10200, 'RESPMSG': 'SUCCESS', 'SERVERURI': 'mqtt://220.180.239.212:8420', 'DS': 'd5f01bddfc994c037be90ede69399ac0'} return response.json()
def did_it_change(file_to_check: str, file_hash: bytes) -> int: try: with open(file_to_check, "rb") as fp: file_data = fp.read() except OSError: return 1 else: return int(hashlib.sha1(file_data).digest() != file_hash)
def calc_websocket_resp(key): concatkey = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" binarr = uhashlib.sha1(concatkey).digest() #hexstr = ubinascii.hexlify(binarr) #print(hexstr) respkey = ubinascii.b2a_base64(binarr).decode('utf-8').rstrip() #respkey = respkey[:-1] # strips the \n return respkey
def verify_patch(self, patch, received_checksum): h = uhashlib.sha1() h.update(patch) checksum = ubinascii.hexlify(h.digest()).decode() print("Computed checksum: {}".format(checksum)) print("Received checksum: {}".format(received_checksum)) if checksum != received_checksum: self.checksum_failure = True return False return True
def _file_hashs(root): l = os.listdir(root) for f in l: gc.collect() st = os.stat("%s/%s" % (root, f)) if st[0] & 0x4000: # stat.S_IFDIR _file_hashs(root + "/" + f) else: file = root + "/" + f h = sha1() for l in open(file): h.update(l) print(ubinascii.hexlify(h.digest()).decode(), file[1:])
def convertsavepostfile(pname): lgen = flinesplitgen(pname, 80) linebreakhash = uhashlib.sha1(next(lgen)).digest() # get the headers for l in lgen: if l == b'\r\n': break k, v = bytes(l).split(b":") if k == b'Content-Disposition': for s in v.split(b";"): se = s.strip().split(b"=", 1) if len(se) == 2: if se[0] == b"filename": filename = se[1].strip(b'"').decode() log("convpostfile", filename) fout = open(filename, "wb") prelinebreak = b"" # used to handle the linebreak before the breakline for l in lgen: linehash = uhashlib.sha1(l).digest() if linehash == linebreakhash: if not prelinebreak: print("where the prelinebreak?") break if prelinebreak: fout.write(prelinebreak) prelinebreak = b"" if len(l) == 2: prelinebreak = bytes(l) if prelinebreak != b"\r\n": prelinebreak = b"" if not prelinebreak: fout.write(l) fout.close() os.remove(pname)
def _handshake(self, httpResponse): try: key = self._httpCli.GetRequestHeaders().get( 'Sec-WebSocket-Key', None) if key: key += self._handshakeSign r = sha1(key.encode()).digest() r = b2a_base64(r).decode().strip() httpResponse.WriteSwitchProto("websocket", {"Sec-WebSocket-Accept": r}) return True except: pass return False
def tree(path): if (not exists(path)): raise OSError(2, ) if (stat.S_ISDIR(uos.stat(path)[stat.ST_MODE])): l = {} li = listdir(path) for i in li: l[i] = tree(path + '/' + i) return l else: with open(path, "rb") as file: sha1v = sha1() sha1v.update(file.read()) return hexlify(sha1v.digest())
def ducos1(lastBlockHash, expectedHash, difficulty): # Loop from 1 too 100*diff hashcount = 0 for ducos1res in range(100 * int(difficulty) + 1): ducos1 = hashlib.sha1( str(lastBlockHash + str(ducos1res)).encode("utf-8")) ducos1 = ubinascii.hexlify(ducos1.digest()).decode() # Generate hash time.sleep(0.005) hashcount += 1 # Increment hash counter for hashrate calculator # Next line was used for debugging, uncomment it to see the miner work :3 # print(str(ducos1) + " | " + str(expectedHash)) if ducos1 == expectedHash: print("Hash found, sending for feedback...") return [ducos1res, hashcount]
def mysha1(path): try: sh = uhashlib.sha1() f=open(path) while True: data = f.read(1) if not data: break sh.update(data) f.close() return ubinascii.hexlify(sh.digest()).upper() except: print("SHA1 Error") return 0
def ClientHandshake(conn, data): data = data.decode().split('\r') for items in data: if 'Sec-WebSocket-Key' in items: print('Socket handshaking...') key = items.split(': ')[1] resp = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" resp = hashlib.sha1(resp).digest() resp = binascii.b2a_base64(resp)[:-1] response = "HTTP/1.1 101 Switching Protocols\r\n" + \ "Upgrade: websocket\r\n" + \ "Connection: Upgrade\r\n" + \ "Sec-WebSocket-Accept: %s\r\n\r\n" % ( resp.decode("utf-8")) conn.send(response.encode()) print('Client is connected!!!')
def server_handshake(sock): clr = sock.makefile("rwb", 0) l = clr.readline() if DEBUG: print("l: %s" % repr(l)) webkey = None while 1: l = clr.readline() if not l: raise OSError("EOF in headers") if l == b"\r\n": break if DEBUG: print("l: %s" % l) # sys.stdout.write(l) h, v = [x.strip() for x in l.split(b":", 1)] if DEBUG: print("h: %s" % h) print("v: %s" % v) if h == b'Sec-WebSocket-Key': webkey = v if not webkey: raise OSError("Not a websocket request") if DEBUG: print("Sec-WebSocket-Key:", webkey, len(webkey)) d = hashlib.sha1(webkey) d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") respkey = d.digest() respkey = binascii.b2a_base64(respkey)[:-1] if DEBUG: print("respkey:", respkey) sock.send(b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: """) sock.send(respkey) sock.send("\r\n\r\n")
def server_handshake(sock): print("start_handshake") clr = sock.makefile("rwb", 0) l = clr.readline() #sys.stdout.write(repr(l)) webkey = None while 1: l = clr.readline() if not l: raise OSError("EOF in headers") if l == b"\r\n": break # sys.stdout.write(l) h, v = [x.strip() for x in l.split(b":", 1)] if DEBUG: print("h, v:") print((h, v)) if h == b'Sec-WebSocket-Key': webkey = v if not webkey: raise OSError("Not a websocket request") if DEBUG: print("Sec-WebSocket-Key:", webkey, len(webkey)) respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" respkey = hashlib.sha1(respkey).digest() respkey = binascii.b2a_base64(respkey)[:-1] resp = b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: %s\r \r """ % respkey if DEBUG: print(resp) sock.send(resp)
def __load_file(self, conf_file): """Loading configuration file Loads configuration file, server adress, wifi SSID and password Args: conf_file (str): configuration file """ with open(conf_file) as inp: self.conf = json.load(inp) self.conf['SERVER'] = tuple(self.conf['SERVER']) mac = hexlify(network.WLAN().config('mac'), ':') pass_hash = sha1(self.conf['OVR'].encode('utf-8')) pass_hash = hexlify(pass_hash.digest()) self.data['MAC'] = mac.decode('utf-8') self.data['OVR'] = pass_hash.decode('utf-8') self.data['NAME'] = self.conf['NAME']
def dl(url, debug=False): import uhashlib import ubinascii proto, dummy, host, path = url.split("/", 3) ai = socket.getaddrinfo(host, 80) addr = ai[0][4] s = socket.socket() s.settimeout(10) try: s.connect(addr) s.write(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)) size = 0 hash = uhashlib.sha1() t = time.ticks_ms() buf = s.read(2000) assert buf, buf if debug: print("initial response:", buf) header, buf = buf.split(b"\r\n\r\n", 1) #print(header) #print(buf) hash.update(buf) size += len(buf) while 1: buf = s.read(1024) if buf == b"": break hash.update(buf) size += len(buf) sys.stdout.write("%dK\r" % (size >> 10)) # sta.active(False) delta = time.ticks_diff(time.ticks_ms(), t) #print() print("Size :", size) print("Speed: %s bytes/s" % (size / delta * 1000)) print("Elapsed: %s" % (delta / 1000)) sha = str(ubinascii.hexlify(hash.digest()), "ascii") print("SHA1 :", sha) return size, sha finally: s.close()
def websocket_ctl(data_ws): #WebSocket控制 if data_ws.find(b'Connection: Upgrade') != -1: client_key_beg = data_ws.find(b'Sec-WebSocket-Key:') + 19 client_key_end = data_ws.find(b'\r\n', client_key_beg) client_key = data_ws[client_key_beg:client_key_end] #print('client_key:', client_key) #Debug mode server_key = (ubinascii.b2a_base64( uhashlib.sha1(client_key + magic_key).digest()).decode('utf-8')).strip() #print('server_key:', server_key) #Debug mode cl.sendall("%s" % (header_101 % (server_key))) print('[Info]: Open WebSocket!!!') while True: data = cl.recv(1024) #print(data) #Debug mode msg = parse_recv_data(data) #print(msg) #Debug mode if msg.find("control&go-value=") != -1: #前进 #go_value_beg = msg.find("control&go-value=") + 17 #go_value_end = go_value_beg + 2 go_value = int(msg[17:]) + 51 pwm12.duty(go_value) print("go_value:", go_value) #Debug mode if msg.find("control&turn-value=") != -1: #左右 #turn_value_beg = msg.find("control&turn-value=") + 19 #turn_value_end = turn_value_beg + 2 if int(msg[19:]) >= 26: #右转 turn_value = int(msg[19:]) - 26 pwm5.duty(77 - turn_value) print("turn_value:", (77 - turn_value)) #Debug mode if int(msg[19:]) < 26: #左转 turn_value = int(~int(msg[19:]) + 26) pwm5.duty(77 + turn_value) print("turn_value:", (77 + turn_value)) #Debug mode if msg == "Close connection": #正常关闭连接 print('[Info]: Close WebSocket!!!') break elif msg == " ": #非正常关闭连接 print('[Warning]: Abnormal closure WebSocket!!!') break
def __init__(self, repopath, prefixes=[], suite='ndn2013'): self._path = repopath self._prefixes = [] for fn in os.listdir(self._path): t = fn.split('.') if t[0] != 'prefix': continue with open(self._path + '/' + fn, 'rb') as f: buf = f.read() pkt = pycn_lite.lib.suite.multi.decode_wirebytes(buf) if not isinstance(pkt, pycn_lite.lib.packet.InterestPacket): continue self._prefixes.append(pkt._name) for pfx in prefixes: if not pfx in self._prefixes: wb = pfx._suite.enc.encode_interest_wirebytes(pfx._comps) h = sha1() h.update(wb) fn = self._path + '/prefix.' + h.hexdigest()[:24] with open(fn, 'wb') as f: f.write(wb) self._prefixes.append(pfx)
def mining(i, username): addr = usocket.getaddrinfo('51.15.127.80', 2811)[0][-1] soc = usocket.socket() soc.connect(addr) soc.recv(3).decode() while True: try: soc.send(bytes("JOB," + str(username) + ",ESP", "utf8")) # Send job request job = soc.recv(1024).decode() # Get work from pool job = job.split( ",") # Split received data to job (job and difficulty) difficulty = job[2] start = time.time() for result in range(100 * int(difficulty) + 1): # Calculate hash with difficulty ducos1 = str( ubinascii.hexlify( uhashlib.sha1(str(job[0] + str(result))).digest())) if job[1] == ducos1[2:42]: end = time.time() hastime = end - start hashrate = result / hastime soc.send( bytes( str(result) + "," + ",Multithread ESP32 MicroPython", "utf8")) feedback = soc.recv(1024).decode() if feedback == "GOOD": # If result was good print("Thread:", i, "Accepted share", result, "Difficulty", difficulty, "Hashrate", hashrate, "H/s", "Hashtime", hastime) break elif feedback == "BAD": # If result was bad print("Thread:", i, "Rejected share", result, "Difficulty", difficulty) break except Exception as err: print(err)
def get_data(self, req, dest_path=None, hash=False, firmware=False): # Connect to server print("Requesting: {}".format(req)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) s.connect((self.ip, self.port)) # Request File s.sendall(self._http_get(req, "{}:{}".format(self.ip, self.port))) try: content = bytearray() fp = None if dest_path is not None: if firmware: raise Exception("Cannot write firmware to a file") fp = open(dest_path, 'wb') if firmware: pycom.ota_start() h = uhashlib.sha1() # Get data from server result = s.recv(100) start_writing = False while (len(result) > 0): # Ignore the HTTP headers if not start_writing: if "\r\n\r\n" in result: start_writing = True result = result.decode().split("\r\n\r\n")[1].encode() if start_writing: if firmware: pycom.ota_write(result) elif fp is None: content.extend(result) else: fp.write(result) if hash: h.update(result) result = s.recv(100) s.close() if fp is not None: fp.close() if firmware: pycom.ota_finish() except Exception as e: # Since only one hash operation is allowed at Once # ensure we close it if there is an error if h is not None: h.digest() raise e hash_val = ubinascii.hexlify(h.digest()).decode() if dest_path is None: if hash: return (bytes(content), hash_val) else: return bytes(content) elif hash: return hash_val
def sha1Hash(val): return str(hexlify(sha1(val).digest()), 'utf-8')
import sys try: import uhashlib as hashlib except ImportError: try: import hashlib except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") sys.exit() try: hashlib.sha1 except AttributeError: # SHA1 is only available on some ports print("SKIP") sys.exit() sha1 = hashlib.sha1(b'hello') sha1.update(b'world') print(sha1.digest())
import socket addr = socket.getaddrinfo('0.0.0.0', 7000)[0][-1] s = socket.socket() s.bind(addr) s.listen(10) print('listening on', addr) while True: import test cl, addr = s.accept() req = cl.recv(1024) reqToObj = test.requestParse(req) magicString = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" test = uhashlib.sha1(reqToObj['Sec-WebSocket-Key']+magicString) # print('test xxxxxx', uhashlib.sha1("dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest()) accept = test.digest() # print('SHA1AAAAAAAAAAAAAAAAAAAAAAAA',accept) # print('SHA1AAAAAAAAAAAAAAAAAAAAAAAA',accept) a1 = ubinascii.b2a_base64(accept) b1 = a1.decode() # print('xxxxxxxxxxxxxxx', a1.decode()) # print(reqToObj) print('client connected from', addr) cl.send('HTTP/1.1 101 Switching Protocols\n') cl.send('Upgrade: websocket\n') cl.send('Connection: Upgrade\n') cl.send('Sec-WebSocket-Accept: '+ b1 + '\n\n') # www = cl.read() while True:
def socket_handler(listen_s): gc.collect() try: client, remote_addr = listen_s.accept() if not client.readline() == b'GET / HTTP/1.1\r\n': client.close() return ws = None ws_key = None while True: line = client.readline() if line == b'\r\n' or line == b'': break h, v = [x.strip() for x in line.split(b':', 1)] if h == b'Connection': if v == b'Upgrade': ws = True elif h == b'Sec-WebSocket-Key': ws_key = v print(v, h) if not ws: client.close() return print('Got valid socket connection from', remote_addr) d = uhashlib.sha1(ws_key) d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11') client.send(b'\\n' b'HTTP/1.1 101 Switching Protocols\r\n' b'Upgrade: websocket\r\n' b'Connection: Upgrade\r\n' b'Sec-WebSocket-Accept: ') client.send(ubinascii.b2a_base64(d.digest())[:-1]) client.send(b'\r\n\r\n') ws = websocket.websocket(client) def socket_handler_inner(client): global settings cmd = ws.readline().strip() if len(cmd) == 0: ws.close() client.close() return elif cmd == b'get': ws.write(json.dumps(settings)) ws.write(b'OK\n') elif cmd == b'set': settings = json.loads(ws.readline()) ws.write(b'OK\n') elif cmd == b'exec': try: exec(ws.readline()) ws.write(b'OK\n') except Exception as e: print('error', e) ws.write(b'ERROR\n') ws.write(json.dumps(repr(e))) ws.write(b'\n') else: ws.write(b'ERROR\nUnknown action') ws.write(cmd) ws.write(b'\n') client.setblocking(False) client.setsockopt(socket.SOL_SOCKET, 20, socket_handler_inner) gc.collect() except Exception as e: print('Error handing socket:', e)
def encrypt(string): string_hash = uhashlib.sha1(string) string_hash.update(config['SECRET_SALT']) string_hash = string_hash.digest() string_hash = ubinascii.hexlify(string_hash) return string_hash