def get_node(node_to_ask): def parse_response(response): if response[0] and response[1][0] == "True": return True elif not response[0]: contract_dict = json.loads(json.dumps(contract.contract, indent=4), object_pairs_hook=OrderedDict) del contract_dict["vendor_order_confirmation"] del contract_dict["buyer_receipt"] order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex") self.send_message( Node(unhexlify(guid)), contract.contract["vendor_offer"]["listing"]["id"] ["pubkeys"]["encryption"], objects.Plaintext_Message.Type.Value("RECEIPT"), json.dumps(contract.contract["buyer_receipt"]), order_id, store_only=True) return True else: return False if node_to_ask: public_key = contract.contract["vendor_offer"]["listing"][ "id"]["pubkeys"]["encryption"] skephem = PrivateKey.generate() pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder) box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder)) nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = box.encrypt( json.dumps(contract.contract, indent=4), nonce) d = self.protocol.callCompleteOrder(node_to_ask, pkephem, ciphertext) return d.addCallback(parse_response) else: return parse_response([False])
def write_to(self, channel: CHANNEL, event, content, r=None, rekey=0): """ This function creates a write statement after encrypting the message. Parameters ---------- self : USER The user who writes channel : CHANNEL The channel where user writes to event: EVENT The event to write content: str The content of the event r: String The public key of the recipient user rekey: int Indicates which dkey to use (0 = latest, 1 = one before latest, ...) """ # no rekey if r != None: # create a box between owner of a channel and invited user box = Box( self.get_curve_private_key(), PublicKey( crypto_sign_ed25519_pk_to_curve25519(bytes.fromhex(r)))) hkey = bytes.fromhex(self.fid) # rekey necessary else: # create a box containing all members of a channel box = SecretBox(channel.dkeys_bytes()[rekey]) hkey = channel.hkey_bytes() # build message from event and content and encrypt it message = get_message_json(event, content).encode('utf-8') encrypted = box.encrypt(message, encoder=Base64Encoder) # write cyphertext using digest (=cypher) and encrypted message digest = hmac.digest(hkey, encrypted, sha256) self.write_cyphertext(digest, encrypted)
def test_put_password_with_missing_secret_key_nonce(self): """ Tests PUT method on password with missing secret_key_nonce """ url = reverse('password') update_data_nonce = nacl.utils.random(Box.NONCE_SIZE) update_data_nonce_hex = nacl.encoding.HexEncoder.encode( update_data_nonce) crypto_box = Box( PrivateKey(self.user_private_key, encoder=nacl.encoding.HexEncoder), PublicKey(self.verifier_public_key, encoder=nacl.encoding.HexEncoder)) update_data_dec = crypto_box.encrypt( json.dumps({ 'authkey': 'authkey', 'private_key': 'private_key', 'private_key_nonce': 'private_key_nonce', 'secret_key': 'secret_key', }).encode("utf-8"), update_data_nonce) update_data = update_data_dec[len(update_data_nonce):] update_data_hex = nacl.encoding.HexEncoder.encode(update_data) data = { 'username': self.test_username, 'recovery_authkey': self.test_recovery_authkey, 'update_data': update_data_hex.decode(), 'update_data_nonce': update_data_nonce_hex.decode(), } self.client.force_authenticate(user=self.test_user_obj) response = self.client.put(url, data) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def createMsgC(self, payload): c = self.db.execute( "SELECT next_outbound_seqnum, my_signkey," " their_channel_record_json" " FROM addressbook WHERE id=?", (self.cid, )) res = c.fetchone() assert res, "missing cid" next_outbound_seqnum = res["next_outbound_seqnum"] self.db.update( "UPDATE addressbook SET next_outbound_seqnum=?" " WHERE id=?", (next_outbound_seqnum + 1, self.cid), "addressbook", self.cid) self.db.commit() seqnum_s = struct.pack(">Q", next_outbound_seqnum) my_signkey = SigningKey(res["my_signkey"].decode("hex")) privkey2 = PrivateKey.generate() pubkey2 = privkey2.public_key.encode() assert len(pubkey2) == 32 crec = json.loads(res["their_channel_record_json"]) channel_pubkey = crec["channel_pubkey"].decode("hex") channel_box = Box(privkey2, PublicKey(channel_pubkey)) CIDKey = crec["CID_key"].decode("hex") authenticator = b"ce0:" + pubkey2 msgE = "".join([ seqnum_s, netstring(my_signkey.sign(authenticator)), json.dumps(payload).encode("utf-8"), ]) msgD = pubkey2 + channel_box.encrypt(msgE, os.urandom(Box.NONCE_SIZE)) HmsgD = sha256(msgD).digest() CIDToken = build_CIDToken(CIDKey, next_outbound_seqnum) sb = SecretBox(CIDKey) CIDBox = sb.encrypt(seqnum_s + HmsgD + channel_pubkey, os.urandom(sb.NONCE_SIZE)) msgC = "".join([b"c0:", CIDToken, netstring(CIDBox), msgD]) return msgC
async def boxer_fight(self, params: Dict, node: BoxerRemoteNode, ctx: UDPContext, pid: str) -> Dict: # validate params if "target" not in params: return JSONRPCResponseError("0", "protocol error", pid).as_json() tkey = PublicKey(bytes.fromhex(params["target"])) if tkey not in self.nodes: return JSONRPCResponseError("1", "node not found", pid).as_json() elif tkey == ctx.remote_pkey: return JSONRPCResponseError("2", "dont hit yourself", pid).as_json() else: target_node = self.nodes[tkey] fight = BoxerFight(self.fightidmngr.getid()) self.fights[fight.fid] = fight # send fight req to target node resp = await target_node.main_ctx.rpc( "fight", { "with": bytes(node.key).hex(), "fid": fight.fid }, target_node.pcktidmngr.getid()) result = resp["result"] if result == "take": result = fight.fid else: del self.fights[fight.fid] return JSONRPCResponseResult(result, pid).as_json()
def send_message(self, receiving_node, public_key, message_type, message, subject=None, store_only=False): """ Sends a message to another node. If the node isn't online it will be placed in the dht for the node to pick up later. """ pro = Profile(self.db).get() p = objects.PlaintextMessage() p.sender_guid = self.kserver.node.id p.signed_pubkey = self.kserver.node.signed_pubkey p.encryption_pubkey = PrivateKey(self.signing_key.encode()).public_key.encode() p.type = message_type p.message = message if subject is not None: p.subject = subject if pro.handle: p.handle = pro.handle if pro.avatar_hash: p.avatar_hash = pro.avatar_hash p.timestamp = int(time.time()) signature = self.signing_key.sign(p.SerializeToString())[:64] p.signature = signature skephem = PrivateKey.generate() pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder) box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder)) nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = box.encrypt(p.SerializeToString(), nonce) def get_response(response): if not response[0]: ciphertext = box.encrypt(p.SerializeToString().encode("zlib"), nonce) self.kserver.set(digest(receiving_node.id), pkephem, ciphertext) self.log.info("sending encrypted message to %s" % receiving_node.id.encode("hex")) if not store_only: self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response) else: get_response([False])
def test_client(self): from twisted.internet import reactor keydir = self.tmpdir.join('key').strpath yield getProcessOutput('curvecpmakekey', [keydir], env=os.environ) proc = BoringProcess() reactor.spawnProcess( proc, 'curvecpserver', [ 'curvecpserver', '127.0.0.1', keydir, '127.0.0.1', str(self.port), '0' * 32, 'curvecpmessage', 'cat' ], env=os.environ, childFDs={}) self.addCleanup(proc.killMaybe) with open(os.path.join(keydir, 'publickey')) as infile: key = PublicKey(infile.read()) endpoint = endpoints.CurveCPClientEndpoint(reactor, '127.0.0.1', self.port, key, '\x00' * 16) fac = DummyFactory('hello world') yield endpoint.connect(fac) yield self.assertFailure(fac.deferred, CurveCPConnectionDone) proc.transport.signalProcess('TERM') yield self.assertFailure(proc.deferred, ProcessTerminated)
def decrypt_message(input_transmission): # load essential data keys = read_configuration("keys") known_nodes = read_configuration("known_nodes") message = input_transmission["message"] # load localhost's keys receiver_priv_key = Privatekey(keys["private_key"], encoder=nacl.encoding.HexEncoder) # load sender's keys sender_id = input_transmission["sender_id"] sender_pub_key = PublicKey(known_nodes[sender_id]["public_key"]) # decrypt the message decrypt_box = Box(receiver_priv_key, sender_pub_key) decrypted_message = decrypt_box.decrypt(message) # recover the dictionary from message decrypted_message = ast.literal_eval(decrypted_message.decode()) # return decrypted message return decrypted_message
def get_node(node_to_ask, recipient_guid, public_key): def parse_response(response): if not response[0]: self.send_message( Node(unhexlify(recipient_guid)), public_key, objects.Plaintext_Message.Type.Value("DISPUTE"), contract, order_id, store_only=True) if node_to_ask: skephem = PrivateKey.generate() pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder) box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder)) nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = box.encrypt(json.dumps(contract, indent=4), nonce) d = self.protocol.callDisputeOpen(node_to_ask, pkephem, ciphertext) return d.addCallback(parse_response) else: return parse_response([False])
def is_client_challenge_verified(self, challenge): """ this is used by the server side. if i can verify the challenge then return True otherwise return False """ assert len(challenge) == 64 mac = challenge[:32] remote_ephemeral_pub_key = challenge[32:64] h = hmac.HMAC(self.application_key[:32], hashes.SHA512(), backend=default_backend()) h.update(bytes(remote_ephemeral_pub_key)) new_hash = h.finalize()[:32] ok = new_hash == mac self._remote_ephemeral_pub_key = PublicKey(remote_ephemeral_pub_key) self._remote_app_mac = mac self._secret = crypto_scalarmult( bytes(self.local_ephemeral_key.private_key), remote_ephemeral_pub_key) self._hashed_secret = hashlib.sha256(self._secret).digest() return ok
def setup_secure_channel(self): if not self.connected or self.default_ssl: return False private_key = PrivateKey(read_encryption_key('client', 'private'), encoder=HexEncoder) server_public_key = PublicKey(read_encryption_key('server', 'public'), encoder=HexEncoder) print('Client: Keys loaded.') # Receive the secret key generated by the server box = Box(private_key, server_public_key) secret_key = receive_message(self.socket) secret_key = verify_sender(self._connection_verify_key, secret_key) if not secret_key: print('Client: Secret key not received.') return False print('Client: Secret key received.') # Setup symmetric encryption using the secret key secret_key = box.decrypt(secret_key) self._set_secret_key(secret_key) return True
def recv_msg(self, user, packet): ''' INPUT * user : user message is from * packet : encrypted message received OUTPUT * Decrypted message with appropriate ''' dec_packet = encoder.decode(packet) self.send_ratc[user] = PublicKey(dec_packet[:32]) mac_packet = dec_packet[32:64] enc_msg = dec_packet[64:] dh_sec = get_DH_secret(self.recv_ratc[user], self.send_ratc[user]) salt = hashlib.md5(dh_sec).digest() self.root_keys[user] = kdf(self.root_keys[user], slt=salt) box = SecretBox(self.root_keys[user]) msg = box.decrypt(enc_msg) mac = hashlib.pbkdf2_hmac('sha256', msg, self.ad_number[user], 1414) if mac == mac_packet: return msg else: raise Exception('VERIFICATION FAILED: Connection to [' + user + '] aborted.')
def rpc_order(self, sender, pubkey, encrypted): try: box = Box( PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey)) order = box.decrypt(encrypted) c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict), testnet=self.multiplexer.testnet) if c.verify(sender.signed_pubkey[64:]): self.router.addContact(sender) self.log.info( "received an order from %s, waiting for payment..." % sender) payment_address = c.contract["buyer_order"]["order"][ "payment"]["address"] chaincode = c.contract["buyer_order"]["order"]["payment"][ "chaincode"] masterkey_b = c.contract["buyer_order"]["order"]["id"][ "pubkeys"]["bitcoin"] buyer_key = derive_childkey(masterkey_b, chaincode) amount = c.contract["buyer_order"]["order"]["payment"][ "amount"] listing_hash = c.contract["buyer_order"]["order"]["ref_hash"] signature = self.signing_key.sign( str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64] c.await_funding(self.multiplexer.ws, self.multiplexer.blockchain, signature, False) return [signature] else: self.log.warning("received invalid order from %s" % sender) return ["False"] except Exception: self.log.error("unable to decrypt order from %s" % sender) return ["False"]
def rpc_order_confirmation(self, sender, pubkey, encrypted): try: box = Box(self.signing_key.to_curve25519_private_key(), PublicKey(pubkey)) order = box.decrypt(encrypted) c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict), testnet=self.multiplexer.testnet) valid = c.accept_order_confirmation( self.get_notification_listener()) if valid is True: self.router.addContact(sender) self.log.info("received confirmation for order %s" % c.get_order_id()) return ["True"] else: self.log.warning( "received invalid order confirmation from %s" % sender) return [valid] except Exception, e: self.log.error("unable to decrypt order confirmation from %s" % sender) return [str(e.message)]
def __init__(self, iid, db, manager): self.iid = iid self.db = db self.manager = manager c = self.db.execute( "SELECT petname, inviteID, inviteKey," # 0,1,2 " theirTempPubkey," # 3 " nextExpectedMessage," # 4 " myMessages," # 5 " theirMessages" # 6 " FROM invitations WHERE id = ?", (iid, )) res = c.fetchone() if not res: raise KeyError("no pending Invitation for '%d'" % iid) self.petname = res[0] self.inviteID = res[1] self.inviteKey = SigningKey(res[2].decode("hex")) self.theirTempPubkey = None if res[3]: self.theirTempPubkey = PublicKey(res[3].decode("hex")) self.nextExpectedMessage = int(res[4]) self.myMessages = splitMessages(res[5]) self.theirMessages = splitMessages(res[6])
def is_server_challenge_verified(self, challenge): """ this is used by the client side to verify a challenge from the server. if verified returns True, otherwise returns False. """ assert len(challenge) == 64 mac = challenge[:32] remote_ephemeral_pub_key = challenge[32:64] scalar_val = crypto_scalarmult( bytes(self.local_ephemeral_key.private_key), bytes(remote_ephemeral_pub_key)) hmac_key = self.application_key[:32] + scalar_val h = hmac.HMAC(hmac_key, hashes.SHA512(), backend=default_backend()) h.update(bytes(remote_ephemeral_pub_key)) new_hmac = h.finalize()[:32] ok = new_hmac == mac self._remote_ephemeral_pub_key = PublicKey(remote_ephemeral_pub_key) self._remote_app_mac = mac self._secret = crypto_scalarmult( bytes(self.local_ephemeral_key.private_key), remote_ephemeral_pub_key) self._hashed_secret = hashlib.sha256(self._secret).digest() return ok
def submit(srv_pub, keys): global app_priv_key global app_key # url = base_url + submit_port + '/upload' url = 'https://submission.wild-samphire.cdssandbox.xyz/upload' headers = {'Content-Type': 'application/x-protobuf'} ep_req = EncryptedUploadRequest() ep_req.server_public_key = srv_pub ep_req.app_public_key = app_key nonce = bytes.fromhex('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') upload = Upload() upload.timestamp.GetCurrentTime() for key in keys: k = upload.keys.add() k.key_data = key.key_data k.transmission_risk_level = key.transmission_risk_level k.rolling_start_interval_number = key.rolling_start_interval_number k.rolling_period = key.rolling_period upload_str = upload.SerializeToString() upload_box = Box(app_priv_key, PublicKey(srv_pub)) ep_req.nonce = nonce ep_req.payload = upload_box.encrypt(upload_str, nonce)[Box.NONCE_SIZE:] resp = requests.post(url, headers=headers, data=ep_req.SerializeToString()) ep_resp = EncryptedUploadResponse() ep_resp.ParseFromString(resp.content) print(ep_resp)
def decrypt_message(input_transmission): # load essential data keys = read_configuration("keys") known_nodes = read_configuration("known_nodes") message = input_transmission["message"] sender_id = input_transmission["sender_id"] # check if the data is usable if not known_nodes: return None elif sender_id not in known_nodes: logging.warning("recieved message from unknown client", sender_id) return None # load localhost's keys receiver_priv_key = PrivateKey( keys["private_key"], encoder = nacl.encoding.HexEncoder ) # load sender's keys sender_pub_key = PublicKey( known_nodes[sender_id]["public_key"], encoder = nacl.encoding.HexEncoder ) # decrypt the message decrypt_box = Box(receiver_priv_key, sender_pub_key) decrypted_message = decrypt_box.decrypt(message) # recover the dictionary from message decrypted_message = ast.literal_eval(decrypted_message.decode()) # return decrypted message return decrypted_message
def rpc_order_confirmation(self, sender, pubkey, encrypted): try: box = Box( PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey)) order = box.decrypt(encrypted) c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict), testnet=self.multiplexer.testnet) contract_id = c.accept_order_confirmation(self.multiplexer.ws) if contract_id: self.router.addContact(sender) self.log.info("Received confirmation for order %s" % contract_id) return ["True"] else: self.log.error("Received invalid order confirmation from %s" % sender) return ["False"] except Exception: self.log.error("Unable to decrypt order confirmation from %s" % sender) return ["False"]
async def init(self) -> None: whitelist = None if await trio.Path("whitelist").exists(): async with await trio.open_file("whitelist", "r") as wlistf: whitelist = [ PublicKey(bytes.fromhex(line.rstrip())) for line in await wlistf.readlines() ] logger.debug(f"loaded whitelist of size {len(whitelist)}.") if await trio.Path("key").exists(): async with await trio.open_file("key", "r") as keyf: self.key = PrivateKey( bytes.fromhex((await keyf.read()).rstrip())) logger.debug(f"loaded key from file.") self.gate = UDPGate(self.nursery, key=self.key, whitelist=whitelist) await self.gate.bind(self.addr, self.new_connection) return None
def _build_profile_block(username): """Builds the PUBLIC identity block that can be distributed. """ pb = {} # profile block pb['timestamp_signed'] = get_timestamp_seconds() user_storage = LocalStorage(username, readonly=True) with user_storage as us: pb['username'] = us['username'] pb['homeserver'] = us['homeserver'] # WARNING do not accidentally leak keys here pb['keys'] = { 'verify': _get_user_verifykey(us['username']).encode(URLSafeBase64Encoder).decode('utf-8'), 'public': _get_user_publickey(us['username']).encode(URLSafeBase64Encoder).decode('utf-8'), } # TODO construct sigchain pb['previous_keys'] = { str(k): { 'verify': VerifyKey(SigningKey(v['signingkey']).verify_key.encode()).encode(URLSafeBase64Encoder).decode('utf-8'), 'public': PublicKey(PrivateKey(v['privatekey']).public_key.encode()).encode(URLSafeBase64Encoder).decode('utf-8'), } for k, v in us['previous_keys'].items() } # end WARNING # TODO device list return pb
def get_contact_data(own_sk, own_mail, contact_mail, pir_vendor): assert isinstance(contact_mail, str) assert isinstance(own_mail, str) filename = hashlib.sha512(contact_mail).hexdigest() # We need to download the manifest file... rawmanifestdata = raidpirlib.retrieve_rawmanifest(pir_vendor) # ...make sure it is valid... manifestdict = raidpirlib.parse_manifest(rawmanifestdata) # we will check that the files are in the release # find the list of files filelist = raidpirlib.get_filenames_in_release(manifestdict) numberofmirrors = 2 redundancy = None rng = False parallel = False if (manifestdict['blockcount'] < numberofmirrors * 8) and redundancy != None: print "Block count too low to use chunks! Try reducing the block size or add more files to the database." return (None, None, None) # ensure the requested file exists... if filename not in filelist: print "The file", filename, "is not listed in the manifest." return (None, None, None) neededblocks = [] # let's figure out what blocks we need theseblocks = raidpirlib.get_blocklist_for_file(filename, manifestdict) #print filename, theseblocks # add the blocks we don't already know we need to request for blocknum in theseblocks: if blocknum not in neededblocks: neededblocks.append(blocknum) # do the actual retrieval work blockdict = request_blocks_from_mirrors(neededblocks, manifestdict, redundancy, rng, parallel, numberofmirrors) # now we should write out the files contact_pk_raw = raidpirlib.extract_file_from_blockdict( filename, manifestdict, blockdict) # let's check the hash thisfilehash = raidpirlib.find_hash(contact_pk_raw, manifestdict['hashalgorithm']) for fileinfo in manifestdict['fileinfolist']: # find this entry if fileinfo['filename'] == filename: if thisfilehash == fileinfo['hash']: # we found it and it checks out! break else: raise Exception( "Corrupt manifest has incorrect file hash despite passing block hash checks!" ) else: raise Exception("Internal Error: Cannot locate fileinfo in manifest!") assert len(contact_pk_raw) == PUBLICKEY_BYTES contact_pk = PublicKey(contact_pk_raw) box = Box(own_sk, contact_pk) nonce = b'\xaa' * 24 shared_secret = box.encrypt(b'\x55' * 8, nonce) # bytes(contact_mail, 'utf8') for python3 secret_in = hmac.new(shared_secret, bytes(own_mail), hashlib.sha512).digest() secret_out = hmac.new(shared_secret, bytes(contact_mail), hashlib.sha512).digest() return (contact_pk, secret_in, secret_out)
def __init__(self, address, provider_name, provider_pk, private_key=None, port=53, timeout=5): self.address = address self.port = port self.publickey = None self.serial = None self.tcp_only = False self.timeout = timeout if not private_key: self.private = PrivateKey.generate() logging.info('Private Key: %s' % self.private.encode(nacl.encoding.HexEncoder)) # noqa logging.info('Public Key : %s' % self.private.public_key.encode(nacl.encoding.HexEncoder)) # noqa else: self.private = PrivateKey(private_key, nacl.encoding.HexEncoder) try: vk = VerifyKey(provider_pk.replace(':', '').lower(), nacl.encoding.HexEncoder) except Exception: # assume this means we have an address instead of a public key try: answer = dns.resolver.query( provider_pk, rdtype=dns.rdatatype.TXT) fp = b''.join(answer.response.answer[0][0].strings) vk = VerifyKey(fp.decode('ascii').replace(':', '').lower(), nacl.encoding.HexEncoder) except Exception: raise TypeError('No valid public key for %s' % provider_name) question = dns.message.make_query( provider_name, rdtype=dns.rdatatype.TXT) try: answer = dns.query.udp(question, self.address, port=self.port, timeout=self.timeout) if answer.flags & dns.flags.TC: answer = dns.query.tcp(question, self.address, port=self.port, timeout=self.timeout) except dns.exception.Timeout: logging.debug('Failed over UDP, trying TCP') self.tcp_only = True answer = dns.query.tcp(question, self.address, port=self.port, timeout=self.timeout) now = time.time() for possible in answer.answer[0]: possible = b''.join(possible.strings) logging.debug('Possible cert %s' % possible.hex()) (magic, es_version, minor_version, signed) = \ struct.unpack('!4sHH%ss' % (len(possible) - 8), possible) logging.debug('Crytpo version %s' % es_version) if magic != DNSCRYPT_CERT_MAGIC: logging.warn('Bad certificate magic: %s' % magic) continue if es_version != 1: logging.warn('Not using es_version 1') continue try: data = vk.verify(signed) except nacl.exceptions.BadSignatureError: logging.warn('Signature did not match') continue (pk, client_magic, serial, start, expire, _) = \ struct.unpack('!32s8sIII%ss' % (len(data) - 52), data) if start > now: logging.warn('Certification not yet valid: %s' % start) continue if expire < now: logging.warn('Certificate expired %s' % expire) continue if self.serial is None or serial > self.serial: self.publickey = PublicKey(pk) self.serial = serial self.client_magic = client_magic if not self.publickey: raise TypeError('No valid certificate found for %s:%s (%s)' % (self.address, self.port, provider_name)) logging.info('Selected certificate %s' % self.serial) self.__secretbox = Box(self.private, self.publickey)
def set_public_key(self, b64_public_key): self.public_key = PublicKey(Base64Encoder.decode(b64_public_key))
def _get_device_publickey(): privkey = _get_device_privatekey() return PublicKey(privkey.public_key.encode())
def _get_user_publickey(username): user_storage = LocalStorage(username, readonly=True) with user_storage as us: return PublicKey(_get_user_privatekey(username).public_key.encode())
def listen(): global shared_secret global listener_stream global secretNotKnown global nonce global nonce2 global callInProgress p = pyaudio.PyAudio() listener_stream = p.open(format=p.get_format_from_width(WIDTH), channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=Listen_CHUNK) PORT = 50008 #23555#50007 changed to 50007 from 50008 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(('', PORT)) s.listen(1) #caller = threading.Thread(target=call) #caller.start() conn, addr = s.accept() #here the thread waits for a connection global waitingForCall if waitingForCall: if (conn): waitingForCall = False talker = threading.Thread(target=talk) talker.start() control.displayUserInputDuringCall() print('Connected by', addr) time.sleep(2) data = conn.recv(Listen_CHUNK) # #1024 #might need this ? nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) i = 1 print("first data received") print(len(data)) writer.start() #https://github.com/pyca/pynacl/blob/51acad0e34e125378d166d6bb9662408056702e0/tests/test_public.py #alice_box = Box(skalice, pkbob) global skbob pkalice = jsonpickle.decode(firebase.get('/littleboy/pk', None)) pkalice = PublicKey(pkalice, encoder=HexEncoder) bob_box = Box(skbob, pkalice) data = bob_box.decrypt(data) shared_secret = bob_box.shared_key() talk_secret_box = nacl.secret.SecretBox(shared_secret) print("listen:", shared_secret) secretNotKnown = False data = conn.recv(Listen_CHUNK) global callInProgress while data != '': try: data = talk_secret_box.decrypt(data) data = oc.decode(data) jitter_buf.put(data) data = conn.recv(Listen_CHUNK) # #1024 i = i + 1 except Exception: print("Error warning:", sys.exc_info()[0]) print("length of shit data", len(data)) if len(data) == 0: callInProgress = False data = conn.recv(Listen_CHUNK - len(data)) # turrible derter destreryer time.sleep(.05) data = conn.recv(Listen_CHUNK) # #1024s if (not callInProgress): break continue #break listener_stream.stop_stream() listener_stream.close() p.terminate() conn.close() print("listen stopped") callInProgress = False
def listen(): global shared_secret global listener_stream global secretNotKnown global nonce global nonce2 global callInProgress p = pyaudio.PyAudio() listener_stream = p.open(format=p.get_format_from_width(WIDTH), channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=Listen_CHUNK) PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(('', PORT)) s.listen(1) conn, addr = s.accept() # waits for a connection global waitingForCall if waitingForCall: if (conn): waitingForCall = False talker = threading.Thread(target=talk) talker.start() control.displayUserInputDuringCall() print('Connected by', addr) time.sleep(2) data = conn.recv(Listen_CHUNK) i = 1 print("first data received") print(len(data)) writer.start() global skbob pkalice = jsonpickle.decode(firebase.get('/fatman/pk', None)) pkalice = PublicKey(pkalice, encoder=HexEncoder) bob_box = Box(skbob, pkalice) data = bob_box.decrypt(data) shared_secret = bob_box.shared_key() talk_secret_box = nacl.secret.SecretBox(shared_secret) print("listen", shared_secret) secretNotKnown = False data = conn.recv(Listen_CHUNK) while data != '' and callInProgress: try: data = talk_secret_box.decrypt(data) data = oc.decode(data) jitter_buf.put(data) data = conn.recv(Listen_CHUNK) i = i + 1 except Exception: print("listen error warning: ", sys.exc_info()[0]) print("length of excepted data: ", len(data)) if len(data) == 0: callInProgress = False data = conn.recv(Listen_CHUNK - len(data)) time.sleep(.05) data = conn.recv(Listen_CHUNK) if (not callInProgress): break continue listener_stream.stop_stream() listener_stream.close() p.terminate() conn.close() callInProgress = False print("listen stopped")
def __init__(self, sender, receiver): self.sender = sender self.receiver = receiver self.sk = PrivateKey(self.getKey(sender, 'sk'), encoder=HexEncoder) self.pk = PublicKey(self.getKey(receiver, 'pk'), encoder=HexEncoder)
def test_client_protocol(): """ test the secret-handshake client protocol, a 4-way cryptographic handshake protocol. """ vectors = get_test_vectors() application_key = bytes( binascii.a2b_base64(vectors['test1']['application_key'])) client_ephemeral_key = Curve25519KeyPair( PrivateKey( binascii.a2b_base64( vectors['test1']['client_ephemeral_priv_key'])), PublicKey( binascii.a2b_base64(vectors['test1']['client_ephemeral_pub_key']))) client_signing_private_key = SigningKey( binascii.a2b_base64(vectors['test1']['client_signing_priv_key'])) client_signing_key = Ed25519KeyPair(client_signing_private_key, client_signing_private_key.verify_key) server_ephemeral_key = Curve25519KeyPair( PrivateKey( binascii.a2b_base64( vectors['test1']['server_ephemeral_priv_key'])), PublicKey( binascii.a2b_base64(vectors['test1']['server_ephemeral_pub_key']))) server_signing_private_key = SigningKey( binascii.a2b_base64(vectors['test1']['server_signing_priv_key'])) server_signing_key = Ed25519KeyPair(server_signing_private_key, server_signing_private_key.verify_key) client_factory = SecretHandshakeClientFactory( application_key, client_ephemeral_key, client_signing_key, server_signing_key.public_key) client_protocol = client_factory.buildProtocol(None) client_transport = proto_helpers.StringTransport() server_factory = SecretHandshakeServerFactory( application_key, server_ephemeral_key, server_signing_key, ) server_protocol = server_factory.buildProtocol(None) server_transport = proto_helpers.StringTransport() client_protocol.makeConnection(client_transport) server_protocol.makeConnection(server_transport) assert len(client_transport.value()) == 68 server_protocol.dataReceived(client_transport.value()) client_transport.clear() client_protocol.dataReceived(server_transport.value()) server_transport.clear() server_protocol.dataReceived(client_transport.value()) client_transport.clear() client_protocol.dataReceived(server_transport.value()) server_transport.clear() yield client_protocol.when_connected() yield server_protocol.when_connected() server_transport.clear() client_transport.clear() client_protocol.messageSend("Alice was not a bit hurt, and she \ jumped up on to her feet in a moment: she looked up, but it was all \ dark overhead; before her was another long passage, and the White \ Rabbit was still in sight, hurrying down it. There was not a moment \ to be lost: away went Alice like the wind, and was just in time to \ hear it say, as it turned a corner, 'Oh my ears and whiskers, how late \ it's getting!' She was close behind it when she turned the corner, but \ the Rabbit was no longer to be seen: she found herself in a long, low \ hall, which was lit up by a row of lamps hanging from the roof.") server_protocol.dataReceived(client_transport.value()) client_transport.clear() server_protocol.messageSend("There were doors all round the hall, \ but they were all locked; and when Alice had been all the way down \ one side and up the other, trying every door, she walked sadly down \ the middle, wondering how she was ever to get out again.") client_protocol.dataReceived(server_transport.value()) server_transport.clear() client_protocol.messageSend("Suddenly she came upon a little \ three-legged table, all made of solid glass; there was nothing on it \ except a tiny golden key, and Alice's first thought was that it might \ belong to one of the doors of the hall; but, alas! either the locks \ were too large, or the key was too small, but at any rate it would not \ open any of them. However, on the second time round, she came upon a \ low curtain she had not noticed before, and behind it was a little \ door about fifteen inches high: she tried the little golden key in the \ lock, and to her great delight it fitted!") server_protocol.dataReceived(client_transport.value()) client_transport.clear() server_protocol.messageSend("Alice opened the door and found that \ it led into a small passage, not much larger than a rat-hole: she \ knelt down and looked along the passage into the loveliest garden you \ ever saw. How she longed to get out of that dark hall, and wander \ about among those beds of bright flowers and those cool fountains, but \ she could not even get her head through the doorway; 'and even if my \ head would go through,' thought poor Alice, 'it would be of very \ little use without my shoulders. Oh, how I wish I could shut up like a \ telescope! I think I could, if I only knew how to begin.' For, you \ see, so many out-of-the-way things had happened lately, that Alice had \ begun to think that very few things indeed were really impossible.") client_protocol.dataReceived(server_transport.value()) server_transport.clear()