def __init__(self, username, password): self.__username = username self.__password = password self.__pri_key = utils.get_private_key() self.__pub_key = utils.get_public_key(self.__pri_key) v = utils.sm3_hash(username.encode() + self.__pub_key)[:4] self.address = base58.b58encode(v).decode() + '@' + username pri_k = utils.sm3_hash(self.__username + self.__password)[:64] pub_k = utils.get_public_key(pri_k) code = utils.sm2_encrypt(pub_k, (self.__pri_key.decode() + '@' + self.__username).encode()) self.verification = code # 验证口令
def get_fab_public_key(): """ Returns the public key material for the private key currently being used by fab (if any) """ # If the user specified a private key via "fab -i" we use that one; # otherwise we use the default RSA key. # env.key_filename can be a list, so make sure we handle it correctly if 'key_filename' in env and env.key_filename: k_fname = env.key_filename if not isinstance(k_fname, list): fnames = [k_fname] else: fnames = k_fname else: fnames = [os.path.expanduser("~/.ssh/id_rsa")] for key_filename in fnames: if key_filename is not None and os.path.exists(key_filename): puts("Obtaining public key for private file %s" % (key_filename,)) pub_key = get_public_key(key_filename) if pub_key: puts("Public key obtained") return pub_key
def start(): global chain global data global new_blocks chain.load() sync() if chain.get_length() < 1: from_k = utils.get_private_key().decode() to_k = utils.get_public_key(from_k).decode() c = {'title': 'abc', 'content': '123', 'to': to_k, 'from': from_k} mail = Mail(to_k, c, from_k) b = Block() b.add_mail(mail) chain.add_block(b) new_blocks.append(b) data = pickle.loads(chain.last_block().data) chain.save() data = pickle.loads(chain.last_block().data) response = { 'message': "OK, is fine!", 'block_hash': chain.last_block().hash.decode(), 'length': chain.get_length(), 'accounts': len(data.account_verify) } # mail_chain.save() return jsonify(response), 200
async def message_handler(self, event): """Callback method for received events.NewMessage""" if event.text: # check if the required aes key is present. aes_shared_key = None for dlg in Dialog.select(): if dlg.dialog_id == event.sender_id: # found a entry of aes key shared with receiver. aes_shared_key = dlg.aes_shared_key break if aes_shared_key is None: # get the public key. peer_pub_key = get_public_key(event.sender_id) shared_key = my_ecdh_private_key.exchange(ec.ECDH(), peer_pub_key) aes_shared_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend(), ).derive(shared_key) peer = Dialog(dialog_id=event.sender_id, aes_shared_key=aes_shared_key) peer.save(force_insert=True) # Decrypt the msg and print. b64_enc_text_bytes = event.text.encode("utf-8") encr_msg_bytes = base64.b64decode(b64_enc_text_bytes) init_vector = encr_msg_bytes[:16] aes = Cipher( algorithms.AES(aes_shared_key), modes.CBC(init_vector), backend=default_backend(), ) decryptor = aes.decryptor() temp_bytes = decryptor.update(encr_msg_bytes[16:]) + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() temp_bytes = unpadder.update(temp_bytes) + unpadder.finalize() event.text = temp_bytes.decode("utf-8") chat = await event.get_chat() if event.is_group: sprint( '<< {} @ {} sent "{}"'.format( get_display_name(await event.get_sender()), get_display_name(chat), event.text, ) ) else: sprint('<< {} sent "{}"'.format(get_display_name(chat), event.text))
def __create_create_coin(self): # Create coin transaction inputs = [] outputs = [ Output(50, utils.get_public_key(self.user)), ] unsigned = UnsignedTransaction(CREATECOINS_TYPE, inputs, outputs) to_sign = unsigned.DataForSigs() sigs = {} sigs[self.scrooge.export_key(format='DER')] = sign(to_sign, 'privatekeyScrooge.pem') transaction = Transaction(unsigned, sigs) return transaction
def verify(self, verify_code): pri_k = utils.sm3_hash(self.__username + self.__password) try: code = utils.sm2_decrypt(pri_k, verify_code).decode() except UnicodeDecodeError: return False verification = str(code.split('@', 1)[1]) if verification == self.__username: self.__pri_key = str(code.split('@', 1)[0]).encode() self.__pub_key = utils.get_public_key(self.__pri_key) v = utils.sm3_hash(self.__username.encode() + self.__pub_key)[:4] self.address = base58.b58encode(v).decode() + '@' + self.__username self.verification = verify_code return True return False
def mine(): global waiting_mail global new_blocks sync() if len(waiting_mail) < 1: from_k = utils.get_private_key().decode() to_k = utils.get_public_key(from_k).decode() c = {'title': '000', 'content': '000', 'to': to_k, 'from': from_k} m = Mail(to_k, c, from_k) mail = {'content': m, 'to': '000', 'from': '000'} waiting_mail.append(mail) print(len(waiting_mail)) block = Block() b_loc = chain.last_block().index + 1 for mail in waiting_mail: index = block.add_mail(mail['content']) to_addr = mail['to'] from_addr = mail['from'] location = [b_loc, index] if data.addr_rec_mail.get(to_addr) is None: data.addr_rec_mail[to_addr] = [] data.addr_rec_mail[to_addr].append(location) print(to_addr, location) if data.addr_send_mail.get(from_addr) is None: data.addr_send_mail[from_addr] = [] data.addr_send_mail[from_addr].append(location) waiting_mail.clear() block.data = pickle.dumps(data) chain.add_block(block) chain.save() new_blocks.append(block) response = { 'message': 'new block is mined', 'block_index': chain.last_block().index, 'block_hash': chain.last_block().hash.decode(), 'block_nonce': chain.last_block().nonce } for node in server_neighbours: requests.get('http://{}/'.format(node)) return jsonify(response), 200
def main(): confDir = "mixnet_conf" if not path.exists(confDir): print(generate_mixnet_config(readSSH()["auth"], confDir)) hosts = readSSH() oldIp = hosts["auth"] del hosts["auth"] del hosts["monitoring"] update_auth_ip(confDir, oldIp, hosts) generate_containers_yaml(confDir) with open("client.toml", 'w') as f: f.write( clientTomlTemplate.format( "true", readSSH()["auth"], get_mixnet_port( path.join(confDir, "nonvoting", "authority.toml")), get_public_key("mixnet_conf/nonvoting")))
def render(self, *args, **kwargs): return captcha.displayhtml(get_public_key())
def setUp(self): self.client = ProfitBricksService(username=USERNAME, password=PASSWORD) self.public_key = get_public_key()
async def run(self): """Main loop of the TelegramClient, will wait for user action""" self.add_event_handler(self.message_handler, events.NewMessage(incoming=True)) # Enter a while loop to chat as long as the user wants while True: dialog_count = 15 dialogs = await self.get_dialogs(limit=dialog_count) i = None while i is None: print_title("Dialogs window") # Display them so the user can choose for i, dialog in enumerate(dialogs, start=1): sprint("{}. {}".format(i, get_display_name(dialog.entity))) # Let the user decide who they want to talk to print() print("> Who do you want to send messages to?") print("> Available commands:") print(" !q: Quits the dialogs window and exits.") print(" !l: Logs out, terminating this session.") print() i = await async_input("Enter dialog ID or a command: ") if i == "!q": return if i == "!l": await self.log_out() return try: i = int(i if i else 0) - 1 # Ensure it is inside the bounds, otherwise retry if not 0 <= i < dialog_count: i = None except ValueError: i = None # Retrieve the selected user (or chat, or channel) entity = dialogs[i].entity # Show some information print_title('Chat with "{}"'.format(get_display_name(entity))) print("Available commands:") print(" !q: Quits the current chat.") print(" !Q: Quits the current chat and exits.") print() # And start a while loop to chat while True: msg = await async_input("Enter a message: ") # Quit if msg == "!q": break if msg == "!Q": return # Send chat message (if any) if msg: # If the receiver's aes key is not present, # fetch his public key from server and derive a aes key print("SENDING MESSAGE TO ENTITTY: ", entity.id) aes_shared_key = None for dlg in Dialog.select(): if dlg.dialog_id == entity.id: # found a entry of aes shared key. aes_shared_key = dlg.aes_shared_key break if aes_shared_key is None: # get the public key. peer_pub_key = get_public_key(entity.id) shared_key = my_ecdh_private_key.exchange( ec.ECDH(), peer_pub_key ) aes_shared_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend(), ).derive(shared_key) peer = Dialog( dialog_id=entity.id, aes_shared_key=aes_shared_key ) peer.save(force_insert=True) init_vector = token_bytes(16) aes = Cipher( algorithms.AES(aes_shared_key), modes.CBC(init_vector), backend=default_backend(), ) encryptor = aes.encryptor() padder = padding.PKCS7(128).padder() padded_data = padder.update(msg.encode("utf-8")) + padder.finalize() enc_msg_bytes = encryptor.update(padded_data) + encryptor.finalize() enc_msg_bytes = init_vector + enc_msg_bytes b64_enc_txt = base64.b64encode(enc_msg_bytes).decode("utf-8") await self.send_message(entity, b64_enc_txt, link_preview=False)
def __init__(self, pass_phrase, host, port, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self._private_key = get_private_key(pass_phrase) self._public_key = get_public_key(pass_phrase) self._host = host self._port = port
def create_and_send_tx(client_socket: socket.socket, user): sender = utils.get_public_key(user) command = gui_metadata(TX_COMMAND) client_socket.send(command) inputs = [] N_inputs = int.from_bytes(client_socket.recv(4), 'little') for _ in range(N_inputs): input_data = client_socket.recv(159) inputs.append(utils.decode_input(input_data)) input_choices = [ { 'name': f'txID: {input.where_created} value: {input.value}', } for index, input in enumerate(inputs) ] recipient_choices = [ { 'name': 'Alice', }, { 'name': 'Bob', }, { 'name': 'Charlie', }, { 'name': 'No more pays', }, ] actions = [{ 'type': 'checkbox', 'name': INPUT_INDEX, 'message': 'Selecciona los inputs a ingresar en la transacción', 'choices': input_choices, }] recipient_actions = [{ 'type': 'list', 'name': 'recipient', 'message': 'Selecciona a la persona que le pagarás', 'choices': recipient_choices, }] value_actions = [{ 'type': 'input', 'name': 'value', 'message': '¿Cuánto le vas a pagar?', }] answers = prompt(actions) inputs_selected = answers.get(INPUT_INDEX) inputs_to_pay = [] for inputs_selected in inputs_selected: index = input_choices.index({'name': inputs_selected}) inputs_to_pay.append(inputs[index]) outputs = [] while True: answers = prompt(recipient_actions) answer = answers['recipient'] if answer == 'No more pays': break recipient = utils.get_public_key(answer) answers = prompt(value_actions) value = int(answers['value']) output = Output(value, recipient) outputs.append(output) unsigned = UnsignedTransaction(PAYCOINS_TYPE, inputs_to_pay, outputs) to_sign = unsigned.DataForSigs() signs = {} signs[sender.export_key(format='DER')] = sign(to_sign, utils.get_private_key(user)) transaction = Transaction(unsigned, signs) client_socket.send(transaction.serialize())