def auth_by_auth_file(ctx): """ Uses an authentication file to generate the key Authfile can either be: * A seed in hexadecimal encoding * PubSec format with public and private key in base58 encoding """ file = ctx.obj["AUTH_FILE_PATH"] authfile = Path(file) if not authfile.is_file(): message_exit('Error: the file "' + file + '" does not exist') filetxt = authfile.open("r").read() # two regural expressions for the PubSec format regex_pubkey = re.compile(PUBSEC_PUBKEY_PATTERN, re.MULTILINE) regex_signkey = re.compile(PUBSEC_SIGNKEY_PATTERN, re.MULTILINE) # Seed hexadecimal format if re.search(re.compile(SEED_HEX_PATTERN), filetxt): return SigningKey.from_seedhex_file(file) # PubSec format elif re.search(regex_pubkey, filetxt) and re.search( regex_signkey, filetxt): return SigningKey.from_pubsec_file(file) else: message_exit("Error: the format of the file is invalid")
def generate_revocation(self, connection, secret_key, password): """ Generate account revocation document for given community :param sakia.data.entities.Connection connection: The connection of the identity :param str secret_key: The account SigningKey secret key :param str password: The account SigningKey password """ document = Revocation(10, connection.currency, connection.pubkey, "") identity = self._identities_processor.get_identity( connection.currency, connection.pubkey, connection.uid) if not identity: identity = self.generate_identity(connection) identity_doc = identity.document() key = SigningKey(connection.salt, connection.password, connection.scrypt_params) identity_doc.sign([key]) identity.signature = identity_doc.signatures[0] self._identities_processor.insert_or_update_identity(identity) self_cert = identity.document() key = SigningKey(secret_key, password, connection.scrypt_params) document.sign(self_cert, [key]) return document.signed_raw(self_cert), identity
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 create(cls, walletid, salt, password, name, identities_registry): """ Factory method to create a new wallet :param int walletid: The wallet number, unique between all wallets :param str salt: The account salt :param str password: The account password :param str name: The account name """ if walletid == 0: key = SigningKey(salt, password) else: key = SigningKey(b"{0}{1}".format(salt, walletid), password) return cls(walletid, key.pubkey, name, identities_registry)
def check_password(self, salt, password): """ Check if wallet password is ok. :param salt: The account salt :param password: The given password :return: True if (salt, password) generates the good public key .. warning:: Generates a new temporary SigningKey from salt and password """ key = None if self.walletid == 0: key = SigningKey(salt, password) else: key = SigningKey("{0}{1}".format(salt, self.walletid), password) return (key.pubkey == self.pubkey)
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)
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'])
async def revoke(self, currency, identity, salt, password): """ Revoke self-identity on server, not in blockchain :param str currency: The currency of the identity :param sakia.data.entities.IdentityDoc identity: The certified identity :param str salt: The account SigningKey salt :param str password: The account SigningKey password """ revocation = Revocation(10, currency, None) self_cert = identity.document() key = SigningKey(salt, password) revocation.sign(self_cert, [key]) self._logger.debug("Self-Revokation Document : \n{0}".format( revocation.raw(self_cert))) self._logger.debug("Signature : \n{0}".format( revocation.signatures[0])) data = { 'pubkey': identity.pubkey, 'self_': self_cert.signed_raw(), 'sig': revocation.signatures[0] } self._logger.debug("Posted data : {0}".format(data)) responses = await self._bma_connector.broadcast( currency, bma.wot.Revoke, {}, data) result = await parse_bma_responses(responses) return result
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
async def send_membership(self, connection, secret_key, password, mstype): """ Send a membership document to a target community. Signal "document_broadcasted" is emitted at the end. :param sakia.data.entities.Connection connection: the connection publishing ms doc :param str secret_key: The account SigningKey salt :param str password: The account SigningKey password :param str mstype: The type of membership demand. "IN" to join, "OUT" to leave """ self._logger.debug("Send membership") blockUID = self._blockchain_processor.current_buid(connection.currency) membership = Membership(10, connection.currency, connection.pubkey, blockUID, mstype, connection.uid, connection.blockstamp, None) key = SigningKey(secret_key, password, connection.scrypt_params) membership.sign([key]) self._logger.debug("Membership : {0}".format(membership.signed_raw())) responses = await self._bma_connector.broadcast( connection.currency, bma.blockchain.membership, req_args={'membership': membership.signed_raw()}) result = await parse_bma_responses(responses) return result
def test_load_ssb_file(self): dummy_content = """ # comments # # { "curve": "ed25519", "public": "dGVzdHRlc3R0ZXN0dGV0c3RldHN0dGV0c3RldGV0ZXRldHN0ZXR0c3RldHN0dGV0c3Q=.ed25519", "private": "dGVzdHRlc3R0ZXN0dGV0c3RldHN0dGV0c3RldGV0ZXRldHN0ZXR0c3RldHN0dGV0c3Q==.ed25519", "id": "@qJ8qVfXU2mIWG9WfKIRsd6GDscQlErzPHsxzHcyQMWQ=.ed25519" } # # comments """ # create dummy .ssb/secret file with open(TEST_FILE_PATH, "w") as fh: fh.write(dummy_content) # test load file sign_key_load = SigningKey.from_credentials_file(TEST_FILE_PATH) self.assertEqual(sign_key_load.pubkey, "FAhCeyWq2Ni2xZS3hmYk5w95f8ELxNhUVvU5VB2LXy49") self.assertEqual( sign_key_load.sk.hex(), "f2f7ae68635dba3455390a74ca0811e4c06142229bb58556aaa37d5598548c9ed27f4cb2bfadbaf45b61714b896d4639ab90db035aee746611cdd342bdaa8996", ) self.assertEqual( sign_key_load.vk.hex(), "d27f4cb2bfadbaf45b61714b896d4639ab90db035aee746611cdd342bdaa8996", )
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 get_membership_document(mtype, current_block, identity, salt, password): """ Get a Membership document :param str mtype: "IN" to ask for membership or "OUT" to cancel membership :param dict current_block: Current block data :param Identity identity: Identity document :param str salt: Passphrase of the account :param str 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(salt, password, ScryptParams(4096, 16, 1)) # create identity document membership = Membership(version=10, currency=current_block['currency'], issuer=key.pubkey, membership_ts=timestamp, membership_type=mtype, uid=identity.uid, identity_ts=identity.timestamp, signature=None) # sign document membership.sign([key]) return membership
def get_identity_document(current_block, uid, salt, password): """ Get an Identity document :param dict current_block: Current block data :param str uid: Unique Identifier :param str salt: Passphrase of the account :param str password: Password of the account :rtype: SelfCertification """ # get current block BlockStamp timestamp = BlockUID(current_block['number'], current_block['hash']) # create keys from credentials key = SigningKey(salt, password) # create identity document identity = SelfCertification(version=2, 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'])
async def send_money(self, connection, secret_key, password, recipient, amount, amount_base, message): """ Send money to a given recipient in a specified community :param sakia.data.entities.Connection connection: The account salt :param str secret_key: The account secret_key :param str password: The account password :param str recipient: The pubkey of the recipient :param int amount: The amount of money to transfer :param int amount_base: The amount base of the transfer :param str message: The message to send with the transfer """ blockstamp = self._blockchain_processor.current_buid(connection.currency) key = SigningKey(secret_key, password, connection.scrypt_params) logging.debug("Sender pubkey:{0}".format(key.pubkey)) tx_entities = [] result = (True, ""), tx_entities try: tx_entities = self.prepare_tx(key, recipient, blockstamp, amount, amount_base, message, connection.currency) for i, tx in enumerate(tx_entities): logging.debug("Transaction : [{0}]".format(tx.raw)) tx_res, tx_entities[i] = await self._transactions_processor.send(tx, connection.currency) # Result can be negative if a tx is not accepted by the network if result[0]: if not tx_res[0]: result = (False, tx_res[1]), tx_entities result = result[0], tx_entities return result except NotEnoughChangeError as e: return (False, str(e)), tx_entities
async def send_membership(self, password, community, mstype): """ Send a membership document to a target community. Signal "document_broadcasted" is emitted at the end. :param str password: The account SigningKey password :param community: The community target of the membership document :param str mstype: The type of membership demand. "IN" to join, "OUT" to leave """ logging.debug("Send membership") blockUID = community.network.current_blockUID self_identity = await self._identities_registry.future_find(self.pubkey, community) selfcert = await self_identity.selfcert(community) membership = Membership(PROTOCOL_VERSION, community.currency, selfcert.pubkey, blockUID, mstype, selfcert.uid, selfcert.timestamp, None) key = SigningKey(self.salt, password) membership.sign([key]) logging.debug("Membership : {0}".format(membership.signed_raw())) responses = await community.bma_access.broadcast(bma.blockchain.Membership, {}, {'membership': membership.signed_raw()}) result = (False, "") for r in responses: if r.status == 200: result = (True, (await r.json())) elif not result[0]: result = (False, (await r.text())) else: await r.release() return result
async def revoke(self, password, community): """ Revoke self-identity on server, not in blockchain :param str password: The account SigningKey password :param sakia.core.community.Community community: The community target of the revokation """ revoked = await self._identities_registry.future_find(self.pubkey, community) revokation = Revocation(PROTOCOL_VERSION, community.currency, None) selfcert = await revoked.selfcert(community) key = SigningKey(self.salt, password) revokation.sign(selfcert, [key]) logging.debug("Self-Revokation Document : \n{0}".format(revokation.raw(selfcert))) logging.debug("Signature : \n{0}".format(revokation.signatures[0])) data = { 'pubkey': revoked.pubkey, 'self_': selfcert.signed_raw(), 'sig': revokation.signatures[0] } logging.debug("Posted data : {0}".format(data)) responses = await community.bma_access.broadcast(bma.wot.Revoke, {}, data) result = (False, "") for r in responses: if r.status == 200: result = (True, (await r.json())) elif not result[0]: result = (False, (await r.text())) else: await r.release() return result
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_signature_block(message: str, signing_key: SigningKey, close_block: bool = True, comment: Optional[str] = None) -> str: """ Return a signature block :param message: Message (not encrypted!) to sign :param signing_key: The libnacl SigningKey instance of the keypair :param close_block: Optional flag to close the signature block with the signature tail header :param comment: Optional comment field content :return: """ base64_signature = base64.b64encode(signing_key.signature(message)) block = """{begin_signature_header} {version_field} """.format(begin_signature_header=BEGIN_SIGNATURE_HEADER, version_field=AsciiArmor._get_version_field()) # add message comment if specified if comment: block += """{comment_field} """.format(comment_field=AsciiArmor._get_comment_field(comment)) # blank line separator block += '\n' block += """{base64_signature} """.format(base64_signature=base64_signature.decode('utf-8')) if close_block: block += END_SIGNATURE_HEADER return block
async def start(cls, port, currency, salt, password, loop): key = SigningKey(salt, password, ScryptParams(2**12, 16, 1)) node = cls(HTTPServer(port, loop), BlockForge(currency, key)) get_routes = { '/network/peering': node.peering, '/blockchain/block/{number}': node.block_by_number, '/blockchain/current': node.current_block, '/tx/sources/{pubkey}': node.sources, '/wot/lookup/{search}': node.lookup, '/wot/certifiers-of/{search}': node.certifiers_of, '/wot/certified-by/{search}': node.certified_by, '/wot/requirements/{pubkey}': node.requirements, '/blockchain/parameters': node.parameters, '/blockchain/with/ud': node.with_ud, '/blockchain/memberships/{search}': node.memberships, '/tx/history/{search}': node.tx_history, '/ud/history/{search}': node.ud_history, } post_routes = { '/wot/add': node.add, '/wot/certify': node.certify, '/tx/process': node.process } for r, h in get_routes.items(): node.http.add_route("GET", r, h) for r, h in post_routes.items(): node.http.add_route("POST", r, h) port, url = await node.http.create_server() print("Server started on {0}".format(url)) return node
def get_certification_document(current_block, self_cert_document, from_pubkey, salt, password): """ Create and return a Certification document :param dict current_block: Current block data :param Identity self_cert_document: Identity document :param str from_pubkey: Pubkey of the certifier :param str salt: Secret salt (DO NOT SHOW IT ANYWHERE, IT IS SECRET !!!) :param str password: Secret password (DO NOT SHOW IT ANYWHERE, IT IS SECRET !!!) :rtype: Certification """ # construct Certification Document certification = Certification(version=10, currency=current_block['currency'], pubkey_from=from_pubkey, pubkey_to=self_cert_document.pubkey, timestamp=BlockUID(current_block['number'], current_block['hash']), signature="") # sign document key = SigningKey(salt, password, ScryptParams(4096, 16, 1)) certification.sign(self_cert_document, [key]) return certification
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 set_scrypt_infos(self, salt, password, scrypt_params): self.connection.salt = salt self.connection.scrypt_N = scrypt_params.N self.connection.scrypt_r = scrypt_params.r self.connection.scrypt_p = scrypt_params.p self.connection.password = password self.connection.pubkey = SigningKey(self.connection.salt, password, scrypt_params).pubkey
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'))
def auth_by_wif(): wif_hex = getpass("Enter your WIF or Encrypted WIF address (masked): ") password = getpass( "(Leave empty in case WIF format) Enter the Encrypted WIF password (masked): " ) try: return SigningKey.from_wif_or_ewif_hex(wif_hex, password) except Exception as error: message_exit(error)
def check_password(self, password): """ Method to verify the key password validity :param str password: The key password :return: True if the generated pubkey is the same as the account .. warnings:: Generates a new temporary SigningKey """ key = SigningKey(self.salt, password) return (key.pubkey == self.pubkey)
def set_scrypt_infos(self, salt, password): """ Change the size of the wallet pool :param int size: The new size of the wallet pool :param str password: The password of the account, same for all wallets """ self.salt = salt self.pubkey = SigningKey(self.salt, password).pubkey wallet = Wallet.create(0, self.salt, password, "Wallet", self._identities_registry) self.wallets.append(wallet)
def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str: """ Decrypt a message from ascii armor format :param ascii_armor_message: Utf-8 message :param signing_key: SigningKey instance created from credentials :return: """ data = signing_key.decrypt_seal(base64.b64decode(ascii_armor_message)) return data.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) 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 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 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'))
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()
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()
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
# you'll have to use one of your private keys instead PRIVATE_KEY_FILE_PATH = os.path.join(home_path, ".duniter_account_pubsec_v1.duniterkey") ################################################ # 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(1) # save private key in a file (PubSec v1 format) signer.save_pubsec_file(PRIVATE_KEY_FILE_PATH) # document saved print("Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH)) try: # load private keys from file loaded_signer = SigningKey.from_pubsec_file(PRIVATE_KEY_FILE_PATH)
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)
# 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)
# you'll have to use one of your private keys instead PRIVATE_KEYS_FILE_PATH = os.path.join(home_path, ".duniter_account_private_keys.txt") ################################################ # 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(1) # save private keys in a file (json format) signer.save_private_key(PRIVATE_KEYS_FILE_PATH) # document saved print("Private keys for public key %s saved in %s" % (pubkey, PRIVATE_KEYS_FILE_PATH)) # load private keys from file loaded_signer = SigningKey.from_private_key(PRIVATE_KEYS_FILE_PATH)
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)