def test_decrypt_exports_inquiry(mocker, cybersource_private_key): """Test that decrypt_exports_inquiry can decrypted an encrypted log""" request = b"<sent/>" response = b"<received/>" box = SealedBox(cybersource_private_key) log = mocker.Mock() log.encrypted_request = box.encrypt(request, encoder=Base64Encoder) log.encrypted_response = box.encrypt(response, encoder=Base64Encoder) decrypted = api.decrypt_exports_inquiry(log, cybersource_private_key) assert decrypted.request == request assert decrypted.response == response
def log_exports_inquiry(user, response, last_sent, last_received): """ Log a request/response for an export inquiry for a given user Args: user (users.models.User): the user that was checked for exports compliance response (etree.Element): the root response node from the API call last_sent (dict): the raw request sent for this call last_received (dict): the raw response received for this call Returns: ExportsInquiryLog: the generated log record of the exports inquiry """ # render lxml data structures into a string so we can encrypt it xml_request = etree.tostring(last_sent["envelope"]) xml_response = etree.tostring(last_received["envelope"]) log.debug("Sent: %s", xml_request) log.debug("Received: %s", xml_response) # overall status code of the response # NOTE: reason_code can indicate a success but a block list still be triggered and indicated in info_code reason_code = int(response.reasonCode) if reason_code in TEMPORARY_FAILURE_REASON_CODES: # if it's a temporary failure in the CyberSource backend or # the request itself, no point in recording this log.error("Unable to verify exports controls, received reasonCode: %s", reason_code) return None # if the data triggered a block list this will be truthy info_code = response.exportReply.infoCode box = SealedBox(get_encryption_public_key()) encrypted_request = box.encrypt(xml_request, encoder=Base64Encoder).decode("ascii") encrypted_response = box.encrypt(xml_response, encoder=Base64Encoder).decode("ascii") return ExportsInquiryLog.objects.create( user=user, computed_result=compute_result_from_codes(reason_code, info_code), reason_code=reason_code, info_code=info_code, encrypted_request=encrypted_request, encrypted_response=encrypted_response, )
def serialise(self, signing_key: SigningKey): # Create buffer buffer = BytesIO() # Write magic number buffer.write(Frame.MAGIC_NUMBER) # Write the destination key buffer.write(self.destination.serialise().read()) # Write the origin key buffer.write(self.origin.serialise().read()) # Write the via field buffer.write(self.via.serialise().read()) # Create a box to send the signed data in box = SealedBox(self.destination.public_key) # Sign the payload signed = signing_key.sign(self.payload.read()) # Encrypt and write the data to the buffer buffer.write(box.encrypt(signed)) # Rewind the buffer buffer.seek(0, 0) # Return the buffer return buffer
def generate_zos_keys(self, node_public_key): """ Generate a new set of wireguard key pair and encrypt the private side using the public key of a 0-OS node. This implementation match the format 0-OS except to be able to read wireguard keys into network reservations. :param node_public_key: hex encoded public key of 0-OS node. This is the format you find in the explorer :type node_public_key: str :return: tuple containing 3 fields (private key, private key encrypted, public key) :rtype: typle """ wg_private_base64, wg_public_base64 = self.generate_key_pair() node_public_bin = j.data.hash.hex2bin(node_public_key) node_public = VerifyKey(node_public_bin) box = SealedBox(node_public.to_curve25519_public_key()) wg_private_encrypted = box.encrypt(wg_private_base64) wg_private_encrypted_hex = j.data.hash.bin2hex(wg_private_encrypted) return (wg_private_base64.decode(), wg_private_encrypted_hex.decode(), wg_public_base64.decode())
def _box(): try: nonce = nacl.utils.random(Box.NONCE_SIZE) box = SealedBox(PublicKey(pubKey)) return box.encrypt(msg, nonce) except Exception: return
def _retrieve_service_generated_cert(self, request, dek_info): """ :param CertificateRequest request: :param EdgeEncryptionKey dek_info: :rtype: Certificate """ box = SealedBox(dek_info.public_key) encrypted_key_pass = box.encrypt(request.key_password) body = { 'exportFormat': 'PEM', 'encryptedPrivateKeyPassphrase': base64.b64encode(encrypted_key_pass).decode('utf-8'), 'encryptedKeystorePassphrase': '', 'certificateLabel': '' } url = URLS.CERTIFICATE_KEYSTORE_BY_ID.format(request.cert_guid) status, data = self._post(url, data=body) if status not in (HTTPStatus.OK, HTTPStatus.CREATED, HTTPStatus.ACCEPTED): log.error("Some error") raise VenafiError cert, chain, private_key = zip_to_pem(data, request.chain_option) return Certificate(cert=cert, chain=chain, key=private_key)
def generate_token(self, private_key, metadata=None, enc_key=None, token_type=None): claims = {} metadata = json.loads(metadata) #create token_id if 'aud' in metadata: claims['aud'] = metadata['aud'] if 'sub' in metadata: claims['sub'] = metadata['sub'] if 'exp' in metadata: claims['exp'] = metadata['exp'] if 'nbf' in metadata: claims['nbf'] = metadata['nbf'] claims['jti'] = random.getrandbits(256) token = jwt.encode(claims, private_key, algorithm='RS256') if enc_key: public_key = nacl.public.PublicKey(enc_key, nacl.encoding.HexEncoder) sealed_box = SealedBox(public_key) token = sealed_box.encrypt(token) token = base64.urlsafe_b64encode(token) #return 200, {'code':200,'message':token.decode('utf-8')} return token, claims
def test_array(self): # Generate Bob's private key, as we've done in the Box example private = PrivateKey.generate() public = private.public_key private_bytes = bytes(private) public_bytes = bytes(public) f = open(os.path.join(os.getcwd(), 'private.key'), 'wb') f.write(private_bytes) f.close() f = open(os.path.join(os.getcwd(),'public.key'), 'wb') f.write(public_bytes) f.close() with open(os.path.join(os.getcwd(), "private.key"), "rb") as f: priv_byte = f.read() with open(os.path.join(os.getcwd(), "public.key"), "rb") as pubf: pubf_byte = pubf.read() public_key = PublicKey(pubf_byte) private_key = PrivateKey(priv_byte) test_message = "This a test message!" sealed_box = SealedBox(public_key) encrypted_text = sealed_box.encrypt(bytes(test_message, "utf-8")) unseal = SealedBox(private_key) result = unseal.decrypt(encrypted_text) print(result.decode("utf-8")) self.assertEqual(result.decode("utf-8"),test_message)
def encrypt(): decrypted_utf8 = read_file('decrypted.txt') decrypted_bin = bytes(decrypted_utf8, 'utf-8') public_key_bin = read_file('public_key.txt', True) public_key = PublicKey(public_key_bin) sealed_box = SealedBox(public_key) encrypted_bin = sealed_box.encrypt(decrypted_bin) write_file("encrypted.txt", encrypted_bin, True)
def encrypt(message, key, output): message_bytes = message.encode('ascii') with open(key, mode="rb") as key_file: key_bytes = key_file.read() with open(output, "wb") as output_file: pub_key = PublicKey(key_bytes) sealed_box = SealedBox(pub_key) output_file.write(sealed_box.encrypt(message_bytes))
def encrypt_password(password, public_key): node_public_bin = j.data.hash.hex2bin(public_key) node_public = VerifyKey(node_public_bin) box = SealedBox(node_public.to_curve25519_public_key()) pasword_encrypted = box.encrypt(password.encode()) pasword_encrypted_hex = j.data.hash.bin2hex(pasword_encrypted) return pasword_encrypted_hex
def encrypt_sealed_box(message, public_rec): message = message.encode('utf-8') public_rec = check_key(public_rec) public_rec = bytes.fromhex(public_rec) public_rec = PublicKey(public_key=public_rec) sealed_box = SealedBox(public_rec) encrypted = sealed_box.encrypt(message) return base64.b64encode(encrypted).decode('utf-8')
def privateMessage(self, message, targetUsername, apiKey, prikey): #self, message, targetusername, apikey, prikey client_saved_at = str(time.time()) sqlite.insertPM(self, self.username, targetUsername, self.username, targetUsername, message, client_saved_at) data = sqlite.getOnline(self) for i in range(len(data["name"])): if (data["name"][i] == targetUsername): address = data["address"][i] url = "http://" + address + "/api/rx_privatemessage" loginserver_record = self.LoginServerRecord(apiKey) target_pubkey = str(sqlite.findOnline(self, str(targetUsername))) print(target_pubkey) pubkey = nacl.signing.VerifyKey(target_pubkey, encoder=nacl.encoding.HexEncoder) curvedrxpubkey = pubkey.to_curve25519_public_key() sealed_box = SealedBox(curvedrxpubkey) message = bytes(message, encoding='utf-8') encrypted = sealed_box.encrypt(message, encoder=nacl.encoding.HexEncoder) signed = bytes(loginserver_record + target_pubkey + targetUsername + encrypted.decode('utf-8') + client_saved_at, encoding='utf-8') signature = prikey.sign(signed, encoder=nacl.encoding.HexEncoder) headers = { 'X-username': self.username, 'X-apikey': apiKey, 'Content-Type': 'application/json; charset=utf-8', } payload = { "loginserver_record": loginserver_record, "target_pubkey": target_pubkey, "target_username": targetUsername, "encrypted_message": encrypted.decode('utf-8'), "sender_created_at": client_saved_at, "signature": signature.signature.decode('utf-8') } payload_str = json.dumps(payload) json_payload = payload_str.encode("utf-8") try: req = urllib.request.Request(url, data=json_payload, headers=headers) response = urllib.request.urlopen(req) data = response.read() encoding = response.info().get_content_charset('utf-8') response.close() except urllib.error.HTTPError as error: print("$$$$$$$$$$$$$$$$$$") print(error.read()) exit() print("##############33") print(data) print("#################") JSON_object = json.loads(str(data.decode(encoding))) print(JSON_object)
def test_sealed_box_too_short_msg(): empty_plaintext = b'' k = PrivateKey.generate() enc_box = SealedBox(k.public_key) dec_box = SealedBox(k) msg = enc_box.encrypt(empty_plaintext) with pytest.raises(CryptoError): dec_box.decrypt(msg[:-1])
def auth(): auth_host = '10.50.8.128' #with open('private_key', 'rb') as f: #f.write('Hello\n') with open('private_key') as f: encoded_private_key = f.read() with open('public_key') as f: encoded_public_key = f.read() loaded_public_key = PublicKey(encoded_public_key, encoder=nacl.encoding.Base64Encoder) loaded_private_key = PrivateKey(encoded_private_key, encoder=nacl.encoding.Base64Encoder) # assert loaded_public_key.encode() == loaded_private_key.public_key.encode() #assert loaded_public_key.encode() == loaded_private_key.public_key.encode() print(loaded_public_key.encode()) print(loaded_private_key.public_key.encode()) private_key = loaded_private_key public_key = loaded_public_key # return 1 # private_key = private_key_b64.decode('base64') # public_key = public_key_b64.decode('base64') # with open('public_key', 'rb') as f: # f.write(encoded_public_key) # with open('x.py') as f: s = f.read() # # Generate Bob's private key, as we've done in the Box example # skbob = PrivateKey.generate() # pkbob = skbob.public_key #return private_key # Alice wishes to send a encrypted message to Bob, # but prefers the message to be untraceable #sealed_box = SealedBox(pkbob) sealed_box = SealedBox(private_key) # This is Alice's message message = b"Kill all kittens" # Encrypt the message, it will carry the ephemeral key public part # to let Bob decrypt it encrypted = sealed_box.encrypt(message) msg = base64.b64encode(encrypted) msg = encoded_public_key #data = {'name': 'jtest', 'ipaddr': '192.168.0.2' 'public_key': b'\x8e\x05{\xe2\xcby:\x0b\xeb\xe69\xac|\x96\xff\xa4\xdaE\x89^\xa7\xaf\x90\x83\x14)bP\x0c\n\x85l'} #data = {'msg': ''} data = {'msg': msg} print(data) #return 1 #r = requests.post('https://stats.rchain.me:30443/auth', data = data) r = requests.post(f'https://{auth_host}:30443/auth', data=data) print(r) text = r.text content = r.content print(text) print(content)
def payload_encrypt_pubkey(self, payload, verifykey=None, hex=False): assert verifykey pubkey = self.pubkey_obj_get(verifykey) sealed_box = SealedBox(pubkey) res = sealed_box.encrypt(payload) if hex: res = self._bin_to_hex(res) return res
def createGroup(self, prikey, apiKey): url = "http://172.23.2.31:10050/api/rx_groupinvite" target = "misl000" loginserverRecord = self.LoginServerRecord(apiKey) str_pass = str("ikea") byte = bytes(str_pass, encoding='utf-8') key_password = str_pass * 16 salt = bytes(key_password.encode('utf-8')[:16]) ops = nacl.pwhash.argon2i.OPSLIMIT_SENSITIVE mem = nacl.pwhash.argon2i.MEMLIMIT_SENSITIVE key = nacl.pwhash.argon2i.kdf(32, byte, salt, ops, mem) hashed = nacl.hash.sha256(key, encoder=nacl.encoding.HexEncoder) hashed = hashed.decode('utf-8') pubkey = str(sqlite.findOnline(self, str(target))) public = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.HexEncoder) curvedpubkey = public.to_curve25519_public_key() box = SealedBox(curvedpubkey) encrypted_groupkey = box.encrypt(key, encoder=nacl.encoding.HexEncoder) encrypted_groupkey = encrypted_groupkey.decode('utf-8') sender_created_at = str(time.time()) signature = bytes(loginserverRecord + hashed + pubkey + target + encrypted_groupkey + sender_created_at, encoding='utf-8') signed = prikey.sign(signature, encoder=nacl.encoding.HexEncoder) headers = { 'X-username': self.username, 'X-apikey': apiKey, 'Content-Type': 'application/json; charset=utf-8', } payload = { 'loginserver_record': loginserverRecord, 'groupkey_hash': hashed, 'target_pubkey': pubkey, 'target_username': self.username, 'encrypted_groupkey': encrypted_groupkey, 'sender_created_at': sender_created_at, 'signature': signed.signature.decode('utf-8') } payload_str = json.dumps(payload) json_payload = payload_str.encode("utf-8") try: req = urllib.request.Request(url, data=json_payload, headers=headers) response = urllib.request.urlopen(req) data = response.read() encoding = response.info().get_content_charset('utf-8') response.close() except urllib.error.HTTPError as error: print(error.read()) exit() JSON_object = json.loads(data.decode(encoding)) print(JSON_object) return JSON_object
def account_register(args): username = get_username(args) if not args.public: server_verifykey = get_server_advertised_verifykey(args.address) else: server_verifykey = VerifyKey(args.public, URLSafeBase64Encoder) print(f"Server verification key: {server_verifykey.encode(URLSafeBase64Encoder).decode()}") server_publickey = get_server_verified_publickey(args.address, server_verifykey) # step 1: check access to homeserver server_name = get_server_name(args.address, server_verifykey) print(f"Server name: {server_name}") device_storage = LocalStorage('device', readonly=True) user_storage = LocalStorage(username, readonly=False) with user_storage as us, device_storage as ds: print(f"Setting identity '{username}' homeserver...") us['homeserver'] = { "address": args.address, "verify": server_verifykey.encode(URLSafeBase64Encoder).decode(), "public": server_publickey.encode(URLSafeBase64Encoder).decode(), "timestamp": get_timestamp_seconds() } us.save() # write changes before profile block: pb = _build_profile_block(username) # pack it: packd = msgpack.packb(pb) # sign it: packd_withsig = _get_user_signingkey(username).sign(packd) # since the server might not know us yet, we have to SealedBox: sbox = SealedBox(server_publickey) encrypted = sbox.encrypt(packd_withsig) # generate a signature for the headers: request_signature = _get_user_signingkey(username).sign(encrypted).signature # ready to submit the request: r = requests.post( args.address + "/api/v1/account/register", data=encrypted, headers={ "KF-Client-Verify": _get_user_verifykey(username).encode(URLSafeBase64Encoder).decode(), "KF-Client-Signature": base64.urlsafe_b64encode(request_signature), } ) if not r.ok: print(f"Error registering:\n{r.text}") # r.raise_for_status() return # box is authenticated, no need to check server signature here s_box = _get_homeserver_box(username) response_bytes = s_box.decrypt(r.content) unpacked = msgpack.unpackb(response_bytes) print(f"Server good response: {unpacked}") print(f"Successfully registered with homeserver.")
def test_sealed_box_zero_length_plaintext(): empty_plaintext = b'' k = PrivateKey.generate() enc_box = SealedBox(k.public_key) dec_box = SealedBox(k) msg = enc_box.encrypt(empty_plaintext) decoded = dec_box.decrypt(msg) assert decoded == empty_plaintext
def encrypt_text(self, text: str): if not self.public_key: self.import_public_key_from_file() if not self.public_key: raise AttributeError( 'No public key known. Import public key first!') else: sealed_box = SealedBox(self.public_key) cipher_byte = sealed_box.encrypt(str.encode(text)) return f'crypt:{self._base64(cipher_byte)}'
def encrypt(self, data, hex=False): """ Encrypt data using the public key :param data: data to be encrypted, should be of type binary @return: encrypted data """ data = self.tobytes(data) sealed_box = SealedBox(self.pubkey) res = sealed_box.encrypt(data) if hex: res = self._bin_to_hex(res) return res
def asymmetrically_encrypt(text, pk): """ :param text: bytestring to be encrypted :param pk: binary public key (from file) :return: encrypted word as hexadecimal string """ public_key = PublicKey(pk) sealed_box = SealedBox(public_key) encrypted_bytestring = sealed_box.encrypt(text.encode('utf-8'), encoder=encoding.HexEncoder) return str(encrypted_bytestring, "utf-8")
def encrypt(self, data, hex=False, public_key=None): """ Encrypt data using the public key :param data: data to be encrypted, should be of type binary :param public_key: if None, the local public key is used @return: encrypted data """ if not public_key: public_key = self.public_key data = self.tobytes(data) sealed_box = SealedBox(public_key) res = sealed_box.encrypt(data) if hex: res = self._bin_to_hex(res) return res
def test_sealed_box_encryption(privalice, pubalice, plaintext, _encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = SealedBox(pubalice) encrypted = box.encrypt(binascii.unhexlify(plaintext), encoder=HexEncoder,) assert encrypted != _encrypted # since SealedBox.encrypt uses an ephemeral sender's keypair box2 = SealedBox(privalice) decrypted = box2.decrypt(encrypted, encoder=HexEncoder,) assert binascii.hexlify(decrypted) == plaintext assert bytes(box) == bytes(box2)
def write_result(o): with lock: with open(MARKFILE,'ab') as f: si=io.StringIO() dw=csv.DictWriter(si,fieldnames=list(o.keys())) dw.writerow(o) si=si.getvalue() #si now contains the unencrypted string. if PUBLIC_KEY==None: f.write(str.encode(si)+b'\n') else: sb=SealedBox(PUBLIC_KEY) enc=sb.encrypt(str.encode(si),encoder=nacl.encoding.Base64Encoder) f.write(enc+b'\n')
def NACL_sealedBox_encrypt(text): # Generate Bob's private key, as we've done in the Box example skbob = PrivateKey.generate() pkbob = skbob.public_key # Alice wishes to send a encrypted message to Bob, # but prefers the message to be untraceable sealed_box = SealedBox(pkbob) # This is Alice's message message = bytes(text,'utf-8') # Encrypt the message, it will carry the ephemeral key public part # to let Bob decrypt it encrypted = sealed_box.encrypt(message) #Now, Bob wants to read the secret message he just received; therefore he must create a SealedBox using his own #private key: unseal_box = SealedBox(skbob) # decrypt the received message plaintext = unseal_box.decrypt(encrypted) print(plaintext.decode('utf-8')) return True
def accept_incoming_connections(): """Sets up handling for incoming clients.""" while True: client, client_address = SERVER.accept() #receiving the public key from recent user pk = client.recv(BUFSIZ) #creating sealed box and sending key to client box = SealedBox(PublicKey(pk)) encryptedKey = box.encrypt(gk) client.send(bytes(encryptedKey)) print("%s:%s has connected." % client_address) greeting = "Greetings from the cave! Now type your name and press enter!".encode( encoding='utf-8') encryptedGreet = nacl.secret.SecretBox(gk).encrypt(greeting) client.send(bytes(encryptedGreet)) addresses[client] = client_address Thread(target=handle_client, args=(client, )).start()
def test_sealed_box_encryption(privalice, pubalice, plaintext, _encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = SealedBox(pubalice) encrypted = box.encrypt( binascii.unhexlify(plaintext), encoder=HexEncoder, ) assert encrypted != _encrypted # since SealedBox.encrypt uses an ephemeral sender's keypair box2 = SealedBox(privalice) decrypted = box2.decrypt( encrypted, encoder=HexEncoder, ) assert binascii.hexlify(decrypted) == plaintext assert bytes(box) == bytes(box2)
def encrypt_for_node(public_key: str, payload: Union[str, bytes]) -> str: """encrypt payload with the public key of a node so only the node itself can decrypt it use this if you have sensitive data to send in a reservation Args: public_key(str): public key of the node, hex-encoded payload(Union[str, bytes]): any data you want to encrypt Returns: str: hex-encoded encrypted data. you can use this safely into your reservation data """ node_public_bin = binascii.unhexlify(public_key) node_public = VerifyKey(node_public_bin) box = SealedBox(node_public.to_curve25519_public_key()) if isinstance(payload, str): payload = payload.encode() encrypted = box.encrypt(payload) return binascii.hexlify(encrypted)
def handle(self, *args, **options): # pylint: disable=too-many-locals, too-many-branches, too-many-statements for data_file in ExternalDataRequestFile.objects.filter( processed=None, skipped=None).order_by('pk')[:1]: print('Processing ' + str(data_file.data_file.path) + ' (' + str(data_file.pk) + ')...') sys.stdout.flush() if data_file.process() is False: print('Unable to process ' + str(data_file.data_file.path) + ' (' + str(data_file.pk) + ').') sys.stdout.flush() data_file.skipped = timezone.now() data_file.save() if options['skip_encryption'] is False: original_path = data_file.data_file.path box = SealedBox( PublicKey( base64.b64decode( settings.PDK_EXTERNAL_CONTENT_PUBLIC_KEY))) size = os.path.getsize(data_file.data_file.path) if size < 1024 * 1024 * 1024: with open(data_file.data_file.path, 'rb') as original_file: encrypted_str = box.encrypt(original_file.read()) filename = os.path.basename( data_file.data_file.path) + '.encrypted' encrypted_file = ContentFile(encrypted_str) data_file.data_file.save(filename, encrypted_file) os.remove(original_path) else: call_command('pdk_external_aes_encrypt_data_file', str(data_file.pk))
def post(self): # Get raw request request_raw = request.data.decode("UTF-8") # Split by ":" post_data = request_raw.split(":") guid = post_data[0] nonce = base64.b64decode(post_data[1]) ciphertext = base64.b64decode(post_data[2]) # Grab shared key from listener Listener = ListenerModel.query.filter( ListenerModel.listener_type == "http").first() sharedkey = base64.b64decode(Listener.shared_key) # Decode ciphertext (client_publickey) using pynacl box = nacl.secret.SecretBox(sharedkey) client_publickey = box.decrypt(ciphertext, nonce) # Generate final session key session_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE) # Write SK8RAT to database with agent name + b64(sessionkey) new_SK8RAT = SK8RATModel( name=''.join( random.choices(string.ascii_uppercase + string.digits, k=15)), guid=guid, session_key=base64.b64encode(session_key).decode("UTF-8"), session_cookie=''.join( random.choices(string.ascii_uppercase + string.digits, k=15)), external_ip=request.remote_addr) new_SK8RAT.save_to_db() # Use sealed box with (client_publickey) to send session key to SK8RAT publickey = nacl.public.PublicKey(client_publickey) sealed_box = SealedBox(publickey) encrypted = sealed_box.encrypt(session_key) return base64.b64encode(encrypted).decode("UTF-8")