def send_data(self, sid, sok): emit, recp, max_l = self.sessions_info[sid] late_pid = emit.timeoutd() if late_pid is not None: pak, time_ = emit.buffer[late_pid] emit.buffer[late_pid] = [pak, time.time()] host = "%s.%s.%s"%(pak, common.sign(pak, self.key), self.domain) if DEBUG: print "resend", host return self.reply(host) packet = recp.get_acknak(emit.rt) # extract size from request : specified in payload, minus hash and packet id size = max_l - 10 - 7 - len(packet) data = common.try_read(sok, size) if data: packet = packet + "." + common.dotly(common.b64ly(data), 63) if packet == "0": return self.empty() pak, pid = emit.register_pak(packet) host = "%s.%s.%s"%(pak, common.sign(pak, self.key), self.domain) if DEBUG: print "send", host return self.reply(host)
def __init__(self, rectPosStart, rectPosEnd): """ constructeur (thx captain opbvious) entrées : rectPosStart : Rect. Coordonnées de la position de départ rectPosEnd : Rect. Coordonnées de la position d'arrivée """ #init de la classe-maman pygame.Rect.__init__(self, rectPosStart) self.rectPosStart = rectPosStart self.rectPosEnd = rectPosEnd #calcul des composantes X et Y du vecteur et de la distance A -> B self.vectX = rectPosEnd.x - rectPosStart.x self.distX = abs(self.vectX) self.vectY = rectPosEnd.y - rectPosStart.y self.distY = abs(self.vectY) #détermination des directions X et Y vers lesquels on se déplace. #la direction donne en même temps le pas de déplacement. C'est les valeurs +1 ou -1 #qu'on applique sur les coordonnées, pour passer au pixel suivant. self.stepX = sign(self.vectX) self.stepY = sign(self.vectY) # --- déterminatino du mouvement primaire (main) et du mouvement secondaire --- #2 cas possibles : mouvement prim X, mouvement sec Y, ou vice-versa. #Le mouvement primaire est effectué à chaque pas d'avancement. #Le mouvement secondaire pas forcément. Faut avoir accumulé suffisament de points #dans le compteur de mouvement secondaire. #Le mouvement primaire est celui dont la composante (X ou Y) a la plus grande #distance à faire. Et le mouvement secondaire ben c'est l'autre. if self.distX > self.distY: #le mouvement primaire est sur X self.mainMove = MOVE_ON_X #correspondance distance prim et sec <- distance X et Y (self.distMain, self.distSec) = (self.distX, self.distY) #création de tuple (X, Y) contenant lez mouvements primaires et secondaires. self.mainMoveStep = (self.stepX, 0) self.secMoveStep = (0, self.stepY) else: #le mouvement primaire est sur Y self.mainMove = MOVE_ON_Y #correspondance distance prim et sec <- distance X et Y (self.distMain, self.distSec) = (self.distY, self.distX) #création de tuple (X, Y) contenant lez mouvements primaires et secondaires. self.mainMoveStep = (0, self.stepY) self.secMoveStep = (self.stepX, 0) #et ça c'est le compteur de mouvement secondaire. self.counterMoveSec = 0
def glue(cnt1, cnt2): """return integrated cnt where cnt1, cnt2 are taken from neighbour sets""" if cnt1 is None or cnt2 is None: # unknown set(s) result return None if cnt2 == 0: return cnt1 # cnt2 set is ignored as empty yet sign1, sign2 = co.sign(cnt1), co.sign(cnt2) if sign1 == sign2: return sign1 * (abs(cnt1) + abs(cnt2)) return cnt2
def update(self): animals.Animal.update(self) self.Change() if self.intpos != None: i,j = self.animsearch() self.si = common.sign(i) self.sj = common.sign(j) self._move(i,j) else: self._move_to(self.movingto[0],self.movingto[1])
def update(self): Animal.update(self) self.satiety -= 0.001 if self.intpos != None: i, j = self._find_grass() self.si = common.sign(i) self.sj = common.sign(j) self._move(i, j) if i == 0 and j == 0: # сожрать траву p = interface.user_interface.pl.eat(self.intpos[0], self.intpos[1]) if p != None: self.satiety += p else: self._move_to(self.movingto[0], self.movingto[1])
def send(self, data, ok_, err_, **kwargs): host = "%s.%s.%s"%(data, common.sign(data, self.key), self.domain) if DEBUG: print "send", host q = dns.Query(host, dns.CNAME, dns.IN) d = self.r.queryUDP([q], [2 * self.rt]) if ok_: d.addCallback(ok_, **kwargs) if err_: d.addErrback(err_, **kwargs)
def robinson(coord: GeoCoord) -> MapCoord: lat, lon = coord.lat, coord.lon def robinson_helper(lat: float) -> tuple[float, float]: lat = abs(lat) xx = [radians(5 * i) for i in range(19)] # every 5 deg from 0 to 90 # https://en.wikipedia.org/wiki/Robinson_projection#Formulation X = linear_interpolation(lat, xx, [ 1, 0.9986, 0.9954, 0.99, 0.9822, 0.973, 0.96, 0.9427, 0.9216, 0.8962, 0.8679, 0.835, 0.7986, 0.7597, 0.7186, 0.6732, 0.6213, 0.5722, 0.5322 ]) Y = linear_interpolation(lat, xx, [ 0, 0.062, 0.124, 0.186, 0.248, 0.31, 0.372, 0.434, 0.4958, 0.5571, 0.6176, 0.6769, 0.7346, 0.7903, 0.8435, 0.8936, 0.9394, 0.9761, 1 ]) return X, Y X, Y = robinson_helper(lat) x = 0.8487 * X * lon y = 1.3523 * Y * sign(lat) # remap to [-1, 1] for both x /= 0.8487 * pi y /= 1.3523 return MapCoord(x, y)
def update(self): Animal.update(self) self.satiety -= 0.001 if self.satiety < 0.1: for x in interface.user_interface.an.predators: if common.distance(x.pos, self.pos) < 0.01 and self.i != x.i and self.alive: self.fight(x) for x in interface.user_interface.an.aliens: if common.distance(x.pos, self.pos) < 0.01: self.kill(x) if self.intpos != None: i, j = self.animsearch() self.si = common.sign(i) self.sj = common.sign(j) self._move(i, j) else: self._move_to(self.movingto[0], self.movingto[1])
def guess_session_id(self): self.sid = None for sid in self.sessions_keys: key, sok = self.sessions_keys[sid] signed_portion = ".".join(self.payload) sign_here = common.sign(signed_portion, key) #print(signed_portion, self.hash_, self.name) if sign_here == self.hash_: #print("got key !") self.sid = sid self.sok = sok self.key = key
def logout(self): try: self.sock.sendto("LOGOUT", self.server_address) dos_cookie = self.sock.recv(1024) # Compute current timestamp and encrypt timestamp = datetime.datetime.now().strftime(fmt) encrypted_timestamp = common.aes_encrypt(timestamp, self.shared_key, self.shared_iv) # Sign the message iv = Random.new().read( 16 ) signature_msg = SHA256.new(str(iv)) signature = common.sign(signature_msg, self.priv_key) # Send logout request send_msg_body = common.encode_msg([self.username, iv, signature, encrypted_timestamp]) send_msg = 'LOGOUT' + ',' + dos_cookie + ',' + send_msg_body data = common.send_and_receive(send_msg, self.server_address, self.sock, 2048, 3) if len(data) != 3 : return None decode_data = common.decode_msg(data) iv2 = decode_data[0] serv_signature = decode_data[1] encrypted_status = decode_data[2] # Verify server signature h = SHA256.new(str(iv2)) verifier = PKCS1_v1_5.new(server_pub_key) if verifier.verify(h, str(serv_signature)): # Decrypt status status = common.aes_decrypt(encrypted_status, self.shared_key, self.shared_iv) if status == "LOGOUTSUCCESS": print "Logout successful!" sys.exit() else: print "Logout failed" else: print "Logout failed - invalid signature" return except socket.timeout as e: print "Server is not responding" sys.exit()
def create_ticket(self, requested_user, requesting_user, shared_user_key): requesting_user_pub_key_str = self.get_user_pub_key(requesting_user).exportKey() requested_user_pub_key = self.get_user_pub_key(requested_user) requested_user_pub_key_str = requested_user_pub_key.exportKey() #requested_user_priv_key = self.get_user_priv_key(requested_user).exportKey() now = datetime.datetime.now() expiration_datetime = (now + datetime.timedelta(days=1)).strftime(fmt) # Create a signature iv = Random.new().read( 16 ) signature_msg = SHA256.new(str(iv)) signature = common.sign(signature_msg, server_priv_key) # Encrypt with public key of requested user encrypt_msg = common.encode_msg([iv, signature, shared_user_key, requesting_user, requesting_user_pub_key_str, expiration_datetime]) encrypted_keys, ciphertext = common.public_key_encrypt(encrypt_msg, requested_user_pub_key) return [encrypted_keys, ciphertext]
def ok_(self, reply, **kw): if CORRUPT and random.random() > 0.9: if DEBUG: print "drop !" return self.rt = 0.8 * self.rt + 0.2 * (time.time() - kw['time_sent']) if 'pid' in kw and kw['pid']: if DEBUG: print 'ackd', kw['pid'], self.rt self.emit.ackd([kw['pid']]) #else: #print 'was x pak', self.rt for a in reply.answers: cname = a.payload.name.name if DEBUG: print "recv", cname if CORRUPT and random.random() > 0.9: cname = common.corrupt(cname) if DEBUG: print "corrupt !", repr(cname) data = cname.split('.') signed_part = ".".join(data[:-self.skip]) hash_ = data[-self.skip] sign_here = common.sign(signed_part, self.key) pid = common._b64I(data[-self.skip-1]) if sign_here != hash_: if DEBUG: print "bad sig" # when the other side cant prove it's id, we dont believe in anything he says, even pid... #self.recp.nak.append([pid, time.time()]) return if DEBUG: print "see :", pid preambule_l = common._b64I(data[0]) preambule = data[1:preambule_l] self.emit.nakackd(preambule, rt=self.rt) payload = common.ub64ly("".join(data[(preambule_l + 1):-(self.skip+1)])) self.recp.ack_(pid) self.recp.write_or_pause(self.socket.sendall, pid, payload)
def handle_request(self, data, addr): data = data.split(',', 4) if data[0] == 'AUTH': if len(data) != 3 : return # Decrypt message with our private key and break out message msg = common.public_key_decrypt(data[1], data[2], self.priv_key) decoded_msg = common.decode_msg(msg) connected_uname = decoded_msg[0] encr_ticket_key = decoded_msg[1] encr_ticket_ciphert = decoded_msg[2] iv2 = decoded_msg[3] signature = decoded_msg[4] encrypted_nonce = decoded_msg[5] # Decrypt ticket ticket = common.public_key_decrypt(encr_ticket_key, encr_ticket_ciphert, self.priv_key) ticket = common.decode_msg(ticket) if len(ticket) != 6 : return iv = ticket[0] serv_signature = ticket[1] shared_user_key = ticket[2] requesting_user = ticket[3] requesting_user_pub_key_str = ticket[4] expiration_datetime_str = ticket[5] # Verify ticket is not expired and username from ticket matches requesting username expiration_timestamp = '' try: expiration_timestamp = datetime.datetime.strptime(expiration_datetime_str, fmt) except ValueError: return # Check offset!!! if common.is_timestamp_current(expiration_timestamp + time_offset) != True : return if requesting_user != connected_uname: return # Verify server's signature h = SHA256.new(str(iv)) verifier = PKCS1_v1_5.new(server_pub_key) if verifier.verify(h, str(serv_signature)): # Now verify signature of initiating user requesting_user_pub_key = RSA.importKey(requesting_user_pub_key_str) h = SHA256.new(str(iv2)) verifier = PKCS1_v1_5.new(requesting_user_pub_key) if verifier.verify(h, str(signature)): # Create signature iv3 = Random.new().read( 16 ) signature_msg = SHA256.new(str(iv3)) signature = common.sign(signature_msg, self.priv_key) # Add user to authenticated users self.authenticated_users[requesting_user]['shared_key'] = shared_user_key self.authenticated_users[requesting_user]['shared_iv'] = iv3 self.authenticated_users[requesting_user]['sequence_n'] = int(iv3.encode('hex'), 16) self.authenticated_users[requesting_user]['address'] = addr # Now decrypt nonce, and encrypt back with kab + 1 nonce = common.aes_decrypt(encrypted_nonce, shared_user_key, iv2) incr_shared_key = SHA256.new(str( common.increment_key(shared_user_key) )).digest() our_encrypted_nonce = common.aes_encrypt(nonce, incr_shared_key, iv3) # Send final message back to initiating user, encrypted with their pub key encrypt_msg = common.encode_msg([iv3, signature, our_encrypted_nonce]) encrypted_keys, ciphertext = common.public_key_encrypt(encrypt_msg, requesting_user_pub_key) send_msg = encrypted_keys + "," + ciphertext self.sock.sendto(send_msg, addr) else: return return if data[0] == 'MESSAGE': if len(data) != 4 : return decoded_msg = common.decode_msg(data[1:]) if len(decoded_msg) != 3 : return connected_uname = decoded_msg[0] user_hmac_key = decoded_msg[1] encrypted_msg = decoded_msg[2] # Retrieve session info for user if self.authenticated_users.get(connected_uname) == None : return shared_key = self.authenticated_users[connected_uname]['shared_key'] shared_iv = self.authenticated_users[connected_uname]['shared_iv'] user_addr = self.authenticated_users[connected_uname]['address'] self.authenticated_users[connected_uname]['sequence_n'] += 1 sequence_n = self.authenticated_users[connected_uname]['sequence_n'] # Decrypt message msg = common.aes_decrypt(encrypted_msg, shared_key, shared_iv).split(',',1) if len(msg) != 2 : return user_seq_n = msg[0] user_msg = msg[1] # Verify sequence number matches our sequence number if user_seq_n != str(sequence_n) : return # Verify hmac key hmac_key = hmac.new(shared_key, str(user_seq_n) + ',' + user_msg).digest() if user_hmac_key != hmac_key : return print connected_uname + ': ' + user_msg return else: return
def get_ticket_from_server(self, user): try: self.sock.sendto("TICKET", self.server_address) dos_cookie = self.sock.recv(1024) # Request to talk to given user, sending current timestamp # Please not sure if adding the offset here is legal, please check!!! timestamp = (datetime.datetime.now() + time_offset).strftime(fmt) msg = user + "," + timestamp encrypted_msg = common.aes_encrypt(msg, self.shared_key, self.shared_iv) encoded_encrypted_msg = common.encode_msg([encrypted_msg]) # Send request to server send_msg = "TICKET," + dos_cookie + ',' + self.username + ',' + encoded_encrypted_msg self.sock.settimeout(5) data = common.send_and_receive(send_msg, self.server_address, self.sock, 16384, 1) if len(data) != 1 : return # Decrypt the message with shared key + 1 msg = base64.b64decode( data[0] ) incr_shared_key = SHA256.new(str( common.increment_key(self.shared_key) )).digest() msg = common.aes_decrypt(msg, incr_shared_key, self.shared_iv).split(',', 8) if len(msg) != 8 : return serv_timestamp = msg[0] serv_user_to_talk_to = msg[1] shared_key_ab = msg[2] encr_ticket_key = msg[3] encr_ticket_ciphert = msg[4] user_pk = msg[5] user_ip = msg[6] user_port = msg[7] # Not sure what to do with timestamp offset here!!! if serv_timestamp == timestamp and serv_user_to_talk_to == user: nonce = Random.new().read( 32 ) iv2 = Random.new().read( 16 ) signature_msg = SHA256.new(str(iv2)) signature = common.sign(signature_msg, self.priv_key) # Encrypt nonce with our shared key encrypted_nonce = common.aes_encrypt(nonce, shared_key_ab, iv2) # Encrypt mesage with pub key of the user user_pk = RSA.importKey(user_pk) encrypt_msg = common.encode_msg([self.username, encr_ticket_key, encr_ticket_ciphert, iv2, signature, encrypted_nonce]) encrypted_keys, ciphertext = common.public_key_encrypt(encrypt_msg, user_pk) user_address = (user_ip,int(user_port)) send_msg = "AUTH" + ',' + encrypted_keys + ',' + ciphertext data = common.send_and_receive(send_msg, user_address, self.sock, 2048, 2) if len(data) != 2 : return # Decrypt message with our private key and break out message msg = common.public_key_decrypt(data[0], data[1], self.priv_key) decoded_msg = common.decode_msg(msg) iv3 = decoded_msg[0] signature = decoded_msg[1] encrypted_nonce = decoded_msg[2] # Decrypt nonce with shared key + 1 incr_shared_key = SHA256.new(str( common.increment_key(shared_key_ab) )).digest() connected_nonce = common.aes_decrypt(encrypted_nonce, incr_shared_key, iv3) # Verify nonce is correct if connected_nonce == nonce: self.authenticated_users[serv_user_to_talk_to]['shared_key'] = shared_key_ab self.authenticated_users[serv_user_to_talk_to]['shared_iv'] = iv3 self.authenticated_users[serv_user_to_talk_to]['sequence_n'] = int(iv3.encode('hex'), 16) self.authenticated_users[serv_user_to_talk_to]['address'] = user_address return except socket.timeout as e: print "Server is not responding" sys.exit()
def add_footprint_variant( key: str, name: str, density_level: str, ) -> None: # UUIDs uuid_footprint = _uuid('footprint-{}'.format(key)) uuid_silkscreen = [ _uuid('polygon-silkscreen-{}-{}'.format(quadrant, key)) for quadrant in [1, 2, 3, 4] ] uuid_outline = _uuid('polygon-outline-{}'.format(key)) uuid_courtyard = _uuid('polygon-courtyard-{}'.format(key)) uuid_text_name = _uuid('text-name-{}'.format(key)) uuid_text_value = _uuid('text-value-{}'.format(key)) # Pad excess according to IPC density levels excess = config.excess_by_density(density_level) # Lead contact offsets lead_contact_x_offset = config.lead_span_x / 2 - config.lead_contact_length # this is the inner side of the contact area # Position of the first and last pad pos_first = get_pad_coords(1, config.lead_count, config.pitch, lead_contact_x_offset) pos_last = get_pad_coords(config.lead_count, config.lead_count, config.pitch, lead_contact_x_offset) lines.append(' (footprint {}'.format(uuid_footprint)) lines.append(' (name "{}")'.format(name)) lines.append(' (description "")') # Pads pad_width = config.lead_width + excess.side * 2 pad_length = config.lead_contact_length + excess.heel + excess.toe for p in range(1, config.lead_count + 1): pad_uuid = uuid_pads[p - 1] pad_center_offset_x = config.lead_span_x / 2 - pad_length / 2 + excess.toe pos = get_pad_coords(p, config.lead_count, config.pitch, pad_center_offset_x) pad_rotation = 90.0 if pos.orientation == 'horizontal' else 0.0 lines.append( ' (pad {} (side top) (shape rect)'.format(pad_uuid)) lines.append( ' (position {} {}) (rotation {}) (size {} {}) (drill 0.0)' .format( ff(pos.x), ff(pos.y), ff(pad_rotation), ff(pad_width), ff(pad_length), )) lines.append(' )') # Documentation: Leads for p in range(1, config.lead_count + 1): pad_center_offset_x = config.lead_span_x / 2 - pad_length / 2 pos = get_pad_coords(p, config.lead_count, config.pitch, lead_contact_x_offset) lead_uuid_ctct = uuid_leads1[p - 1] # Contact area lead_uuid_proj = uuid_leads2[p - 1] # Vertical projection # Contact area if pos.orientation == 'horizontal': x1 = ff(pos.x) x2 = ff(pos.x + sign(pos.x) * config.lead_contact_length) y1 = ff(pos.y - config.lead_width / 2) y2 = ff(pos.y + config.lead_width / 2) elif pos.orientation == 'vertical': x1 = ff(pos.x - config.lead_width / 2) x2 = ff(pos.x + config.lead_width / 2) y1 = ff(pos.y) y2 = ff(pos.y + sign(pos.y) * config.lead_contact_length) lines.append(' (polygon {} (layer top_documentation)'.format( lead_uuid_ctct)) lines.append(' (width 0.0) (fill true) (grab_area false)') lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y1)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x2, y1)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x2, y2)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y2)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y1)) lines.append(' )') # Vertical projection, between contact area and body if pos.orientation == 'horizontal': x1 = ff(sign(pos.x) * config.body_size_x / 2) x2 = ff(pos.x) y1 = ff(pos.y - config.lead_width / 2) y2 = ff(pos.y + config.lead_width / 2) elif pos.orientation == 'vertical': x1 = x2 = y1 = y2 = ff(0) x1 = ff(pos.x - config.lead_width / 2) x2 = ff(pos.x + config.lead_width / 2) y1 = ff(sign(pos.y) * config.body_size_y / 2) y2 = ff(pos.y) lines.append(' (polygon {} (layer top_documentation)'.format( lead_uuid_proj)) lines.append(' (width 0.0) (fill true) (grab_area false)') lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y1)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x2, y1)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x2, y2)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y2)) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( x1, y1)) lines.append(' )') # Silkscreen: 1 per quadrant # (Quadrant 1 is at the top right, the rest follows CCW) for quadrant in [1, 2, 3, 4]: uuid = uuid_silkscreen[quadrant - 1] x_min = abs( pos_last.x ) + config.lead_width / 2 + excess.side + silkscreen_offset + line_width / 2 x_max = config.body_size_x / 2 + line_width / 2 y_min = abs( pos_first.y ) + config.lead_width / 2 + excess.side + silkscreen_offset + line_width / 2 y_max = config.body_size_y / 2 + line_width / 2 vertices = [(x_min, y_max), (x_max, y_max), (x_max, y_min)] # Pin 1 marking line if quadrant == 2: vertices.append(( config.lead_span_x / 2 + excess.toe - line_width / 2, y_min, )) lines.append( ' (polygon {} (layer top_placement)'.format(uuid)) lines.append( ' (width {}) (fill false) (grab_area false)'.format( line_width)) sign_x = 1 if quadrant in [1, 4] else -1 sign_y = 1 if quadrant in [1, 2] else -1 for (x, y) in vertices: xx = ff(sign_x * x) yy = ff(sign_y * y) lines.append( ' (vertex (position {} {}) (angle 0.0))'.format( xx, yy)) lines.append(' )') # Documentation outline (fully inside body) outline_x_offset = config.body_size_x / 2 - line_width / 2 outline_y_offset = config.body_size_y / 2 - line_width / 2 lines.append( ' (polygon {} (layer top_documentation)'.format(uuid_outline)) lines.append(' (width {}) (fill false) (grab_area false)'.format( line_width)) oxo = ff(outline_x_offset) # Used for shorter code lines below :) oyo = ff(outline_y_offset) # Used for shorter code lines below :) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( oxo, oyo)) # NE lines.append(' (vertex (position {} -{}) (angle 0.0))'.format( oxo, oyo)) # SE lines.append(' (vertex (position -{} -{}) (angle 0.0))'.format( oxo, oyo)) # SW lines.append(' (vertex (position -{} {}) (angle 0.0))'.format( oxo, oyo)) # NW lines.append(' (vertex (position {} {}) (angle 0.0))'.format( oxo, oyo)) # NE lines.append(' )') # Courtyard x_max = config.lead_span_x / 2 + excess.toe x_mid = config.body_size_x / 2 x_min = abs(pos_last.x) + config.lead_width / 2 + excess.side y_max = config.lead_span_y / 2 + excess.toe y_mid = config.body_size_y / 2 y_min = abs(pos_first.y) + config.lead_width / 2 + excess.side vertices = [ # Starting at top left # Top (-x_min, y_max), (x_min, y_max), (x_min, y_mid), (x_mid, y_mid), (x_mid, y_min), # Right (x_max, y_min), (x_max, -y_min), (x_mid, -y_min), (x_mid, -y_mid), (x_min, -y_mid), # Bottom (x_min, -y_max), (-x_min, -y_max), (-x_min, -y_mid), (-x_mid, -y_mid), (-x_mid, -y_min), # Left (-x_max, -y_min), (-x_max, y_min), (-x_mid, y_min), (-x_mid, y_mid), (-x_min, y_mid), # Back to top (-x_min, y_max), ] lines.append(' (polygon {} (layer {})'.format( uuid_courtyard, 'top_courtyard')) lines.append(' (width {}) (fill false) (grab_area false)'.format( COURTYARD_LINE_WIDTH)) for (x, y) in vertices: xx = ff(x + sign(x) * excess.courtyard) yy = ff(y + sign(y) * excess.courtyard) lines.append(' (vertex (position {} {}) (angle 0.0))'.format( xx, yy)) lines.append(' )') # Labels y_offset = ff(config.lead_span_y / 2 + text_y_offset) text_attrs = '(height {}) (stroke_width 0.2) ' \ '(letter_spacing auto) (line_spacing auto)'.format(pkg_text_height) lines.append( ' (stroke_text {} (layer top_names)'.format(uuid_text_name)) lines.append(' {}'.format(text_attrs)) lines.append( ' (align center bottom) (position 0.0 {}) (rotation 0.0)'. format(y_offset)) lines.append( ' (auto_rotate true) (mirror false) (value "{{NAME}}")') lines.append(' )') lines.append( ' (stroke_text {} (layer top_values)'.format(uuid_text_value)) lines.append(' {}'.format(text_attrs)) lines.append( ' (align center top) (position 0.0 -{}) (rotation 0.0)'. format(y_offset)) lines.append( ' (auto_rotate true) (mirror false) (value "{{VALUE}}")') lines.append(' )') lines.append(' )')
def login_protocol(self, data): if len(data) != 2 : return # Decrypt message with our private key and break out message msg = common.public_key_decrypt(data[0], data[1], server_priv_key) decoded_msg = common.decode_msg(msg) uname = decoded_msg[0] iv1 = decoded_msg[1] signature = decoded_msg[2] encrypted_dh_val = decoded_msg[3] if connected_clients.get(uname) is not None: return # Lookup public key of the user user_pub_key = self.get_user_pub_key(uname) # Verify the user's signature h = SHA256.new(str(uname) + str(iv1)) verifier = PKCS1_v1_5.new(user_pub_key) if verifier.verify(h, str(signature)): print "Signature Verified!" pass_hash = base64.b64decode( self.get_password_hash(uname) ) # Decrypt DH val diff_hell_val = long(common.aes_decrypt(encrypted_dh_val, pass_hash, iv1)) # Create random values nonce1 = Random.new().read( 32 ) iv2 = Random.new().read( 16 ) # Compute our diffie hellman value and encrypt with password hash dh = diffie_hellman.DiffieHellman() serv_dh_key = str(dh.genPublicKey()) serv_dh = common.aes_encrypt(serv_dh_key, pass_hash, iv2) # Establish shared key dh.genKey(diff_hell_val) shared_key = dh.getKey() # Sign the message signature_msg = SHA256.new(str(iv2)) signature = common.sign(signature_msg, server_priv_key ) # Encrypt with public key of user encrypt_msg = common.encode_msg([iv2, signature, serv_dh, nonce1]) encrypted_server_keys, ciphertext = common.public_key_encrypt(encrypt_msg, user_pub_key) # Send message send_msg = encrypted_server_keys + "," + ciphertext data = common.send_and_receive(send_msg, self.client_address, self.socket, 1024, 2) if len(data) != 2 : return rec_msg = common.public_key_decrypt(data[0], data[1], server_priv_key) decoded_msg = common.decode_msg(rec_msg) iv3 = decoded_msg[0] encrypted_user_nonce1 = decoded_msg[1] nonce2 = decoded_msg[2] # Verify user encrypted nonce1 with the shared key user_nonce1 = common.aes_decrypt(encrypted_user_nonce1, shared_key, iv3) if nonce1 == user_nonce1: print "Login Sucess for user: "******"Login Failure for user: "******"The signature is not authentic" return
def f(row): x1, x2 = row return sign(x1**2 + x2**2 - 0.6)
def homotopy_update(A, y, N_iter, tolerance): """ Function: homotopy_update -------------------- uses the homotopy method to solve the equation min||x||_1 subject to A x = y A: sensing matrix y: signal N_iter: maximum number of iterations tolerance: sparsity budget This function solves the equation transpose(A) * A * d = sign(c) by continuously updating (transpose(A) * A)^(-1). returns: the sparse representation vector x """ M, N = A.shape # initialise x to a vector of zeros x = np.zeros(N) # initialise residual vector c = residual_vector(A, y, x) # initialise lambda = ||c||_inf c_inf = np.linalg.norm(c, np.inf) # initialise vector to hold indices of maximum absolute values lambda_indices = np.array([False] * N, dtype=bool) lambda_indices[np.argmax(np.abs(c))] = True # evaluate the first direction vector A_gamma = A[:, lambda_indices] c_gamma = c[lambda_indices] invAtA = 1.0 / (np.linalg.norm(A_gamma)**2) direction = np.zeros(N) direction[lambda_indices] = invAtA * helper.sign(c_gamma, tolerance=tolerance) k = update_x(A, y, x, direction, c_inf, lambda_indices) effective_index = sum(lambda_indices[0:k]) # evaluate homotopy path segments in iterations for i in range(0, N_iter): # update A_gamma and inverse_A_gamma invAtA = upd_inv.one_col_inv(A_gamma, invAtA, effective_index, A[:, k], lambda_indices[k]) A_gamma = A[:, lambda_indices] # update residual vector c = residual_vector(A, y, x) c_gamma = c[lambda_indices] # update direction vector direction.fill(0) direction[lambda_indices] = np.dot( invAtA, helper.sign(c_gamma, tolerance=tolerance)) # find lambda (i.e., infinity norm of residual vector) c_inf = np.linalg.norm(c, np.inf) # print update print("iteration {}\n cinf={}\n c={}\n x={}\n".format( i, c_inf, c, x)) # check if infinity norm of residual vector is within tolerance yet if c_inf < tolerance: break k = update_x(A, y, x, direction, c_inf, lambda_indices) # find where in A_gamma the new index fits in effective_index = sum(lambda_indices[0:k]) return x
def login_to_server(self, password): try: self.sock.sendto("LOGIN", self.server_address) dos_cookie = self.sock.recv(1024) # compute diffie hellman value and encrypt with password hash iv1 = Random.new().read( 16 ) dh = diffie_hellman.DiffieHellman() dh_key = str(dh.genPublicKey()) dh_val = common.aes_encrypt(dh_key, password, iv1) # Sign the message signature_msg = SHA256.new(str(self.username) + str(iv1)) signature = common.sign(signature_msg, self.priv_key) # Encrypt plaintext using server public key encrypt_msg = common.encode_msg([self.username, iv1, signature, dh_val]) encrypted_keys, ciphertext = common.public_key_encrypt(encrypt_msg, server_pub_key) send_msg = "LOGIN," + dos_cookie + "," + encrypted_keys + "," + ciphertext self.sock.settimeout(3) data = common.send_and_receive(send_msg, self.server_address, self.sock, 8192, 2) if len(data) != 2 : return None rec_msg = common.public_key_decrypt(data[0], data[1], self.priv_key) decoded_msg = common.decode_msg(rec_msg) iv2 = decoded_msg[0] signature = decoded_msg[1] encrypted_serv_dh_val = decoded_msg[2] nonce1 = decoded_msg[3] # Verify the signature h = SHA256.new(str(iv2)) verifier = PKCS1_v1_5.new(server_pub_key) if verifier.verify(h, str(signature)): # Decrypt server dh val server_dh_val = long(common.aes_decrypt(encrypted_serv_dh_val, password, iv2)) # Generate shared key dh.genKey(server_dh_val) shared_key = dh.getKey() # Encrypt nonce1 with our shared key nonce2 = Random.new().read( 32 ) iv3 = Random.new().read( 16 ) encrypted_n1 = common.aes_encrypt(nonce1, shared_key, iv3) # Encrypt mesage with pub key of the server encrypt_msg = common.encode_msg([iv3, encrypted_n1, nonce2]) encrypted_keys, ciphertext = common.public_key_encrypt(encrypt_msg, server_pub_key) # Send message send_msg = encrypted_keys + ',' + ciphertext data = common.send_and_receive(send_msg, self.server_address, self.sock, 4096, 2) if len(data) != 2 : return None rec_msg = common.public_key_decrypt(data[0], data[1], self.priv_key) decoded_msg = common.decode_msg(rec_msg) iv4 = decoded_msg[0] encrypted_serv_nonce2 = decoded_msg[1] # Verify user nonce1 value matches the value we sent serv_nonce2 = common.aes_decrypt(encrypted_serv_nonce2, shared_key, iv4) if nonce2 == serv_nonce2: self.shared_key = shared_key self.shared_iv = iv4 print "Successfully logged in!" else: self.shared_key = None print "Login unsuccessful" sys.exit() else: print "Server could not be verified" sys.exit() except socket.timeout as e: print "Server is not responding" sys.exit()
def test_sign(inval: float, outval: str): assert sign(inval) == outval
def _loop_calculate_speeds(self): speeds = self.adjust_speeds( self.current['ha_err'], self.current['de_err'], dagor_motors.MAX_SPEED_HA, dagor_motors.MAX_SPEED_DE, ) b = 200 if self.config['rough'] else 400 # HA: ha_speed = self.slope( speeds['speed_ha'], self.current['ha_err'], a=20, b=b) ha_speed = self.speed_real_to_motor( ha_speed, dagor_motors.MAX_SPEED_HA) ha_speed = min( ha_speed, conf.MOTORS['speed_limit'] * speeds[ 'speed_ha'] / dagor_motors.MAX_SPEED_HA) ha_speed = int(ha_speed * sign(self.current['ha_err'])) if not self.config['target_is_static']: ha_speed += dagor_motors.TRACKING_SPEED # DE: de_speed = self.slope(speeds['speed_de'], self.current['de_err'], b=b) de_speed = self.speed_real_to_motor( de_speed, dagor_motors.MAX_SPEED_DE) de_speed = min( de_speed, conf.MOTORS['speed_limit'] * speeds[ 'speed_de'] / dagor_motors.MAX_SPEED_DE) de_speed = int(de_speed * sign(self.current['de_err'])) # TODO This is ugly hardcoded gear direction switch accelerator! OMG! now = datetime.utcnow() if 0 < abs(de_speed) < 15 and de_speed == self._last_de_speed: if self._de_speed_same_since is None: self._de_speed_same_since = now if now - self._de_speed_same_since > timedelta(seconds=2): self._de_warp_speed = True else: self._de_warp_speed = False self._de_speed_same_since = None self._last_de_speed = de_speed if self._de_warp_speed: print "DE WARP SPEED!!!!!!......" de_speed *= 8 if self.config['target_is_static']: if 0 < abs(ha_speed) < 15 and ha_speed == self._last_ha_speed: if self._ha_speed_same_since is None: self._ha_speed_same_since = now if now - self._ha_speed_same_since > timedelta(seconds=2): self._ha_warp_speed = True else: self._ha_warp_speed = False self._ha_speed_same_since = None self._last_ha_speed = ha_speed if self._ha_warp_speed: print "HA WARP SPEED!!!!!!......" ha_speed *= 8 # limit total speed: sum_speed = abs(ha_speed) + abs(de_speed) if sum_speed > conf.TRACKING['total_speed_limit']: correct_factor = conf.TRACKING['total_speed_limit'] / sum_speed ha_speed *= correct_factor de_speed *= correct_factor # all done: self.current.update( ha_speed=int(round(ha_speed)), de_speed=int(round(de_speed)), )