def encrypt(self, message, public_key, base64=True): box = Box(self._private_key, public_key) nonce = nacl.utils.random(Box.NONCE_SIZE) # encrypted = box.encrypt(message, nonce) if base64: encrypted = box.encrypt(message, nonce, encoder=nacl.encoding.Base64Encoder) else: encrypted = box.encrypt(message, nonce) return encrypted
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 encryptTo(self, jid, message): if not jid in self.pk: self.addPubkey(jid) box = Box(self.sk, self.pk[jid]) nonce = nacl.utils.random(Box.NONCE_SIZE) return (nacl.encoding.URLSafeBase64Encoder.encode(nonce).decode('utf-8'), box.encrypt(message.encode('utf-8'), nonce, nacl.encoding.URLSafeBase64Encoder).ciphertext.decode('utf-8'))
def storelogin(identifier, passwordstring, host, port, auth, tls): logindata = { 'user' : identifier, 'passwd' : passwordstring, 'host' : host, 'port' : port, 'auth' : auth, 'tls' : tls } clear_text = json.dumps(logindata) nonce = nacl.utils.random(Box.NONCE_SIZE) box = Box(me_seckey, user_pubkey) encrypted = box.encrypt(clear_text, nonce) signed = me_sigkey.sign(encrypted, encoder=Base64Encoder); data = { 'id' : me_identifier, 'verkey' : me_verkey64, 'pubkey' : me_pubkey64, 'login' : signed } path = '%s.ypom' % identifier fd = open(path, 'w') fd.write(json.dumps(data)) fd.close()
def login(self, uid): a, q = self.pow() if a == -1: raise Exception("Failed to prove work!") if not self.server_key or not self.client_key: raise Exception("Must have keys set to login!") payload = json.dumps({ "timestamp": time.time(), }) box = Box(self.client_key, self.server_key) nonce = nacl.utils.random(Box.NONCE_SIZE) payload = box.encrypt(payload, nonce) r = requests.post(self.url + "/api/login", params={ "powa": a, "powq": q, "nonce": nonce, "payload": base64.b64encode(payload), "uid": uid }) try: r.raise_for_status() except: print r.content raise print r.json()
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)
class CryptoBoxCtx: def __init__(self, privk_path, pubk_path): with open(privk_path, "rb") as privk: self.privk = PrivateKey( load_pem_private_key( privk.read(), password=None, backend=default_backend(), ).private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()), RawEncoder, ) with open(pubk_path, "rb") as pubk: self.pubk = PublicKey( load_pem_public_key( pubk.read(), backend=default_backend(), ).public_bytes(Encoding.Raw, PublicFormat.Raw), RawEncoder, ) self.box = Box(self.privk, self.pubk) def encrypt(self, plain, nonce): return self.box.encrypt(plain, nonce) def decrypt(self, cipher, nonce): return self.box.decrypt(cipher, nonce)
def asymmetric_encryption(ours_private_key, target_public_key, plain_text): '''Encrypt a message with the ours private_key and the public_key used by the target. Args: ours_private_key(bytes): generate from asmmetric_key_generate. target_public_key(bytes): generate from asmmetric_key_generate, but user query from the server, user don't have this key. plain_text(str): the text you want to encrypted. Returns: A dict result_dict. For example: { 'cipher_text': ...(bytes), 'nonce': ...(bytes) } None: error. ''' bytes_text = plain_text.encode() private_key_object = PrivateKey(ours_private_key) public_key_object = PublicKey(target_public_key) try: encrypt_box = Box(private_key_object, public_key_object) nonce = nacl.utils.random(Box.NONCE_SIZE) encrypted = encrypt_box.encrypt(bytes_text, nonce=nonce) except Exception: # print(e.args) return None result_dict = dict() result_dict['cipher_text'] = encrypted.ciphertext result_dict['nonce'] = nonce return result_dict
def send_message(self, receiving_node, public_key, message_type, message, subject=None): """ 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().get() if len(message) > 1500: return 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]: self.kserver.set(digest(receiving_node.id), pkephem, ciphertext) self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
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"] verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:]) verify_key.verify(str(address), 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) return d.addCallback(parse_response)
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)), nacl.signing.VerifyKey(public_key, encoder=nacl.encoding.HexEncoder) .to_curve25519_public_key() .encode(), objects.PlaintextMessage.Type.Value("DISPUTE_OPEN"), json.dumps(contract), order_id, store_only=True, ) if node_to_ask: enc_key = nacl.signing.VerifyKey( public_key, encoder=nacl.encoding.HexEncoder ).to_curve25519_public_key() skephem = PrivateKey.generate() pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder) box = Box(skephem, enc_key) 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 run(args): try: me = Me.get(profile=args.profile) except DoesNotExist: print('You need to run setup first!') return 1 try: recipient = Person.get(email=args.email, profile=args.profile) except DoesNotExist: print('Nobody with email {} exists.'.format(args.email)) return 1 private_key = me.private_key public_key = recipient.public_key try: input_file = open(args.input, 'rb') if args.input else sys.stdin.buffer except FileNotFoundError: print('File does not exist') return 1 output_file = open(args.output, 'wb') if args.output else sys.stdout.buffer box = Box(private_key, public_key) encrypted_message = box.encrypt(input_file.read()) output_file.write(encrypted_message)
class CryptoContext(object): """ Context used for performing cryptography on a stream """ def __init__(self, pubkey, mypriv): super(CryptoContext, self).__init__() self.tcvpub = PublicKey(pubkey) # target's CvPub is unencrypted self.cvpriv = PrivateKey(mypriv, encoder=b64) self.cvpub = self.cvpriv.public_key def precompute(self): self.box = Box(self.cvpriv, self.tcvpub) print("Precomputation done, yay!") pass def encrypt(self, pt): nonce = nacl.utils.random(24) return self.box.encrypt(pt, nonce) def decrypt(self, ct): pt = None try: pt = self.box.decrypt(ct) except Exception as e: print(e) return b'', False else: return pt, True pass
def send_message(self, receiving_node, public_key, message_type, message, subject=None): """ 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().get() if len(message) > 1500: return 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]: self.kserver.set(receiving_node.id, pkephem, ciphertext) self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
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 init(self, password, new=True) -> str: headers = {"Content-Type": "application/json"} tname = j.core.identity.me.tname username = j.core.identity.me.tname.split(".")[0] url = os.path.join(MARKETPLACE_URL, PUBLIC_KEY_ENDPOINT) response = requests.post(url) if response.status_code != 200: raise Exception("Can not get market place publickey") mrkt_pub_key = nacl.public.PublicKey(response.json().encode(), nacl.encoding.Base64Encoder) priv_key = j.core.identity.me.nacl.private_key box = Box(priv_key, mrkt_pub_key) password_encrypted = box.encrypt( password.encode(), encoder=nacl.encoding.Base64Encoder).decode() data = { "threebot_name": tname, "passwd": password_encrypted, "new": new } url = os.path.join(MARKETPLACE_URL, CREATE_USER_ENDPOINT) response = requests.post(url, json=data, headers=headers) if response.status_code != 200: raise j.exceptions.Value( f"can not create user with name:{username}, error={response.text}" ) config_dict = dict(zip(REPO_NAMES, response.json())) for repo_name, serverip in config_dict.items(): print(repo_name, serverip) repo = j.tools.restic.get(repo_name) repo.repo = f"rest:http://{username}:{password}@{serverip}:8000/{username}/" repo.password = password repo.init_repo() repo.save() return j.data.serializers.json.dumps({"data": "backup repos inited"})
def encryptAsymmetric(self, public_key, plaintext, nonce=None, encoder=RawEncoder): """ Encrypts the plaintext message using the given `nonce` (or generates one randomly if omitted) and returns the ciphertext encoded with the encoder. Uses a Box, created using public_key and self.private_key, to encrypt the data. :param public_key: public key used to encrypt and decrypt messages :type public_key: nacl.public.PublicKey :param plaintext: The plain text message to encrypt :type plaintext: str :param nonce: The nonce to use in the encryption, defaults to None :type nonce: bytes, optional :param encoder: The encoder to use to encode the ciphertext, defaults to RawEncoder :type encoder: nacl encoder, optional :return: encrypted plaintext :rtype: nacl.utils.EncryptedMessage """ box = Box(self.private_key, public_key) return box.encrypt(plaintext, nonce, encoder)
def _box(): try: nonce = nacl.utils.random(Box.NONCE_SIZE) box = Box(PrivateKey(privKey), PublicKey(pubKey)) return box.encrypt(msg, nonce) except Exception: return
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])
class CryptoContext(object): """ Context used for performing cryptography on a stream """ def __init__(self, pubkey): super(CryptoContext, self).__init__() self.tcvpub = PublicKey(pubkey, encoder=b64) def keygen(self): self.cvpriv = pk = PrivateKey.generate() self.cvpub = pk.public_key pass def createproposal(self): return self.cvpub.encode() def precompute(self): self.box = Box(self.cvpriv, self.tcvpub) pass def encrypt(self, pt): nonce = nacl.utils.random(24) return self.box.encrypt(pt, nonce) def decrypt(self, ct): pt = None try: pt = self.box.decrypt(ct) except Exception as e: print(e) return b'', False else: return pt, True pass
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"] order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex") self.send_message(Node(unhexlify(guid)), contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["encryption"], objects.Plaintext_Message.Type.Value("ORDER_CONFIRMATION"), json.dumps(contract.contract["vendor_order_confirmation"]), order_id, store_only=True) return True else: return False if node_to_ask: public_key = contract.contract["buyer_order"]["order"]["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.callOrderConfirmation(node_to_ask, pkephem, ciphertext) return d.addCallback(parse_response) else: return parse_response([False])
def processM1(self, msg): #print "processM1", self.petname self.theirTempPubkey = PublicKey(msg) self.db.update( "UPDATE invitations SET theirTempPubkey=?" " WHERE id=?", (self.theirTempPubkey.encode(Hex), self.iid), "invitations", self.iid) # theirTempPubkey will committed by our caller, in the same txn as # the message send my_privkey = self.getMyTempPrivkey() my_channel_record = self.getMyPublicChannelRecord() b = Box(my_privkey, self.theirTempPubkey) signedBody = b"".join([ self.theirTempPubkey.encode(), my_privkey.public_key.encode(), my_channel_record.encode("utf-8") ]) my_sign = self.getMySigningKey() body = b"".join([ b"i0:m2a:", my_sign.verify_key.encode(), my_sign.sign(signedBody) ]) nonce = os.urandom(Box.NONCE_SIZE) nonce_and_ciphertext = b.encrypt(body, nonce) #print "ENCRYPTED n+c", len(nonce_and_ciphertext), nonce_and_ciphertext.encode("hex") #print " nonce", nonce.encode("hex") msg2 = "i0:m2:" + nonce_and_ciphertext self.send(msg2) self.nextExpectedMessage = 2
def POST(self, contact_id, msg): global config contact_found = False for contact in config['contact_list']: if contact.mail == contact_id: contact_found = True if not isinstance(contact.pk, PublicKey): print "Contact has no pk" return '{"status": "failure", "reason": "Error: Friend request still pending."}' box = Box(config['own_sk'], contact.pk) nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = box.encrypt(str(msg), nonce) if contact.secret_out is None: return '{"status": "failure", "reason": "Error: Friend request still pending."}' print 'Sending message...' clientlib.send_message(config['server_pk'], contact.secret_out, ciphertext) message = dict() message["isIncoming"] = False message["isAction"] = False message["message"] = str(msg) message["time"] = time.time() * 1000 contact.chat.insert(0, message) save_config_file(config) return '{"status": "success"}' if not contact_found: return '{"status": "failure", "reason": "Contact not found."}'
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"] order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex") self.send_message(Node(unhexlify(guid)), nacl.signing.VerifyKey( contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"], encoder=nacl.encoding.HexEncoder).to_curve25519_public_key().encode(), objects.PlaintextMessage.Type.Value("ORDER_CONFIRMATION"), json.dumps(contract.contract["vendor_order_confirmation"]), order_id, store_only=True) return True else: return False if node_to_ask: public_key = nacl.signing.VerifyKey( contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"], encoder=nacl.encoding.HexEncoder).to_curve25519_public_key() skephem = PrivateKey.generate() pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder) box = Box(skephem, public_key) nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce) d = self.protocol.callOrderConfirmation(node_to_ask, pkephem, ciphertext) return d.addCallback(parse_response) else: return parse_response([False])
def processM1(self, msg): #print "processM1", self.petname self.theirTempPubkey = PublicKey(msg) self.db.update("UPDATE invitations SET theirTempPubkey=?" " WHERE id=?", (self.theirTempPubkey.encode(Hex), self.iid), "invitations", self.iid) # theirTempPubkey will committed by our caller, in the same txn as # the message send my_privkey = self.getMyTempPrivkey() my_channel_record = self.getMyPublicChannelRecord() b = Box(my_privkey, self.theirTempPubkey) signedBody = b"".join([self.theirTempPubkey.encode(), my_privkey.public_key.encode(), my_channel_record.encode("utf-8")]) my_sign = self.getMySigningKey() body = b"".join([b"i0:m2a:", my_sign.verify_key.encode(), my_sign.sign(signedBody) ]) nonce = os.urandom(Box.NONCE_SIZE) nonce_and_ciphertext = b.encrypt(body, nonce) #print "ENCRYPTED n+c", len(nonce_and_ciphertext), nonce_and_ciphertext.encode("hex") #print " nonce", nonce.encode("hex") msg2 = "i0:m2:"+nonce_and_ciphertext self.send(msg2) self.nextExpectedMessage = 2
def encrypt_text(text, secret_key, rcpt_public_key): """Encrypts a text """ secret_key = PrivateKey(secret_key.decode('hex')) rcpt_public_key = PublicKey(rcpt_public_key.decode('hex')) box = Box(secret_key, rcpt_public_key) return box.encrypt(text, nacl.utils.random(Box.NONCE_SIZE))
def send(self, msg, content_type=None): ''' Send the clear text 'msg' to this user ''' box = Box(me.seckey, self.pubkey) if content_type == None: content_type = 'text/plain; charset:"utf-8"' data = { "_type" : "msg", "timestamp" : time.time(), "content" : b64encode(msg), "content-type" : content_type, } clear_text = json.dumps(data) # This is a nonce, it *MUST* only be used once, but it is not considered # secret and can be transmitted or stored alongside the ciphertext. A # good source of nonce is just 24 random bytes. nonce = nacl.utils.random(Box.NONCE_SIZE) # print "NONCE = ", binascii.hexlify(nonce) encrypted = box.encrypt(clear_text, nonce) signed = me.sigkey.sign(encrypted, encoder=Base64Encoder); # to/from topic = topicname(self.identifier, me.identifier) mqttc.publish(topic, signed, qos=2, retain=False)
def recv_messages(own_sk, server_pk, contacts): assert isinstance(own_sk, PrivateKey) assert isinstance(server_pk, PublicKey) assert isinstance(contacts, list) messages = list() for contact in contacts: if contact.secret_in is None: continue dead_drop = derive_dead_drop_id(contact.secret_in) tmp_sk = PrivateKey.generate() tmp_pk_raw = tmp_sk.public_key.encode(encoder=nacl.encoding.RawEncoder) nonce = nacl.utils.random(Box.NONCE_SIZE) box = Box(tmp_sk, server_pk) ciphertext = box.encrypt(dead_drop, nonce).ciphertext data = to_byte(PACKET_ID_RECV_MSG) + tmp_pk_raw + nonce +\ ciphertext # Create a new Tor TCP socket sock = get_new_socket() try: # Connect to server and send data sock.connect((options['registration_server'], options['registration_server_port'])) sock.sendall(itonb(len(data)) + data) (packet_id, data) = receive_packet(sock) if packet_id != PACKET_ID_RECV_MSG_RESPONSE: raise UserWarning("Unknown packet id: " + str(packet_id)) nonce = increase_nonce(nonce) data = box.decrypt(data, nonce) box = Box(own_sk, contact.pk) current_pos = 0 while (current_pos + 5 < len(data)): # trying to decrypt the message of length `length` length = nbtoi(data[current_pos:current_pos + 4]) current_pos += 4 msg_crypt = data[current_pos:current_pos + length] current_pos += length try: msg = box.decrypt(msg_crypt) print "DECRYPTION SUCCESSFUL", (contact.mail, msg) messages.append((contact.mail, msg)) except Exception as e: print "Decryption not successful", contact.mail finally: sock.close() return messages
def _encrypt_msg(msg, server_pk, client_sk): try: box = Box(client_sk, server_pk) except nacl.exceptions.TypeError: raise OidcAgentCryptError("Malformed encryption key") encrypted = box.encrypt(msg.encode('utf-8'), encoder=Base64Encoder) return "{}:{}:{}".format(len(msg), encrypted.nonce.decode('utf-8'), encrypted.ciphertext.decode('utf-8'))
def get_message_key_ciphertext(self, captain_room_participant_privkey, room_message_key): """As the captain, encrypt the room_message_key for this particular room member.""" encryption_box = Box(captain_room_participant_privkey, self.room_pubkey) message = room_message_key nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = encryption_box.encrypt(message, nonce) # XXX move to crypto.py return ciphertext
def handshake_initiate(private_key, redis_client): try: request = expect_json_request(bottle.request, INITIATE_SCHEMA) symmetric_key = redis_get_cookie( redis_client, request[INITIATE_COOKIE_FIELD]) cookie_sbox = SecretBox(symmetric_key) cookie = cookie_sbox.decrypt( str(request[INITIATE_COOKIE_FIELD]), encoder=Base64Encoder) if len(cookie) != 2 * CURVE25519_KEY_BYTES: bottle.response.status = HTTP_INTERNAL_SERVER_ERROR return {'error': 'An invalid cookie was sent to the client.'} client_transient_pkey = PublicKey(cookie[0:CURVE25519_KEY_BYTES]) transient_skey = PrivateKey(cookie[CURVE25519_KEY_BYTES:]) if request[INITIATE_CLIENT_TRANSIENT_PKEY_FIELD] != \ client_transient_pkey.encode(Base64Encoder): raise InvalidClientRequest( 'Initiate: non matching transient public keys.') vouch_json = open_box(request[INITIATE_VOUCH_FIELD], transient_skey, client_transient_pkey) vouch = parse_and_verify_json(vouch_json, VOUCH_SCHEMA) client_pkey = PublicKey( str(vouch[VOUCH_CLIENT_PKEY_FIELD]), encoder=Base64Encoder) vouch_for_transient_pkey = open_box( vouch[VOUCH_TRANSIENT_KEY_BOX_FIELD], private_key, client_pkey) if vouch_for_transient_pkey != client_transient_pkey.encode(): raise InvalidClientRequest( 'Initiate: non matching transient public keys.') resp = 'I believe you are {} and you want {}'.format( client_pkey.encode(Base64Encoder), vouch[VOUCH_MESSAGE_FIELD]) print(resp) response_nonce = nacl.utils.random(Box.NONCE_SIZE) response_box = Box(transient_skey, client_transient_pkey) response_box_cipher = response_box.encrypt( resp, response_nonce, encoder=Base64Encoder) return {'response': response_box_cipher} except jsonschema.ValidationError as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': str(e)} except InvalidClientRequest as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': str(e)} except MissingCookie as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': str(e)} except CryptoError as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': 'Bad encryption in handshake.'} return {'error': ''}
def cryptoboxEncryptionToBase64(privateKey, publicKey, plaintext): sk = nacl.public.PrivateKey(privateKey) pk = nacl.public.PublicKey(publicKey) box = Box(sk, pk) nonce = generateRandomNonce() encrypted = box.encrypt(plaintext.encode("ascii"), nonce) # output is (24 byte) nonce + ciphertext ciphertextBase64 = base64Encoding(encrypted) return insert_colon(ciphertextBase64, 32)
def __init__(self, vote, private1, public2, private2, public1): self.private1 = private1 self.public2 = public2 self.private2 = private2 self.public = public1 self.vote = vote # testing box = Box(self.private1, self.public2) message = str.encode(vote) self.encrypted = box.encrypt(message)
def test_put_password(self): """ Tests PUT method on password """ url = reverse('password') update_data_nonce = nacl.utils.random(Box.NONCE_SIZE) update_data_nonce_hex = nacl.encoding.HexEncoder.encode(update_data_nonce).decode() crypto_box = Box(PrivateKey(self.user_private_key, encoder=nacl.encoding.HexEncoder), PublicKey(self.verifier_public_key, encoder=nacl.encoding.HexEncoder)) new_authkey = 'authkey' new_private_key = 'private_key' new_private_key_nonce = 'private_key_nonce' new_secret_key = 'secret_key' new_secret_key_nonce = 'secret_key_nonce' update_data_dec = crypto_box.encrypt(json.dumps({ 'authkey': new_authkey, 'private_key': new_private_key, 'private_key_nonce': new_private_key_nonce, 'secret_key': new_secret_key, 'secret_key_nonce': new_secret_key_nonce, }).encode("utf-8"), update_data_nonce) update_data = update_data_dec[len(update_data_nonce):] update_data_hex = nacl.encoding.HexEncoder.encode(update_data).decode() data = { 'username': self.test_username, 'recovery_authkey': self.test_recovery_authkey, 'update_data': update_data_hex, 'update_data_nonce': update_data_nonce_hex, } self.client.force_authenticate(user=self.test_user_obj) response = self.client.put(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) # Update was accepted, now lets check that the old verifier details have been deleted in the database and the # user details like authkey and private / secret key have been updated db_user = models.User.objects.get(pk=self.test_user_obj.id) self.assertEqual(db_user.private_key, new_private_key) self.assertEqual(db_user.private_key_nonce, new_private_key_nonce) self.assertEqual(db_user.secret_key, new_secret_key) self.assertEqual(db_user.secret_key_nonce, new_secret_key_nonce) self.assertTrue(check_password(new_authkey, db_user.authkey)) db_recovery_code = models.Recovery_Code.objects.get(pk=self.test_recovery_code_obj.id) self.assertEqual(db_recovery_code.verifier, '') self.assertIsNone(db_recovery_code.verifier_issue_date)
def encrypt_to_public_key(self, plaindata: bytes, key: bytes): box = Box(self.private_key, PublicKey(key)) nonce = nacl.utils.random(Box.NONCE_SIZE) encrypted_message = box.encrypt(plaindata, nonce) return encrypted_message
def encrypt_data(private_hex, public_hex, message): sk = PrivateKey(private_hex, nacl.encoding.HexEncoder) pk = PublicKey(public_hex, nacl.encoding.HexEncoder) box = Box(sk, pk) nonce = nacl.utils.random(Box.NONCE_SIZE) encoded = box.encrypt(message.encode(), nonce, encoder=nacl.encoding.HexEncoder) return encoded
def submit_key(self): # Request a code headers = {'Authorization': 'Bearer ' + os.environ["KEY"]} r = self.client.post('/new-key-claim', headers=headers) code = r.text.strip('\n') # Claim the code key = PrivateKey.generate() app_public_key = key.public_key.encode( encoder=nacl.encoding.RawEncoder) app_private_key = key._private_key key_claim_request = covidshield_pb2.KeyClaimRequest() key_claim_response = covidshield_pb2.KeyClaimResponse() key_claim_request.one_time_code = code key_claim_request.app_public_key = app_public_key r = self.client.post('/claim-key', data=key_claim_request.SerializeToString()) key_claim_response.ParseFromString(r.content) server_public_key = key_claim_response.server_public_key # Generate random keys keys = [] for i in range(14): en_id = int((time.time() - (i * 86400)) / (60 * 10)) tek = covidshield_pb2.TemporaryExposureKey() tek.key_data = nacl.utils.random(16) tek.transmission_risk_level = 4 tek.rolling_start_interval_number = en_id tek.rolling_period = 144 keys.append(tek) upload = covidshield_pb2.Upload() upload.timestamp.CopyFrom(Timestamp(seconds=int(time.time()))) upload.keys.extend(keys) msg = upload.SerializeToString() box = Box(PrivateKey(app_private_key), PublicKey(server_public_key)) nonce = nacl.utils.random(Box.NONCE_SIZE) signed_payload = box.encrypt(msg, nonce=nonce) encypted_payload = covidshield_pb2.EncryptedUploadRequest() encypted_payload.server_public_key = server_public_key encypted_payload.app_public_key = app_public_key encypted_payload.nonce = nonce encypted_payload.payload = signed_payload.ciphertext self.client.post('/upload', data=encypted_payload.SerializeToString())
def test_box_wrong_length(): with pytest.raises(ValueError): PublicKey(b"") with pytest.raises(ValueError): PrivateKey(b"") pub = PublicKey( b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) priv = PrivateKey( b"5c2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) b = Box(priv, pub) with pytest.raises(ValueError): b.encrypt(b"", b"") with pytest.raises(ValueError): b.decrypt(b"", b"")
def encrypt_curve25519(self, message, priv_key, pub_key): """ encrypt data using the curve25519 algorithm. It takes a message to encrypt, your own private key, and another party's public key. The data can later be decrypted by the other party provided it has access to your public key. """ box = Box(priv_key, pub_key) encrypted_message = box.encrypt(message) return encrypted_message
def test_box_wrong_length(): with pytest.raises(ValueError): PublicKey(b"") with pytest.raises(TypeError): PrivateKey(b"") pub = PublicKey( b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) priv = PrivateKey( b"5c2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) b = Box(priv, pub) with pytest.raises(ValueError): b.encrypt(b"", b"") with pytest.raises(ValueError): b.decrypt(b"", b"")
def talk(): global shared_secret global secretNotKnown global nonce global nonce2 global callInProgress s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.connect((Listener_HOST, Listener_PORT)) p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=Talk_CHUNK) print("*recording") global skbob pkalice = jsonpickle.decode(firebase.get('/littleboy/pk', None)) pkalice = PublicKey(pkalice, encoder=HexEncoder) bob_box = Box(skbob, pkalice) ####PUBLIC KEY AGREEMENT data = stream.read(Talk_CHUNK) compressed_data = oc.encode(data) encrypted = bob_box.encrypt(compressed_data, nonce2) s.send(encrypted) ####PUBLIC KEY AGREEMENT while secretNotKnown: time.sleep(.01) listen_secret_box = nacl.secret.SecretBox(shared_secret) print("talk:", shared_secret) forwardsecret = 0 try: while (callInProgress ): #for i in range(0, int(RATE/Talk_CHUNK*RECORD_SECONDS)): data = stream.read(Talk_CHUNK) compressed_data = oc.encode(data) encrypted = listen_secret_box.encrypt(compressed_data, nonce) #nonce if (len(encrypted) == 168): bytes_sent = s.send(encrypted) time.sleep(.01) except Exception: print("problem occured", sys.exc_info()) stream.stop_stream() stream.close() p.terminate() s.close() callInProgress = False print("talk stopped")
def main(listeners=1): global HOST global PORT global privateKey global publicKey getKeys() with socket(AF_INET, SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen(listeners) conn, addr = s.accept() with conn: print("Connection from: ", addr) fromClient = conn.recv(1024).decode('utf-8') #RECEIVE if fromClient == "sending client key": conn.send("send client key".encode()) #SEND #receives public key from client in bytes fromClient = conn.recv(1024) #RECEIVE print("**received public key") #create public key object from client client_pubObj = PublicKey(fromClient) #get public key in bytes send_publicKey = publicKey.__bytes__() #sends over public key conn.send(send_publicKey) #SEND print("**sent public key") #create server box server_box = Box(privateKey, client_pubObj) while True: #receive encrypted message encrypted = conn.recv(1024) #RECEIVE print("**received encrypted message") message = server_box.decrypt(encrypted) message = message.decode('utf-8') if message == "exit(0)": print("**client ended communication") break print("client: ", message) message = message + " - read by server" encrypted = server_box.encrypt(bytes(message, 'utf-8')) #send encrypted message conn.send(encrypted) #SEND else: conn.send("error, please send client key".encode()) #SEND conn.close() print("**closed connection")
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 handshake(self, fernet_key): try: my_priv_key = PrivateKey.generate() my_publ_key = my_priv_key.public_key self.send_data(my_publ_key,False) server_publ_key = self.recv_pckt() my_box = Box(my_priv_key, server_publ_key) encrypted_key = my_box.encrypt(fernet_key) self.send_data(encrypted_key) return True except: return False
def Encrypt_NaCl(Pk, Sk, plaintext): Sk = PrivateKeyNaCl(Sk, encoder=Base64Encoder) Pk = PublicKeyNaCl(Pk, encoder=Base64Encoder) box = BoxNaCl(Sk, Pk) # import numpy as np # print np.fromstring(box.shared_key(), dtype=np.uint8) nonce = nacl.utils.random(BoxNaCl.NONCE_SIZE) ciphertext = box.encrypt(plaintext, nonce, encoder=Base64Encoder) nonce = ciphertext.nonce ciphertext = ciphertext.ciphertext return ciphertext, nonce
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 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 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 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
class CryptoBox: # Init def __init__(self, sk=None, pk=None): # Set local Variables self._box = None self.sk = None self.pk = None # Generate key pair if nessessary if not sk or not pk: self.sk = PrivateKey.generate() self.pk = self.sk.public_key else: self.sk = sk self.pk = pk # Generate shared key / box self._box = Box(self.sk, self.pk) # Encryption def encrypt(self, plaintext, nonce=None): if not nonce: nonce = nacl.utils.random(Box.NONCE_SIZE) ciphertext = self._box.encrypt(plaintext, nonce) return ciphertext[24:] # Decryption def decrypt(self, ciphertext, nonce=None): if nonce: plaintext = self._box.decrypt(ciphertext, nonce) else: plaintext = self._box.decrypt(ciphertext) return plaintext
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 handshake_hello(private_key, redis_client): try: request = expect_json_request(bottle.request, HELLO_SCHEMA) client_transient_pkey = PublicKey( str(request[HELLO_CLIENT_TRANSIENT_PKEY_FIELD]), Base64Encoder) zeros = open_box(request[HELLO_ZEROS_BOX_FIELD], private_key, client_transient_pkey) if len(zeros) != HELLO_PADDING_BYTES: raise InvalidClientRequest( 'zeros_box should contain exactly %d bytes of padding' % HELLO_PADDING_BYTES) transient_skey = PrivateKey.generate() cookie_plain = client_transient_pkey.encode() + \ transient_skey.encode() cookie_nonce = nacl.utils.random(SecretBox.NONCE_SIZE) symmetric_key = nacl.utils.random(SecretBox.KEY_SIZE) cookie_sbox = SecretBox(symmetric_key) cookie = cookie_sbox.encrypt( cookie_plain, cookie_nonce, encoder=Base64Encoder) redis_set_cookie(redis_client, cookie, symmetric_key) cookie_box = Box(private_key, client_transient_pkey) cookie_box_nonce = nacl.utils.random(Box.NONCE_SIZE) server_tpkey = transient_skey.public_key.encode(Base64Encoder) cookie_box_cipher = cookie_box.encrypt(json.dumps({ COOKIE_SERVER_TRANSIENT_PKEY_FIELD: server_tpkey, COOKIE_COOKIE_FIELD: cookie }), cookie_box_nonce, encoder=Base64Encoder) response = {COOKIE_COOKIE_BOX_FIELD: cookie_box_cipher} jsonschema.validate(response, COOKIE_SCHEMA) return response except jsonschema.ValidationError: log.exception(e) bottle.response.status = HTTP_INTERNAL_SERVER_ERROR return {'error': 'A packet with an invalid JSON schema was generated.'} except InvalidClientRequest as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': str(e)} except CryptoError as e: log.exception(e) bottle.response.status = HTTP_BAD_REQUEST return {'error': 'bad encryption'} return {'error': ''}
def wrap(self, payload_contents ): # look up the signature key with open( config.get('global', 'keypath') + '/' + self.origin + '.sig', 'r') as originSigKey: originSig = self.deserialize(originSigKey) # look up the public and private keys with open( config.get('global', 'keypath') + '/' + self.origin + '.private', 'r' ) as originPrivateKey: originKey = self.deserialize(originPrivateKey) with open( config.get('global', 'keypath') + '/' + self.destination + '.public', 'r' ) as destinationPublicKey: destinationKey = self.deserialize(destinationPublicKey) # make payload a NaCL box container = Box( originKey, destinationKey ) # sign the contents signedContents = originSig.sign(payload_contents) # encrypt the payload rawPayload = container.encrypt( signedContents, self.nonce ) # sign the payload and attach it to the object self.payload = originSig.sign( rawPayload )
def test_box_encryption(skalice, pkalice, skbob, pkbob, nonce, plaintext, ciphertext): pkalice = PublicKey(pkalice, encoder=HexEncoder) skbob = PrivateKey(skbob, encoder=HexEncoder) box = Box(skbob, pkalice) encrypted = box.encrypt( binascii.unhexlify(plaintext), binascii.unhexlify(nonce), encoder=HexEncoder, ) expected = binascii.hexlify( binascii.unhexlify(nonce) + binascii.unhexlify(ciphertext), ) assert encrypted == expected assert encrypted.nonce == nonce assert encrypted.ciphertext == ciphertext
def asymmetricEncryption(toEncrypt): #generiranje privatnog kljuca posiljatelja koji mora ostati tajan skSender = PrivateKey.generate() #generiranje javnog kljuca posiljatelja pkSender = skSender.public_key #generiranje privatnog kljuca primatelja koji mora ostati tajan skReceiver = PrivateKey.generate() #generiranje javnog kljuca primatelja pkReceiver = skReceiver.public_key #"kutija" s posiljateljevim privatnim kljucem i primateljevim javnim kljucem #sluzi za enkriptiranje poruke senderBox = Box(skSender, pkReceiver) #broj koji se koristi samo jednom, ne smatra se tajnim i moze ga se slati uz enkriptiranu poruku #dobar izvor za nonce su nasumicna 24 byta nonce = nacl.utils.random(Box.NONCE_SIZE) #enkriptiranje poruke koja ce potom biti dulja za tocno 40 byta od originalne poruke #razlog tome je informacija o autentifikaciji i nonce koji se pohranjuju uz nju encrypted = senderBox.encrypt(toEncrypt, nonce, encoder = nacl.encoding.Base64Encoder) return pkSender, skReceiver, encrypted
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 main(): current_location = get_current_location() # READ TEXT key = read_file(current_location + '/decrypted_text/texto_descifrado_ejercicio1.base64') box = nacl.secret.SecretBox(key) text = read_file(current_location + '/crypted_text/texto_cifrado_paso2_nacl.base64') print 'Encrypted text is: "%s", length is: "%i"' % (text, len(text)) decrypted_text = box.decrypt(text) print 'Decrypted text is: "%s"' % decrypted_text # GET KEYS my_public_key = PublicKey(read_file(current_location + '/pp_keys/pkAlumno.base64')) my_private_key = PrivateKey(read_file(current_location + '/pp_keys/skAlumno.base64')) iarenaza_public_key = PublicKey(read_file(current_location + '/pp_keys/pkTutor.base64')) # ENCRYPT box = Box(my_private_key, iarenaza_public_key) nonce = nacl.utils.random(Box.NONCE_SIZE) encrypted_text = box.encrypt(decrypted_text, nonce) print 'Encrypted text is: "%s", length is: "%i"' % (encrypted_text, len(encrypted_text)) # WRITE FILE create_file(current_location + '/crypted_text/', 'texto_cifrado_ejercicio2.base64', encrypted_text.encode('base64'))
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.PlaintextMessage.Type.Value("DISPUTE_CLOSE"), dispute_json, 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(dispute_json, indent=4), nonce) d = self.protocol.callDisputeClose(node_to_ask, pkephem, ciphertext) return d.addCallback(parse_response) else: return parse_response([False])
def encrypt_key(message_key, recipient_pub_key): """Encrypt a message_key for a given identifier :param message_key: the key. :param identifier: the identifier of the message recipient. """ # Generate a new keypair & cipher the key with it. temp_private_key, temp_public_key = generate_keypair() recipient_pub_key = PublicKey( recipient_pub_key, HexEncoder) box = PublicBox(temp_private_key, recipient_pub_key) nonce = nacl.utils.random(PublicBox.NONCE_SIZE) encrypted_key = box.encrypt(message_key, nonce, HexEncoder) # Return the public key used to cipher the message key. return { 'encrypted_key': encrypted_key, 'temp_public_key': temp_public_key.encode(HexEncoder) }