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 _poll_handshake_file(self): """Check if a client has created a handshake file. If so, parse the file and store the session key""" # check for file with valid name with self.xmit_lock: files = list_files(self.ftps) for f in files: s_id, direction, seq = parse_tunnel_filename(f[0]) if s_id is not None and direction == 0 and seq == 0: # check if contents of file is encrypted with this proxy's public key data = get_file_contents(self.ftps, f[0]) try: # attempt to decrypt the received message unseal_box = SealedBox(self.private_key) self.session_key = unseal_box.decrypt(data) self.session_id = s_id return except Exception as e: # file contents not encrypted with proxy's key continue # update heartbeat if needed if self.heart + PROXY_HEARTBEAT_TIMEOUT < time.time(): upload_binary_data(self.ftps, self.my_proxy_id, generate_proxy_descriptor(self.public_key)) self.heart = time.time()
async def test_valid_auth_code_ecn_token(): privateKeyHex = 'd686cb5b1e7866c657af66b6c365dd8f1523678dbf1a9d0344c5e9c38847c034' publicKeyHex = '34a0d7e2c95b24c9c87e47ce4e528c3814a8516528b4095c84b49908390b7a24' nbf = time.mktime(datetime.datetime(2020, 4, 1, 00, 00).timetuple()) exp = time.mktime(datetime.datetime(2020, 4, 1, 23, 59).timetuple()) payload = { 'grant-type': 'auth_code', 'grant': 'shared_secret_key', 'metadata': json.dumps({ 'aud': 'sofie-iot.eu', 'nbf': nbf, 'exp': exp }), 'enc-key': publicKeyHex } response = requests.post("http://localhost:9001/gettoken", data=payload).text response = json.loads(response) enc64 = response['message'] enc = base64.urlsafe_b64decode(enc64) private_key = nacl.public.PrivateKey(privateKeyHex, nacl.encoding.HexEncoder) sealed_box = SealedBox(private_key) msg = sealed_box.decrypt(enc) assert (response['code'] == 200)
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 handle(self, *args, **options): # pylint: disable=too-many-locals, too-many-branches, too-many-statements if options['key'] is None: options['key'] = getpass.getpass('Enter private key: ') box = SealedBox(PrivateKey(base64.b64decode(options['key']))) original_path = options['file'] try: with open(original_path, 'rb') as original_file: print('Decrypting ' + str(original_path) + '...') try: cleartext = box.decrypt(original_file.read()) filename = original_path.replace('.encrypted', '') with open(filename, 'wb') as file_obj: file_obj.write(cleartext) print('Decrypted ' + str(original_path) + ' to ' + filename + '.') except CryptoError: print('Unable to decrypt ' + str(original_path) + ' (CryptoError). Please investigate manually.') if options['file_pk'] > 0: traceback.print_exc() except MemoryError: print('Unable to decrypt ' + str(original_path) + ' (MemoryError). Please investigate manually.') except IOError: traceback.print_exc() print('Unable to decrypt ' + str(original_path) + ' (IOError). Please investigate manually.')
def test_sealed_box_decryption(privalice, pubalice, plaintext, encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = SealedBox(privalice) decrypted = box.decrypt(encrypted, encoder=HexEncoder,) assert binascii.hexlify(decrypted) == plaintext
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 rx_privatemessage(self): print("privatemessage api called") target_username = cherrypy.request.json["target_username"] print("received: " + target_username) print("actual: " + username) target_pubkey = cherrypy.request.json["target_pubkey"] print("received: " + target_pubkey) print("actual: " + pubkey_hex_str) time_str = str(time.time()) if (username == target_username and pubkey_hex_str == target_pubkey): certificate = cherrypy.request.json["loginserver_record"] sender_username = certificate[0:7] try: private_key_curve = signing_key.to_curve25519_private_key() unseal_box = SealedBox(private_key_curve) message_encrypted = bytes( cherrypy.request.json["encrypted_message"], encoding='utf-8') message_decrypted = unseal_box.decrypt( message_encrypted, encoder=nacl.encoding.HexEncoder) message = message_decrypted.decode('utf-8') print(message) database.add_message(username, sender_username, message, time_str) return {'response': 'ok'} except nacl.exceptions.CryptoError: return {'response': 'not decrypted'} return {'response': 'wrong target user'}
def _box(): try: nonce = nacl.utils.random(Box.NONCE_SIZE) box = SealedBox(PublicKey(pubKey)) return box.encrypt(msg, nonce) except Exception: return
def read_secret_msg(receiver_private_key, msg): try: key = receiver_private_key.to_curve25519_private_key() unseal_box = SealedBox(key) return unseal_box.decrypt(msg) except nacl.exceptions.CryptoError: return "wrong secret key"
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 decrypt(): encrypted_bin = read_file('encrypted.txt', True) secret_key_bin = read_file('secret_key.txt', True) secret_key = PrivateKey(secret_key_bin) sealed_box = SealedBox(secret_key) decrypted_bin = sealed_box.decrypt(encrypted_bin) decrypted_utf8 = decrypted_bin.decode('utf-8') write_file("decrypted.txt", decrypted_utf8)
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_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 decrypt_sealed_box(encrypted, secret): secret = check_key(secret) secret = bytes.fromhex(secret) secret = PrivateKey(private_key=secret) unseal_box = SealedBox(secret) encrypted = base64.b64decode(encrypted) plaintext = unseal_box.decrypt(encrypted) return plaintext.decode('utf-8')
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(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 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_public_key_cannot_decrypt(_privalice, pubalice, _plaintext, encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) box = SealedBox(pubalice) with pytest.raises(TypeError): box.decrypt( encrypted, encoder=HexEncoder, )
def decrypt(self, data, hex=False): """ Decrypt incoming data using the private key :param data: encrypted data provided @return decrypted data """ unseal_box = SealedBox(self.privkey) if hex: data = self._hex_to_bin(data) return unseal_box.decrypt(data)
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 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 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 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 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 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 test_sealed_box_decryption(privalice, pubalice, plaintext, encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) privalice = PrivateKey(privalice, encoder=HexEncoder) box = SealedBox(privalice) decrypted = box.decrypt( encrypted, encoder=HexEncoder, ) assert binascii.hexlify(decrypted) == plaintext
def test_sealed_box_public_key_cannot_decrypt(_privalice, pubalice, _plaintext, encrypted): pubalice = PublicKey(pubalice, encoder=HexEncoder) box = SealedBox(pubalice) with pytest.raises(TypeError): box.decrypt( encrypted, encoder=HexEncoder, )
def decrypt(self, secret="", message="", words="", interactive=False): """ use output from encrypt js_shell 'j.data.nacl.decrypt()' """ if interactive: secret, words = self._remember_get(secret, words) if not secret: secret = j.tools.console.askPassword("your secret") if not message: message = j.tools.console.askMultiline( "your message to decrypt") message = message.strip() if not words: yn = j.tools.console.askYesNo( "do you wan to specify secret key as bip39 words?") if yn: words = j.tools.console.askString("your bip39 words") else: if not secret or not message: raise RuntimeError("secret or message needs to be used") secret = j.data.hash.md5_string(secret) secret = bytes(secret, 'utf-8') if not j.data.types.bytes.check(message): message = bytes(message, 'utf8') message = base64.decodestring(message) if words == "": words = j.data.nacl.default.words privkeybytes = j.data.encryption.mnemonic.to_entropy(words) pk = PrivateKey(privkeybytes) sb = SealedBox(pk) message = sb.decrypt(message) # now decrypt symmetric box = nacl.secret.SecretBox(secret) message = box.decrypt(message) message = message.decode(encoding='utf-8', errors='strict') if interactive: print("decrypted text:\n*************\n") print(message.strip() + "\n") return message
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_decrypt(text, sk): """ :param text: hexadecimal string to be decrypted :param sk: private key [binary] from file :return: """ private_key = PrivateKey(sk) sealed_box = SealedBox(private_key) return sealed_box.decrypt(text, encoder=encoding.HexEncoder)
def test_sealed_box_creation(): pub = PublicKey( b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) priv = PrivateKey( b"5c2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder, ) SealedBox(priv) SealedBox(pub)
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 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 decrypt(s_b64, sk_b64): box = SealedBox(PrivateKey(base64.b64decode(sk_b64))) dec = box.decrypt(base64.urlsafe_b64decode(s_b64)) return(dec)