def purchase(self, node_to_ask, contract): """ Send an order message to the vendor. Args: node_to_ask: a `dht.node.Node` object contract: a complete `Contract` object containing the buyer's order """ def parse_response(response): try: address = contract.contract["buyer_order"]["order"]["payment"]["address"] chaincode = contract.contract["buyer_order"]["order"]["payment"]["chaincode"] masterkey_b = contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"] buyer_key = derive_childkey(masterkey_b, chaincode) amount = contract.contract["buyer_order"]["order"]["payment"]["amount"] listing_hash = contract.contract["buyer_order"]["order"]["ref_hash"] verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:]) verify_key.verify( str(address) + str(amount) + str(listing_hash) + str(buyer_key), response[1][0]) return response[1][0] except Exception: return False 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.callOrder(node_to_ask, pkephem, ciphertext) self.log.info("purchasing contract %s from %s" % (contract.get_contract_id().encode("hex"), node_to_ask)) return d.addCallback(parse_response)
def _checkInitiate(self, clientID, data, host_port): cookieNonce, encryptedCookie, nonce = _initiateStruct.unpack_from(data) try: decryptedCookie = self._secretBox.decrypt(encryptedCookie, 'c' * 8 + cookieNonce) except CryptoError: return clientShortPubkey = PublicKey(decryptedCookie[:32]) serverShortKey = PrivateKey(decryptedCookie[32:]) serverShortClientShort = Box(serverShortKey, clientShortPubkey) try: decrypted = serverShortClientShort.decrypt(data[176:], 'CurveCP-client-I' + nonce) except CryptoError: return clientPubkeyString, vouchNonce, encryptedVouch, serverDomain = _initiateInnerStruct.unpack_from(decrypted) clientPubkey = PublicKey(clientPubkeyString) serverLongClientLong = Box(self.serverKey.key, clientPubkey) try: vouchKey = serverLongClientLong.decrypt(encryptedVouch, 'CurveCPV' + vouchNonce) except CryptoError: return if vouchKey != str(clientShortPubkey): return transport = CurveCPServerTransport( self.reactor, self.serverKey, self.factory, clientID, clientPubkey, host_port, serverShortClientShort, dnsToName(serverDomain)) return transport, decrypted[352:]
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 rpc_order(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) v = c.verify(sender.pubkey) if v is True: 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["vendor_offer"]["listing"]["contract_id"] signature = self.signing_key.sign( str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64] c.await_funding(self.get_notification_listener(), self.multiplexer.blockchain, signature, False) return [signature] else: self.log.warning("received invalid order from %s reason %s" % (sender, v)) return ["False"] except Exception, e: self.log.error("Exception (%s) occurred processing order from %s" % (e.message, sender)) return ["False"]
def parse_messages(messages): if messages is not None: for message in messages: try: value = objects.Value() value.ParseFromString(message) try: box = Box(PrivateKey(self.signing_key.encode()), PublicKey(value.valueKey)) ciphertext = value.serializedData plaintext = box.decrypt(ciphertext) p = objects.Plaintext_Message() p.ParseFromString(plaintext) signature = p.signature p.ClearField("signature") verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:]) verify_key.verify(p.SerializeToString(), signature) h = nacl.hash.sha512(p.signed_pubkey) pow_hash = h[64:128] if int(pow_hash[:6], 16) >= 50 or hexlify(p.sender_guid) != h[:40]: raise Exception('Invalid guid') listener.notify(p.sender_guid, p.encryption_pubkey, p.subject, objects.Plaintext_Message.Type.Name(p.type), p.message) except Exception: pass signature = self.signing_key.sign(value.valueKey)[:64] self.kserver.delete(self.kserver.node.id, value.valueKey, signature) except Exception: pass
def rpc_message(self, sender, pubkey, encrypted): try: box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey)) plaintext = box.decrypt(encrypted) p = PlaintextMessage() p.ParseFromString(plaintext) signature = p.signature p.ClearField("signature") verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:]) verify_key.verify(p.SerializeToString(), signature) h = nacl.hash.sha512(p.signed_pubkey) pow_hash = h[64:128] if int(pow_hash[:6], 16) >= 50 or p.sender_guid.encode("hex") != h[:40] or p.sender_guid != sender.id: raise Exception('Invalid guid') self.log.info("received a message from %s" % sender) self.router.addContact(sender) for listener in self.listeners: try: verifyObject(MessageListener, listener) listener.notify(p, signature) except DoesNotImplement: pass return ["True"] except Exception: self.log.warning("received invalid message from %s" % sender) return ["False"]
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.get_notification_listener(), 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 vouch(self, public_key): """ given the public key of another user, asymmetrically encrypt the master key. this encryption inherently includes authentication so we don't need to also sign this block. """ assert self._master_key is not None pkey = PublicKey(public_key, encoder=nacl.encoding.HexEncoder) box = Box(self.enc_key, pkey) encrypted = box.encrypt(self._master_key) data = {'version': VERSION, 'key': encrypted.hex()} return json.dumps(data).encode('ascii')
def test_box_decryption(skalice, pkalice, skbob, pkbob, nonce, plaintext, ciphertext): pkbob = PublicKey(pkbob, encoder=HexEncoder) skalice = PrivateKey(skalice, encoder=HexEncoder) box = Box(skalice, pkbob) nonce = binascii.unhexlify(nonce) decrypted = binascii.hexlify( box.decrypt(ciphertext, nonce, encoder=HexEncoder), ) assert decrypted == plaintext
def handle(self, *args, **options): # pylint: disable=too-many-locals, too-many-branches, too-many-statements supports_json = install_supports_jsonfield() bundle = DataBundle.objects.get(pk=options['bundle_pk'][0]) if supports_json is False: bundle.properties = json.loads(bundle.properties) if bundle.encrypted: if 'nonce' in bundle.properties and 'encrypted' in bundle.properties: payload = base64.b64decode(bundle.properties['encrypted']) nonce = base64.b64decode(bundle.properties['nonce']) private_key = PrivateKey(base64.b64decode(settings.PDK_SERVER_KEY).strip()) # pylint: disable=line-too-long public_key = PublicKey(base64.b64decode(settings.PDK_CLIENT_KEY).strip()) # pylint: disable=line-too-long box = Box(private_key, public_key) decrypted_message = box.decrypt(payload, nonce) decrypted = six.text_type(decrypted_message, encoding='utf8') if bundle.compression != 'none': compressed = base64.b64decode(decrypted) if bundle.compression == 'gzip': fio = StringIO.StringIO( compressed) # io.BytesIO for Python 3 gzip_file_obj = gzip.GzipFile(fileobj=fio) payload = gzip_file_obj.read() gzip_file_obj.close() decrypted = payload bundle.properties = json.loads(decrypted) elif 'encrypted' in bundle.properties: print 'Missing "nonce" in encrypted bundle. Cannot decrypt bundle ' + str( bundle.pk) + '. Skipping...' elif 'nonce' in bundle.properties: print 'Missing "encrypted" in encrypted bundle. Cannot decrypt bundle ' + str( bundle.pk) + '. Skipping...' elif bundle.compression != 'none': compressed = base64.b64decode(bundle.properties['payload']) if bundle.compression == 'gzip': fio = StringIO.StringIO(compressed) # io.BytesIO for Python 3 gzip_file_obj = gzip.GzipFile(fileobj=fio) payload = gzip_file_obj.read() gzip_file_obj.close() bundle.properties = json.loads(payload) print json.dumps(bundle.properties, indent=2)
def test_box_decode(): pub = PublicKey( b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) priv = PrivateKey( b"5c2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) b1 = Box(priv, pub) b2 = Box.decode(b1._shared_key) assert b1._shared_key == b2._shared_key
def test_box_optional_nonce(privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext): pubbob = PublicKey(pubbob, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = Box(privalice, pubbob) encrypted = box.encrypt(binascii.unhexlify(plaintext), encoder=HexEncoder) decrypted = binascii.hexlify(box.decrypt(encrypted, encoder=HexEncoder)) assert decrypted == plaintext
def test_box_decryption_combined(privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext): pubbob = PublicKey(pubbob, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = Box(privalice, pubbob) combined = binascii.hexlify( binascii.unhexlify(nonce) + binascii.unhexlify(ciphertext), ) decrypted = binascii.hexlify(box.decrypt(combined, encoder=HexEncoder)) assert decrypted == plaintext
def _update_boxes(self): """Create and set the NaCl boxes.""" if self.election_private_key and self.backend_public_key: self._decryption_box = Box(self.election_private_key, self.backend_public_key) else: self._decryption_box = None if self.election_public_key and self.backend_private_key: self._encryption_box = Box(self.backend_private_key, self.election_public_key) else: self._encryption_box = None
def check_key(public_doctor, challenge, challenge_answer): # Private-key for the system private_system = "d9136c8ba792fef21c9ea11ec80cf3a38cc702e36948ece61c340208b0ac596a" private_system = PrivateKey(bytes.fromhex(private_system)) try: box = Box(private_system, public_doctor) plaintext = box.decrypt(challenge_answer) result = plaintext.decode('utf-8') except: result = None return (result == challenge)
def rpc_dispute_close(self, sender, pubkey, encrypted): try: box = Box(self.signing_key.to_curve25519_private_key(), PublicKey(pubkey)) res = box.decrypt(encrypted) resolution_json = json.loads(res, object_pairs_hook=OrderedDict) close_dispute(resolution_json, self.db, self.get_message_listener(), self.get_notification_listener(), self.multiplexer.testnet) self.router.addContact(sender) self.log.info("Contract dispute closed by %s" % sender) return ["True"] except Exception: self.log.error("unable to parse disputed close message from %s" % sender) return ["False"]
def writeMessage(self, message, address): pubkey = self.getPublicKeyForAddress(address) if pubkey is not None: log.msg('issuing DNSCurve query to', address, system='dnscurve') box = Box(self._key, pubkey) nonce = os.urandom(12) query = ( 'Q6fnvWj8' + str(self._key.public_key) + nonce + box.encrypt(message.toStr(), nonce + '\x00' * 12).ciphertext) self._outstandingDNSCurveQueries[nonce] = box else: query = message.toStr() self.transport.write(query, address)
def handle_N(self, message): """ encryption key negotiation """ pub_key = PublicKey(message[:32]) auth = message[32:64] if blake2b(bytes(pub_key) + get_cas_secret(), encoder=RawEncoder) != auth: raise RuntimeError('Bad Client Auth! %s' % auth) self.client_box = Box(self.private_key, pub_key) if self.debug: print('server public_key: %s' % self.public_key.hex()) print('client public_key: %s' % bytes(pub_key).hex()) return [b'OK']
def get_message_key_ciphertext(captain_room_participant_privkey, room_message_key, member_pubkey): """ As the captain, encrypt the room_message_key for this particular room member with key 'member_pubkey'. """ encryption_box = Box(captain_room_participant_privkey, member_pubkey) message = room_message_key nonce = get_random_bytes(Box.NONCE_SIZE) ciphertext = encryption_box.encrypt(message, nonce) # XXX move to crypto.py return ciphertext
def encrypt_entry(self, entry: str, public_key: str) -> str: entry = entry.encode('utf-8') sk = encode_private_key(self.password) pk = encode_public_key(public_key) box = Box(sk, pk) encrypted = box.encrypt(entry) """ This method will be used to encrypt messages using a 3rd party public key, such as the one that the DS server provides. returns encrypted_message:bytes """ return EM_to_hex(encrypted)
def encrypt_for_perma_payments(message, encoder=encoding.Base64Encoder): """ Basic public key encryption ala pynacl. """ box = Box( PrivateKey( settings.PERMA_PAYMENTS_ENCRYPTION_KEYS['perma_secret_key'], encoder=encoder ), PublicKey( settings.PERMA_PAYMENTS_ENCRYPTION_KEYS['perma_payments_public_key'], encoder=encoder ) ) return box.encrypt(message, encoder=encoder)
def decrypt_from_perma_payments(ciphertext, encoder=encoding.Base64Encoder): """ Decrypt bytes encrypted by perma-payments. """ box = Box( PrivateKey( settings.PERMA_PAYMENTS_ENCRYPTION_KEYS['perma_secret_key'], encoder=encoder ), PublicKey( settings.PERMA_PAYMENTS_ENCRYPTION_KEYS['perma_payments_public_key'], encoder=encoder ) ) return box.decrypt(ciphertext, encoder=encoder)
def encrypt(self, textfile, encfile, noncefile): box = Box(self.sk, self.pk) tfile = open(textfile, 'rb') text = tfile.read() tfile.close() nonce = nacl.utils.random(Box.NONCE_SIZE) nfile = open(noncefile, 'wb') nfile.write(nonce) nfile.close() etext = box.encrypt(text, nonce) efile = open(encfile, 'wb') efile.write(etext) efile.close()
def createMsgA(trec, msgC): MSTID = rrid.randomize(trec["STID"].decode("hex")) msgB = netstring(MSTID) + msgC privkey1 = PrivateKey.generate() pubkey1 = privkey1.public_key.encode() assert len(pubkey1) == 32 transport_pubkey = trec["transport_pubkey"].decode("hex") transport_box = Box(privkey1, PublicKey(transport_pubkey)) boxed = transport_box.encrypt(msgB, os.urandom(Box.NONCE_SIZE)) msgA = b"".join([b"a0:", pubkey1, boxed]) return msgA
def test_login_with_wrong_password(self): """ Ensure we cannot login with wrong authkey """ # our public / private key box box = PrivateKey.generate() # our hex encoded public / private keys user_session_private_key_hex = box.encode( encoder=nacl.encoding.HexEncoder).decode() user_session_public_key_hex = box.public_key.encode( encoder=nacl.encoding.HexEncoder).decode() server_crypto_box = Box( PrivateKey(user_session_private_key_hex, encoder=nacl.encoding.HexEncoder), PublicKey(settings.PUBLIC_KEY, encoder=nacl.encoding.HexEncoder)) login_info_nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) encrypted = server_crypto_box.encrypt( json.dumps({ 'username': self.test_username, 'authkey': make_password( binascii.hexlify(os.urandom( settings.AUTH_KEY_LENGTH_BYTES)).decode()), }).encode("utf-8"), login_info_nonce) login_info_encrypted = encrypted[len(login_info_nonce):] data = { 'login_info': nacl.encoding.HexEncoder.encode(login_info_encrypted).decode(), 'login_info_nonce': nacl.encoding.HexEncoder.encode(login_info_nonce).decode(), 'public_key': user_session_public_key_hex, } url = reverse('authentication_login') models.Token.objects.all().delete() response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data.get('non_field_errors'), [u'USERNAME_OR_PASSWORD_WRONG']) self.assertEqual(models.Token.objects.count(), 0)
def rpc_complete_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) contract_id = c.accept_receipt(self.multiplexer.ws, self.multiplexer.blockchain) self.router.addContact(sender) self.log.info("received receipt for order %s" % contract_id) return ["True"] except Exception: self.log.error("unable to parse receipt from %s" % sender) return ["False"]
def Decript(self, HEX, password, dsupk="jIqYIh2EDibk84rTp0yJcghTPxMWjtrt5NW4yPZk3Cw="): try: sk = encode_private_key(password) pk = encode_public_key(dsupk) box = Box(sk, pk) EM = hex_to_EM(HEX) plaintext = box.decrypt(EM).decode('utf-8') except: plaintext = '__ERROR__' return plaintext
def generate_box(self): self.encrypt = True addr = (self.send_address[0], str(self.send_address[1])) try: public_key = publicKeys[addr] except KeyError: print "connect(): error extracting public key" try: private_key = privateKeys[addr] except KeyError: print "connect(): error extracting privatekey" public_key = publicKeys[addr] if public_key is not None and private_key is not None: self.box = Box(private_key, public_key)
def test_msgA(self): nA, nB, entA, entB = self.make_nodes() msgC = "msgC" trec = json.loads(entA["their_channel_record_json"])["transports"][0] msgA = createMsgA(trec, msgC) pubkey1_s, boxed = parseMsgA(msgA) tpriv = self.tport2[0]["privkey"] b = Box(tpriv, PublicKey(pubkey1_s)) msgB = b.decrypt(boxed) MSTID, msgC2 = parseMsgB(msgB) self.failUnlessEqual(msgC, msgC2)
def rpc_refund(self, sender, pubkey, encrypted): try: box = Box(self.signing_key.to_curve25519_private_key(), PublicKey(pubkey)) refund = box.decrypt(encrypted) refund_json = json.loads(refund, object_pairs_hook=OrderedDict) c = Contract(self.db, hash_value=unhexlify(refund_json["refund"]["order_id"]), testnet=self.multiplexer.testnet) c.process_refund(refund_json, self.multiplexer.blockchain, self.get_notification_listener()) self.router.addContact(sender) self.log.info("order %s refunded by vendor" % refund_json["refund"]["order_id"]) return ["True"] except Exception, e: self.log.error("unable to parse refund message from %s" % sender) return [e.message]
def connect(self, path=None): if path is None: path = Connection.get_socket_path() self.socket.connect(path) message = json.dumps(self.change_public_keys()) self.socket.sendall(message.encode("utf-8")) response = self.get_unencrypted_response() if not response["success"]: raise ResponseUnsuccesfulException self.box = Box(self.private_key, PublicKey(base64.b64decode(response["publicKey"]))) self.nonce = (int.from_bytes(self.nonce, "big") + 1).to_bytes( 24, "big")
def on_post(self, req, resp): configuration = req.context['configuration'] if req.content_length: data = json.load(req.bounded_stream) else: raise Exception("No data.") if 'public_key' not in data: raise Exception("No public key.") db_session = req.context['db_session'] user_public_key = PublicKey(data['public_key'].encode('utf-8'), encoder=nacl.encoding.Base64Encoder) user = db_session.query( db.User).filter(db.User.public_key == user_public_key.encode( nacl.encoding.RawEncoder)).first() if user is None: raise Exception("Public key unknown.") challenge_answer = nacl.utils.random(Box.NONCE_SIZE) challenge_uuid = str(uuid.uuid4()) box = Box(configuration['server_key_pair'], user_public_key) challenge_box = box.encrypt(plaintext=challenge_answer, encoder=nacl.encoding.Base64Encoder) challenge = db.Challenge(uuid=challenge_uuid, user=user, answer_hash=nacl.hash.sha256( challenge_answer, encoder=nacl.encoding.RawEncoder)) db_session.add(challenge) db_session.commit() resp.status = falcon.HTTP_200 resp.body = json.dumps({ 'uuid': challenge_uuid, 'nonce': str(challenge_box.nonce.decode('utf-8')), 'challenge': str(challenge_box.ciphertext.decode('utf-8')) })
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.Plaintext_Message() 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_box_encryption_generates_different_nonces(privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext): pubbob = PublicKey(pubbob, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = Box(privalice, pubbob) nonce_0 = box.encrypt(binascii.unhexlify(plaintext), encoder=HexEncoder).nonce nonce_1 = box.encrypt(binascii.unhexlify(plaintext), encoder=HexEncoder).nonce assert nonce_0 != nonce_1
def encrypt(self, packetID, payload): if packetID == 10100: return payload elif packetID == 10101: self.encryptNonce = Nonce() self.Nonce = Nonce(clientKey=self.pk, serverKey=self.serverKey) self.sharedKey = Box(self.sk, PublicKey(self.serverKey)) return bytes(self.pk) + self.encryptPacket(self.sessionKey + bytes(self.encryptNonce) + payload, self.Nonce) else: return self.encryptPacket(payload)
def test_equivalent_keys_shared_key_getter(self): alices = PrivateKey.generate() alicesP = alices.public_key bobs, bobsprime = self._gen_equivalent_raw_keys_couple() bobsP, bobsprimeP = bobs.public_key, bobsprime.public_key assert bobsP == bobsprimeP box_AB = Box(alices, bobsP) box_BA = Box(bobs, alicesP) box_BprimeA = Box(bobsprime, alicesP) assert box_AB.shared_key() == box_BA.shared_key() assert box_BprimeA.shared_key() == box_BA.shared_key()
def test_msgA(self): nA, nB, entA, entB = self.make_connected_nodes() msgC = "msgC" trec = json.loads(entA["their_channel_record_json"])["transports"][0] msgA = createMsgA(trec, msgC) pubkey1_s, boxed = parseMsgA(msgA) tpriv_hex = self.tports2["local"]["retrieval"]["privkey"] tpriv = PrivateKey(tpriv_hex.decode("hex")) b = Box(tpriv, PublicKey(pubkey1_s)) msgB = b.decrypt(boxed) MSTT, msgC2 = parseMsgB(msgB) self.failUnlessEqual(msgC, msgC2)