def test_create_encrypted(self): # pubkey of recipient alice_signing_key = SigningKey.from_credentials("alice", "password") # message message = """ Hello world ! Héhé ;-) This is a utf-8 message... """ # create encrypted and signed ascii armor message encrypted_aa_message = AsciiArmor.create(message, alice_signing_key.pubkey) # split in lines for check up aa_message_lines = encrypted_aa_message.splitlines() # check before message self.assertEqual(aa_message_lines[0], BEGIN_MESSAGE_HEADER) self.assertTrue(aa_message_lines[1].startswith("Version:")) self.assertEqual("", aa_message_lines[2].strip()) # check after message self.assertEqual(aa_message_lines[4], END_MESSAGE_HEADER) # parse ascii armor message result = AsciiArmor.parse(encrypted_aa_message, alice_signing_key) # check result self.assertEqual(message + "\n", result['message']['content'])
def test_create_encrypted(self): # pubkey of recipient alice_signing_key = SigningKey.from_credentials("alice", "password") # message message = """ Hello world ! Héhé ;-) This is a utf-8 message... """ # create encrypted and signed ascii armor message encrypted_aa_message = AsciiArmor.create(message, alice_signing_key.pubkey) # split in lines for check up aa_message_lines = encrypted_aa_message.splitlines() # check before message self.assertEqual(aa_message_lines[0], BEGIN_MESSAGE_HEADER) self.assertTrue(aa_message_lines[1].startswith("Version:")) self.assertEqual("", aa_message_lines[2].strip()) # check after message self.assertEqual(aa_message_lines[4], END_MESSAGE_HEADER) # parse ascii armor message result = AsciiArmor.parse(encrypted_aa_message, alice_signing_key) # check result self.assertEqual(message + "\n", result["message"]["content"])
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity: """ Get an Identity document :param current_block: Current block data :param uid: Unique IDentifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identity """ # get current block BlockStamp timestamp = BlockUID(current_block['number'], current_block['hash']) # create keys from credentials key = SigningKey.from_credentials(salt, password) # create identity document identity = Identity(version=10, currency=current_block['currency'], pubkey=key.pubkey, uid=uid, ts=timestamp, signature=None) # sign document identity.sign([key]) return identity
def test_create_signed_cleartext(self): # signing key of issuer bob_signing_key = SigningKey.from_credentials("bob", "password") # message message = """ Hello world ! Héhé ;-) This is a utf-8 message... """ # create encrypted and signed ascii armor message signed_cleartext_aa_message = AsciiArmor.create(message, None, [bob_signing_key]) # split in lines for check up aa_message_lines = signed_cleartext_aa_message.splitlines() # check before message self.assertEqual(aa_message_lines[0], BEGIN_MESSAGE_HEADER) self.assertEqual("", aa_message_lines[1].strip()) # check after message self.assertEqual(aa_message_lines[10], BEGIN_SIGNATURE_HEADER) self.assertTrue(aa_message_lines[11].startswith("Version:")) self.assertEqual("", aa_message_lines[12].strip()) self.assertEqual(aa_message_lines[14], END_SIGNATURE_HEADER) # parse ascii armor message result = AsciiArmor.parse(signed_cleartext_aa_message, None, [bob_signing_key.pubkey]) # check result self.assertEqual(message + "\n", result['message']['content']) self.assertTrue(message + "\n", result['signatures'][0]['valid'])
def test_save_wif_and_load_from_ewif_or_wif_file(self): sign_key_save = SigningKey.from_credentials("alice", "password", ScryptParams()) sign_key_save.save_wif_file(TEST_FILE_PATH) sign_key_load = SigningKey.from_wif_or_ewif_file(TEST_FILE_PATH) self.assertEqual(sign_key_save.sk, sign_key_load.sk)
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity: """ Get an Identity document :param current_block: Current block data :param uid: Unique Identifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identity """ # get current block BlockStamp timestamp = BlockUID(current_block['number'], current_block['hash']) # create keys from credentials key = SigningKey.from_credentials(salt, password) # create identity document identity = Identity( version=10, currency=current_block['currency'], pubkey=key.pubkey, uid=uid, ts=timestamp, signature=None ) # sign document identity.sign([key]) return identity
def test_decrypt_seal(self): sign_key = SigningKey.from_credentials("alice", "password", ScryptParams()) public_key = PublicKey(sign_key.pubkey) message = "Hello world with utf-8 chars like éàè !" encrypted_message = public_key.encrypt_seal(bytes(message, 'utf-8')) decrypted_message = sign_key.decrypt_seal(encrypted_message) self.assertEqual(message, decrypted_message.decode('utf-8'))
def test_encrypt_seal(self): sign_key = SigningKey.from_credentials("alice", "password", ScryptParams()) public_key = PublicKey(sign_key.pubkey) message = "Hello world with utf-8 chars like éàè !" encrypted_message = public_key.encrypt_seal(bytes(message, 'utf-8')) decrypted_message = sign_key.decrypt_seal(encrypted_message) self.assertEqual(message, decrypted_message.decode('utf-8'))
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter recipient pubkey: ") # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # capture sources of account response = await client(bma.tx.sources, pubkey_from) if len(response["sources"]) == 0: print("no sources found for account %s" % pubkey_to) sys.exit(1) # get the first source source = response["sources"][0] # create the transaction document transaction = get_transaction_document(current_block, source, pubkey_from, pubkey_to) # sign document transaction.sign([key]) # send the Transaction document to the node response = await client(bma.tx.process, transaction.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing transaction: {0}".format( await response.text())) # Close client aiohttp session await client.close()
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter your public key: ") # init signer instance signer = SigningKey.from_credentials(salt, password) # check public key if signer.pubkey != pubkey: print("Bad credentials!") sys.exit(0) # capture current block to get currency name current_block = await client(bma.blockchain.current) # create our Identity document to sign the Certification document identity = await get_identity_document(client, current_block, pubkey) if identity is None: print("Identity not found for pubkey {0}".format(pubkey)) # Close client aiohttp session await client.close() sys.exit(1) # get the revoke document revocation_signed_raw_document = get_signed_raw_revocation_document( identity, salt, password) # save revoke document in a file fp = open(REVOCATION_DOCUMENT_FILE_PATH, "w") fp.write(revocation_signed_raw_document) fp.close() # document saved print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH) # Close client aiohttp session await client.close()
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter recipient pubkey: ") # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # capture sources of account response = await client(bma.tx.sources, pubkey_from) if len(response['sources']) == 0: print("no sources found for account %s" % pubkey_to) exit(1) # get the first source source = response['sources'][0] # create the transaction document transaction = get_transaction_document(current_block, source, pubkey_from, pubkey_to) # sign document transaction.sign([key]) # send the Transaction document to the node response = await client(bma.tx.process, transaction.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing transaction: {0}".format(await response.text())) # Close client aiohttp session await client.close()
def test_get_verified_data(self): sign_key = SigningKey.from_credentials("alice", "password", ScryptParams()) message = "Hello world with utf-8 chars like éàè !" # Sign the message, the signed string is the message itself plus the # signature signed_message = sign_key.sign(bytes(message, 'utf-8')) # type: bytes # Verify the message! verifier = VerifyingKey(sign_key.pubkey) verified_message = verifier.get_verified_data(signed_message) self.assertEqual(message, verified_message.decode('utf-8'))
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter certified pubkey: ") # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # create our Identity document to sign the Certification document identity = await get_identity_document(client, current_block, pubkey_to) if identity is None: print("Identity not found for pubkey {0}".format(pubkey_to)) # Close client aiohttp session await client.close() sys.exit(1) # send the Certification document to the node certification = get_certification_document(current_block, identity, pubkey_from) # sign document certification.sign([key]) # Here we request for the path wot/certify response = await client(bma.wot.certify, certification.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing certification: {0}".format( await response.text())) # Close client aiohttp session await client.close()
def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str: """ Generate account revocation document for given identity :param identity: Self Certification of the identity :param salt: Salt :param password: Password :rtype: str """ revocation = Revocation(PROTOCOL_VERSION, identity.currency, identity, "") key = SigningKey.from_credentials(salt, password) revocation.sign([key]) return revocation.signed_raw()
def test_load_credentials_file(self): salt = password = "******" # create a dummy credentials file with open(TEST_FILE_PATH, "w") as fh: fh.write("{}\n{}\n".format(salt, password)) # same key from credentials sign_key_test = SigningKey.from_credentials(salt, password) # test load file sign_key_load = SigningKey.from_credentials_file(TEST_FILE_PATH) self.assertEqual(sign_key_test.sk, sign_key_load.sk) self.assertEqual(sign_key_test.pubkey, sign_key_load.pubkey) self.assertEqual(sign_key_test.vk, sign_key_load.vk)
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter your public key: ") # init signer instance signer = SigningKey.from_credentials(salt, password) # check public key if signer.pubkey != pubkey: print("Bad credentials!") exit(0) # capture current block to get currency name current_block = await client(bma.blockchain.current) # create our Identity document to sign the revoke document identity_document = await get_identity_document(client, current_block['currency'], pubkey) # get the revoke document revocation_signed_raw_document = get_signed_raw_revocation_document(identity_document, salt, password) # save revoke document in a file fp = open(REVOCATION_DOCUMENT_FILE_PATH, 'w') fp.write(revocation_signed_raw_document) fp.close() # document saved print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH) # Close client aiohttp session await client.close()
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter certified pubkey: ") # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # create our Identity document to sign the Certification document identity = await get_identity_document(client, current_block, pubkey_to) # send the Certification document to the node certification = get_certification_document(current_block, identity, pubkey_from) # sign document certification.sign([key]) # Here we request for the path wot/certify response = await client(bma.wot.certify, certification.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing certification: {0}".format(await response.text())) # Close client aiohttp session await client.close()
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos by dedicated method (with json schema validation) response = await client(bma.node.summary) print(response) # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"results"][0] # create a membership demand document membership = get_membership_document("IN", current_block, identity, key) # send the membership signed raw document to the node response = await client(bma.blockchain.membership, membership.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing membership : {0}".format( await response.text())) # Close client aiohttp session await client.close()
def auth_by_scrypt(ctx): salt = getpass("Please enter your Scrypt Salt (Secret identifier): ") password = getpass("Please enter your Scrypt password (masked): ") if ctx.obj["AUTH_SCRYPT_PARAMS"]: n, r, p = ctx.obj["AUTH_SCRYPT_PARAMS"].split(",") if n.isnumeric() and r.isnumeric() and p.isnumeric(): n, r, p = int(n), int(r), int(p) if n <= 0 or n > 65536 or r <= 0 or r > 512 or p <= 0 or p > 32: message_exit( "Error: the values of Scrypt parameters are not good") scrypt_params = ScryptParams(n, r, p) else: message_exit("one of n, r or p is not a number") else: scrypt_params = None try: return SigningKey.from_credentials(salt, password, scrypt_params) except ValueError as error: message_exit(error)
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # capture current block to get version and currency and blockstamp current_block = await client(bma.blockchain.current) # prompt entry uid = input("Enter your Unique IDentifier (pseudonym): ") # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Error while publishing identity : {0}".format(await response.text())) # Close client aiohttp session await client.close()
def test_create_signed_cleartext(self): # signing key of issuer bob_signing_key = SigningKey.from_credentials("bob", "password") # message message = """ Hello world ! Héhé ;-) This is a utf-8 message... """ # create encrypted and signed ascii armor message signed_cleartext_aa_message = AsciiArmor.create( message, None, [bob_signing_key]) # split in lines for check up aa_message_lines = signed_cleartext_aa_message.splitlines() # check before message self.assertEqual(aa_message_lines[0], BEGIN_MESSAGE_HEADER) self.assertEqual("", aa_message_lines[1].strip()) # check after message self.assertEqual(aa_message_lines[10], BEGIN_SIGNATURE_HEADER) self.assertTrue(aa_message_lines[11].startswith("Version:")) self.assertEqual("", aa_message_lines[12].strip()) self.assertEqual(aa_message_lines[14], END_SIGNATURE_HEADER) # parse ascii armor message result = AsciiArmor.parse(signed_cleartext_aa_message, None, [bob_signing_key.pubkey]) # check result self.assertEqual(message + "\n", result["message"]["content"]) self.assertTrue(message + "\n", result["signatures"][0]["valid"])
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str, password: str) -> Membership: """ Get a Membership document :param membership_type: "IN" to ask for membership or "OUT" to cancel membership :param current_block: Current block data :param identity: Identity document :param salt: Passphrase of the account :param password: Password of the account :rtype: Membership """ # get current block BlockStamp timestamp = BlockUID(current_block['number'], current_block['hash']) # create keys from credentials key = SigningKey.from_credentials(salt, password) # create identity document membership = Membership( version=10, currency=current_block['currency'], issuer=key.pubkey, membership_ts=timestamp, membership_type=membership_type, uid=identity.uid, identity_ts=identity.timestamp, signature=None ) # sign document membership.sign([key]) return membership
async def main(): """ Main code """ # Arbitrary credentials to create the node key pair to sign ws2p documents salt = password = "******" # You can connect with member credentials in case there is not much slots available on the endpoint # # # Prompt hidden user entry # import getpass # salt = getpass.getpass("Enter your passphrase (salt): ") # # # Prompt hidden user entry # password = getpass.getpass("Enter your password: "******"Successfully connected to the web socket endpoint") # HANDSHAKE ####################################################### try: # Resolve handshake print("Handshake...") await handshake(ws, signing_key, CURRENCY) except ValidationError as exception: print(exception.message) print("HANDSHAKE FAILED !") sys.exit(1) print("Handshake ok") loop = True # Iterate on each message received... while loop: print("Waiting message...") # Wait and capture next message data = await ws.receive_json() print("Message received:") print(json.dumps(data, indent=2)) # Close session await client.close() except (aiohttp.WSServerHandshakeError, ValueError) as e: print("Websocket handshake {0} : {1}".format(type(e).__name__, str(e))) except (aiohttp.ClientError, gaierror, TimeoutError) as e: print("{0} : {1}".format(str(e), ws2p_endpoint.inline())) except jsonschema.ValidationError as e: print("{:}:{:}".format(str(e.__class__.__name__), str(e))) await client.close()
# CONFIG ####################################### SIGNED_MESSAGE_FILENAME = '/tmp/duniter_signed_message.bin' ################################################ if __name__ == '__main__': # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Public key for your credentials: %s" % key.pubkey) message = input("Enter your message: ") # Sign the message, the signed string is the message itself plus the # signature signed_message = key.sign(bytes(message, 'utf-8')) # type: bytes # To create a verifier pass in the verify key: veri = libnacl.sign.Verifier(key.hex_vk()) # Verify the message! verified = veri.verify(signed_message)
# CONFIG ####################################### CLEARTEXT_AA_MESSAGE_PATH = "/tmp/duniter_cleartext_aa_message.txt" ################################################ if __name__ == "__main__": # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Enter your message (Ctrl-D below last line to end):") message = sys.stdin.read() print("Message signed by puplic key : {pubkey}".format(pubkey=signing_key.pubkey)) comment = "generated by Duniterpy {0}".format(__version__) # Dash escape the message and sign it aa_cleartext_message = AsciiArmor.create( message, None, [signing_key], None, signatures_comment=comment ) # Save cleartext ascii armor message in a file with open(CLEARTEXT_AA_MESSAGE_PATH, "w") as file_handler:
if len(sys.argv) < 2: print(""" Usage: python decrypt_message.py ENCRYPTED_MESSAGE_FILEPATH """) # capture encrypted message filepath argument signed_message_path = sys.argv[1] # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Decrypted message:") except ValueError as error: message = str(error) print(message)
print(""" Usage: python decrypt_message.py ENCRYPTED_MESSAGE_FILEPATH """) # capture encrypted message filepath argument signed_message_path = sys.argv[1] # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # prompt hidden user entry password = getpass.getpass("Enter your password: "******"Decrypted message:") except ValueError as error: message = str(error) print(message)
def patched_auth_method(): return SigningKey.from_credentials(identity_uid, identity_uid)
def test_from_credentials(self): sign_key = SigningKey.from_credentials("alice", "password", ScryptParams()) verify_key = VerifyingKey(sign_key.pubkey) self.assertEqual(verify_key.vk, sign_key.vk)
async def main(): """ Main code """ # dummy credentials salt = password = "******" # You can connect with member credentials in case there is not much slots available on the endpoint # # # Prompt hidden user entry # import getpass # salt = getpass.getpass("Enter your passphrase (salt): ") # # # Prompt hidden user entry # password = getpass.getpass("Enter your password: "******"Successfully connected to the web socket endpoint") # HANDSHAKE ####################################################### try: await handshake(ws, signing_key, CURRENCY) except ValidationError as exception: print(exception.message) print("HANDSHAKE FAILED !") sys.exit(1) # Send ws2p request print("Send getCurrent() request") request_id = get_ws2p_challenge()[:8] response = await send( ws, requests.get_current(request_id), request_id, requests.BLOCK_RESPONSE_SCHEMA, ) print("Response: " + json.dumps(response, indent=2)) # Send ws2p request print("Send getBlock(30000) request") request_id = get_ws2p_challenge()[:8] response = await send( ws, requests.get_block(request_id, 30000), request_id, requests.BLOCK_RESPONSE_SCHEMA, ) print("Response: " + json.dumps(response, indent=2)) # Send ws2p request print("Send getBlocks(30000, 2) request") request_id = get_ws2p_challenge()[:8] response = await send( ws, requests.get_blocks(request_id, 30000, 2), request_id, requests.BLOCKS_RESPONSE_SCHEMA, ) print("Response: " + json.dumps(response, indent=2)) # Send ws2p request print("Send getRequirementsPending(3) request") request_id = get_ws2p_challenge()[:8] response = await send( ws, requests.get_requirements_pending(request_id, 3), request_id, requests.REQUIREMENTS_RESPONSE_SCHEMA, ) print("Response: " + json.dumps(response, indent=2)) # Close session await client.close() except (aiohttp.WSServerHandshakeError, ValueError) as e: print("Websocket handshake {0} : {1}".format(type(e).__name__, str(e))) except (aiohttp.ClientError, gaierror, TimeoutError) as e: print("{0} : {1}".format(str(e), ws2p_endpoint.inline())) except jsonschema.ValidationError as e: print("{:}:{:}".format(str(e.__class__.__name__), str(e))) await client.close()