def acceptInputs(self, r, payL, payR, wdrawL, wdrawR): assert self.status == "OK" assert r == self.lastRound + 1 # Assumption - don't call acceptInputs(r,...) multiple times depositsL = self.contract.deposits(0) depositsR = self.contract.deposits(1) withdrawalsL = self.contract.withdrawals(0) withdrawalsR = self.contract.withdrawals(1) _, (creditsL, creditsR, withdrawnL, withdrawnR) = self.lastCommit assert payL <= depositsL + creditsL assert payR <= depositsR + creditsR assert wdrawL <= depositsL + creditsL - payL assert wdrawR <= depositsR + creditsR - payR creditsL += payR - payL - wdrawL creditsR += payL - payR - wdrawR withdrawalsL += wdrawL withdrawalsR += wdrawR self.lastProposed = (creditsL, creditsR, withdrawalsL, withdrawalsR) self.h = utils.sha3( state_to_bytes(self.contract.address, r, creditsL, creditsR, withdrawalsL, withdrawalsR)) sig = sign(self.h, self.sk) broadcast(self, r, self.h, sig) return sig
def return_note(client_data): """ Create a promissory note from data, sign it with the private key, and send it back to the client. :param data: dictonnary (or json file?) containing data provided by the client :return: some object (json file?) representing the note, send to the client via internet """ # some formatting/checking of "client_data" pass # create note note = Note(client_data) # create first transaction and sign new_transaction = { 'cle': client_data['public_key'], 'hash_info_payment': None, 'signature': None } note.transactions.append(new_transaction) my_sig = sign(note, MY_PRIVATE_KEY) note.transactions[-1]['signature'] = my_sig # return to client return note.display_web_format( ) # dans un format qui va bien dans tuyau internet, genre json
def main(): print('your address:', my_address) server = Server() server.start() while True: cmd = input() if cmd == 'mine': print('mining...') Miner().start() elif cmd == 'balance': print(get_state(my_address).balance) elif cmd == 'chain': print(json.dumps(get_current_chain(), default=lambda o: o.__dict__)) elif cmd == 'send': to = input('to: ') value = int(input('value: ')) n = next_nonce(my_address) m = my_address + ' ' + to + ' ' + str(value) + ' ' + str(n) if add_transaction( Transaction(my_address, to, value, n, sign(private_key, m))): print('success') elif cmd == 'nodes': print(nodes) elif cmd == 'node': node = input('ip: ') add_node(node) elif cmd == 'pool': print(json.dumps(transactions_pool, default=lambda o: o.__dict__)) else: print('unsupported command')
def add_transaction(to, amount, addr, public: PublicKey, private: PrivateKey): t = Transaction(addr, to, amount, '', public) print(t.message()) t.sign = sign(t.message(), private) data = t.to_dict() resp = requests.post(b_url + '/add_transaction', json=data) return resp.text
def transaction(receiver, amount, times=1): global public global private global blockchain if get_balance(public) < amount: print "You don't have enough HackCoins." return txns = [] if os.path.exists(TXN_FILE): with open(TXN_FILE, 'r') as f: txns_json = f.read() txns = jsonpickle.decode(txns_json) for _ in range(times): # Build a new transaction. t = Transaction(id=gen_uuid(), owner=public, receiver=receiver, coins=amount, signature=None) # Sign it. t.signature = sign(t.comp(), private) # Place it in the miner queue to be mined. txns.append(t) with open(TXN_FILE, 'w') as f: f.write(jsonpickle.encode(txns))
def paySomeone(public, private, target, amount): txn = Transaction(id=gen_uuid(), owner=public, receiver=target, coins=amount, signature=None) txn.signature = sign(txn.comp(), private) return txn
def mint_coin(pubkey_owner): """ Tells the mint to create a new coin and assign it to the public key of the new owner """ return Transaction(current_owner_pubkey=pubkey_owner, previous_owner_pubkey=mint_pubkey, transaction_signature=sign(crypto_hash(pubkey_owner), mint_passphrase))
def __init__(self, forwarder, receiver, amount, publickey): self.forwarder = forwarder self.receiver = receiver self.amount = amount self.publickey = publickey self.signature = crypto.sign(str(self)) self.hashed = hashlib.md5(str( self.signature).encode('utf-8')).hexdigest()
def test_sign(): for _ in range(5): privkey = RSA.generate(2048) pubkey = privkey.publickey() for str_len in range(2, 200): message = 'ENO{%s}' % ''.join( [random.choice(string.printable[:95]) for _ in range(str_len)]) signature = sign(message, privkey) assert verify(message, signature, pubkey)
def send( text: str , s: sock.socket.socket , own_priv: crypto.Priv , remote_pub: crypto.Pub ) -> None: signature = crypto.sign(text, own_priv) encrypted = crypto.encrypt(text, remote_pub) msg = pack.Packet(encrypted, signature).to_bytes() s.sendall(msg)
def send(coin, pubkey_next_owner, current_owner_privkey): """ Simulate the owner of the coin sending the coin to another user's public key by creating a valid signature for it """ to_hash = combine_hex(coin.transaction_signature, pubkey_next_owner) to_sign = crypto_hash(to_hash) return Transaction(current_owner_pubkey=pubkey_next_owner, previous_owner_pubkey=coin.current_owner_pubkey, transaction_signature=sign(to_sign, current_owner_privkey), previous_transaction=coin)
def _cast_vote(self, chosen_candidate, proof): content = { "proof": proof, "vote": crypto.encrypt(str(chosen_candidate), self.election_public_key) } return { "content": content, "header": { "signature": crypto.sign(json.dumps(content, sort_keys=True), self.private_key), "vcm_id": self.id } }
def wsgiapp(environ, start_response): req = webob.Request(environ) try: result =crypto.sign(req.params["input"]) start_response('200 OK', [('Content-Type', 'text/plain')]) yield base64.b64encode(result) except Exception, e: logging.exception(e) start_response('500 Server error', [('Content-Type', 'text/plain')]) yield "There was an error."
def mint(self, Node, lastBlock, stop): tx = chr(random.randint(1, 100)) mroot = hashlib.sha256(tx).hexdigest() timestamp = str(datetime.datetime.now()) c_header = str(lastBlock.hash) + mroot + timestamp keys = Node.keys() signature = crypto.sign( str(lastBlock.index + 1) + str(lastBlock.hash), keys) hash_result = crypto.hash(str(c_header)) if stop.is_set(): return False, False, False, False elected = self.election(Node, lastBlock) if elected: return block.Block(lastBlock.index + 1, lastBlock.hash, keys, signature, hash_result)
def test_command_joke(): service = Store() pubkey = RSA.import_key(service.process_command('send_pubkey'.encode())) privkey = RSA.import_key(open('../checker/checker.privkey', 'r').read()) tick = random.randint(1, 1 << 32) joke = 'How do you call a fly without wings? - A walk.' content = 'joke %s %d' % (hexlify(joke.encode()).decode(), tick) res = service.process_command( ('receive %s %s' % (content, sign(content, privkey))).encode()) assert res == sha256(joke.encode()).hexdigest() input_command = ('send joke %d' % tick).encode() res = service.process_command(input_command) test_flag = decrypt(res, privkey=privkey) assert test_flag == flag
def run_miner(): """Run the main miner loop. """ global blockchain global public global private while True: # Load transaction queue and blockchain from server. txns = load_transactions() blockchain = load_blockchain() # Add reward to us yay. reward = Transaction(id=gen_uuid(), owner="mined", receiver=public, coins=REWARD, signature=None) reward.signature = sign(reward.comp(), private) txns.append(reward) # Construct a new block. b = Block(timestamp=datetime.datetime.now(), transactions=txns, previous_hash=blockchain.head.hash_block()) # Let's mine this block. mine_till_found(b) # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() if new_chain.head.hash_block() == blockchain.head.hash_block(): # WE MINED THIS BLOCK YAY. # AND WE WIN. resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message'] else: print "Someone else mined the block before us :("
def _send_msg(self, message, msgid): ''' Send one message using stomppy. The message will be signed using the host cert and key. If an encryption certificate has been supplied, the message will also be encrypted. ''' log.info('Sending message: ' + msgid) headers = {'destination': self._dest, 'receipt': msgid, 'empa-id': msgid} if message is not None: to_send = crypto.sign(message, self._cert, self._key) if self._enc_cert is not None: to_send = crypto.encrypt(to_send, self._enc_cert) else: to_send = '' self._conn.send(to_send, headers=headers)
def test_command_flag(): service = Store() pubkey = RSA.import_key(service.process_command('send_pubkey'.encode())) privkey = RSA.import_key(open('../checker/checker.privkey', 'r').read()) for str_len in range(2, 20): tick = random.randint(1, 1 << 32) flag = 'ENO{%s}' % ''.join( [random.choice(string.printable[:95]) for _ in range(str_len)]) data = encrypt(flag, pubkey) content = 'flag %s %d' % (data, tick) res = service.process_command( ('receive %s %s' % (content, sign(content, privkey))).encode()) assert res == sha256(flag.encode()).hexdigest() input_command = ('send flag %d' % tick).encode() res = service.process_command(input_command) test_flag = decrypt(res, privkey=privkey) assert test_flag == flag
def add_vote(self, vote): vote["header"]["hash_of_proof"] = crypto.sha256( json.dumps(vote["content"]["proof"], sort_keys=True)) self.validate_vote(vote) self.check_casted_vote(vote) self._votes.append(vote) if len(self._votes) >= config.BLOCKCHAIN_BLOCK_VOTE_LIMIT: self.blockchain.add_block({ "content": self._votes, "header": { "signature": crypto.sign(json.dumps(self._votes, sort_keys=True), self.private_key), "miner_id": self.id } }) self._votes = []
from note import Note # à coder from crypto import sign, verify # à coder import requests # pour l'exemple URL_SERVER = 'http://localhost' MY_PRIVATE_KEY = 'XXXX' # get data for payment # à coder merchant_key = 'YYYY' data = {'montant': 1, 'cle': merchant_key} # send a request to the server and get back the note r = requests.get(url, data = data) response_from_server = r.content() # ou r.json() ? note = Note(response_from_server) # il faudra surement reformater response # verify note signature if not verify(note, note.transactions[-1]['signature']): raise SignatureError # à coder # create new transaction and sign new_transaction = {'cle': merchant_key, 'hash_info_payment': None, 'signature': None} note.transactions.append(new_transaction) my_sig = sign(note, MY_PRIVATE_KEY) note.transactions[-1]['signature'] = my_sig # send to merchant note.display_QR_code() # une manière de faire parmi d'autres
def sign(self, data): return crypto.sign(self._key, data)
def sign(self, msg): return crypto.sign(msg, crypto.encode_privkey(self.private_key))
def sign(self, priv_key, password): return crypto.sign(priv_key, password, self.get_hash())
def main(): """ Main que gestiona todo el funcionamiento del sistema. :return: """ # Creamos un parser para los argumentos de entrada del programa parser = argparse.ArgumentParser(description="Cliente SecureBox") # Ayuda # Gestion de usuarios parser.add_argument("--create_id", nargs=2, metavar=('name', 'email')) parser.add_argument("--search_id", nargs=1, metavar=('data')) parser.add_argument("--delete_id", nargs=1, metavar=('user_id')) # Gestion de ficheros parser.add_argument("--upload", nargs=1, metavar=('file')) parser.add_argument("--source_id", nargs=1, metavar=('user_id')) parser.add_argument("--dest_id", nargs=1, metavar=('user_id')) parser.add_argument("--list_files", action='store_true') parser.add_argument("--download", nargs=1, metavar=('file_id')) parser.add_argument("--delete_file", nargs=1, metavar=('file_id')) # Gestion del cifrado y firmado de documentos parser.add_argument("--encrypt", nargs=1, metavar=('file')) parser.add_argument("--sign", nargs=1, metavar=('file')) parser.add_argument("--enc_sign", nargs=1, metavar=('file')) # Se parsean los argumentos args = parser.parse_args() # Si no se encuentan los parametros suficientes if len(sys.argv) < 2: print( "Se necesitan mas argumentos de entrada para ejecutar el programa." ) print("Si necesita ayuda ejecute el programa con la flag --help") return # Gestion de usuarios if args.create_id: users.register_user(name=args.create_id[0], email=args.create_id[1], token=token) elif args.search_id: users.search_user(data_search=args.search_id[0], token=token) elif args.delete_id: users.delete_user(user_id=args.delete_id[0], token=token) # Gestion de cifrado y firmado elif args.encrypt and args.dest_id: key = users.get_public_key(user_id=args.dest_id[0], token=token) crypto.encrypt(file=args.encrypt[0], public_key_receiver=key) elif args.sign: crypto.sign(file=args.sign[0]) elif args.enc_sign and args.dest_id: key = users.get_public_key(user_id=args.dest_id[0], token=token) crypto.encrypt_and_sign(file=args.enc_sign[0], public_key_receiver=key) # Gestion de ficheros elif args.upload and args.dest_id: key = users.get_public_key(user_id=args.dest_id[0], token=token) files.upload_file(file=args.upload[0], public_key_dest=key, token=token) elif args.list_files: files.list_files(token=token) elif args.download and args.source_id: key = users.get_public_key(user_id=args.source_id[0], token=token) files.download_file(file_id=args.download[0], public_key_receiver=key, token=token) elif args.delete_file: files.delete_file(file_id=args.delete_file[0], token=token) else: print("Comando no soportado") print( "Revise con el comando --help los comandos que puede ejecutar el cliente SecureBox." )
resp = 'Invalid card' print(resp) else: if cardAmount[pi['cardN']] < pi['amount']: resp = 'Insuficient founds' print(resp) else: # modify account balance cardAmount[pi['cardN']] -= pi['amount'] resp = resp + '\tCard Balance: ' + str( cardAmount[pi['cardN']]) #the response along with all the other info is DG signedMessage = crypto.sign( pickle.dumps({ 'resp': resp, 'sid': pi['sid'], 'amount': pi['amount'], 'nc': clientNonce }), filenameKey) transactionInfo = pickle.dumps({ 'resp': resp, 'sid': pi['sid'], 'signedMessage': signedMessage }) encryptedTransactionInfo = crypto.encryptAES( transactionInfo, AESkeyM) encryptedKey = crypto.encryptRSA(AESkeyM, pubKM) conn.sendall( pickle.dumps({ 'encryptedTransactionInfo': encryptedTransactionInfo,
def test_sign(): priv = crypto.generate_rsa_key(complexity=512) message = "Secret wish list" sig = crypto.sign(message, priv) assert crypto.verify_signature(sig, message, priv.public_key())
pi = { 'cardN': b'4026467078008334', 'cardExp': datetime.datetime(2020, 9, 10), 'PIN': b'2334', 'amount': produse[produs], 'sid': SID, 'nc': 1, 'M': b'merchantName' } #Payment Message #PM = {PI, DSigC(PI)} PubKPG #prevent the merchant from seeing the credit Card info pm = { 'pi': pickle.dumps(pi), 'signedPi': crypto.sign(pickle.dumps(pi), rsaKeyFilename) } #the message is encrypted using the PubKPG encryptedPm = crypto.encryptAES(pickle.dumps(pm), AESkeyPG) encryptedPGkey = crypto.encryptRSA(AESkeyPG, pubKPG) #relevant order info #OI poContent = pickle.dumps({ 'orderDesc': produs, 'sid': SID, 'amount': produse[produs] }) #semnatura digitala pentru OI po = { 'poContent': poContent,
def set_signature(self, lifetime=None): """Generates a signature to prevent XSRF (a confused deputy attack).""" self.vars['signature'] = crypto.sign( self.xsrf_key, self.user.user_id(), lifetime)
def send_signed_rebalance_set(self, leader): return { 'leader': leader, 'participant': self, 'signature': sign(self.instance_hash, self.private_key) }
def sign_image(): global image global label_success label_success.destroy() # used for performance metric intime = time.time_ns() # Generate signature using message signature = crypto.sign(message) print(f'-\nSignature:\n{signature}') # Convert signature to base64 signature = base64.b64encode(signature) print(f'-\nBase64 Signature:\n{signature}') data = signature # load the image img = cv2.imread(image) #### FACIAL DETECTION #### # establish initial bounds # [x, y, width, height] where x, y is for the top left bounding pixel bounds = [0, 0, img.shape[0], img.shape[1]] # update our bounds based on the largest face detected bounds = facedetect.getFace(image) # narrow our facial bounds to: # - improve performance during verification # - focus our manipulation onto the main facial area bounds = [ bounds[0] + bounds[2] // 4, bounds[1] + bounds[3] // 4, bounds[2] // 2, bounds[3] // 2 ] #### STEGANOGRAPHY #### # strip the signature from the image by inverting our LSB algorithm # check if data (+ 5-character stopping sequence) can fit in the bounds if (len(data) + 5) * 8 > bounds[2] * bounds[3] * 3: raise ValueError('ERROR: too much data to fit in facial bounds') # append stopping sequence of 5 underscores '_____' data_str = str(data) + '_____' print('-\nFINAL DATA STRING:\n' + data_str) # convert data to binary bin_data = helper.to_binary(data_str) # keep track of where we are in bin_data data_index = 0 for x in range(bounds[1], bounds[1] + bounds[3]): # rows for y in range(bounds[0], bounds[0] + bounds[2]): # cols r, g, b = helper.to_binary(img[x, y]) # apply LSB manipulation if data_index < len(bin_data): # red channel: replace LSB with current index of our binary data img[x][y][0] = int(r[:-1] + bin_data[data_index], 2) data_index += 1 if data_index < len(bin_data): # green channel: replace LSB with current index of our binary data img[x][y][1] = int(g[:-1] + bin_data[data_index], 2) data_index += 1 if data_index < len(bin_data): # blue channel: replace LSB with current index of our binary data img[x][y][2] = int(b[:-1] + bin_data[data_index], 2) data_index += 1 # check if we've reached the end of our data if data_index >= len(bin_data): break # path and image name were separated and modified for organization during experimentation path = image[:image.rfind('/')] image = image[image.rfind('/'):image.rfind('.')] + '_signed.png' # write the signed image to a new file cv2.imwrite(f'{path}{image}', img) # used for performance metrics outtime = time.time_ns() signtime = (outtime - intime) // 1000000 # create a clean console output for gathering performance metrics print(f"""---------- FILENAME: {path}{image} DIMENSIONS: {img.shape[1]} x {img.shape[0]} MESSAGE LENGTH: {len(message)} SIGNING TIME: {signtime} ----------""") #display the success label label_success = Label(bottom_frame, text="Signing Successful!", bg='lightgreen', font=('arial', 20)) label_success.pack(side=LEFT)
def _sign_blob(tx_blob, seed, test=False): signing_hash = _get_signing_hash(tx_blob, test) signature = crypto.sign(signing_hash, seed) return signature
def sign_transaction_blob(seed, blob): signing_hash = get_signing_hash(blob) key = crypto.get_private_key(seed.data) signature = crypto.sign(signing_hash, key) return signature
def run_miner(): """Run the main miner loop. """ global blockchain global public global private while True: # Load transaction queue and blockchain from server. txns = load_transactions() blockchain = load_blockchain() # Loc: Check our balance balance = get_balance(public) print "Current balance", balance # Loc: Set up attack is_attacking = False if balance > 60: print "Setting up Finney attack" is_attacking = True t = Transaction( id=gen_uuid(), owner=public, receiver= "6f181e44edfc93de084071e590421e5b083f93da6012d441658b6b31a966ae9c", coins=balance, signature=None) # Sign it. t.signature = sign(t.comp(), private) # Pay myself a lot! for x in range(0, 3): txns.append(t) # Add reward to us yay. reward = Transaction(id=gen_uuid(), owner="mined", receiver=public, coins=REWARD, signature=None) reward.signature = sign(reward.comp(), private) txns.append(reward) # Construct a new block. b = Block(timestamp=datetime.datetime.now(), transactions=txns, previous_hash=blockchain.head.hash_block()) # Let's mine this block. mine_till_found(b) # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() if new_chain.head.hash_block() == blockchain.head.hash_block(): # WE MINED THIS BLOCK YAY. # AND WE WIN. # Loc: Add in a Finney attack to double spend the coin resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message'] else: print "Someone else mined the block before us :("
def run_miner(): """Run the main miner loop. """ my_address = "2cb4fc5902917e58e531cfbe1d909727aaf331b4856bf8627e09bf8941b69a40" my_private = "610af1630bf08b0072d97bdaf71882cd0a2c86e7af72296b4ee73f508b812c28" my_address_2 = "a173fd8d2330cc2b4776730891f50099204376217c67b7b23254aca04fbeb5a3" my_private_2 = "d0f783f01ac0df1799856964fe74f702763932e1edf3e9d0074646de885d5559" public = my_address_2 private = my_private_2 donor = None while True: print("new public", public) print("new private", private) global blockchain global real_b1 global fake_b1 global fake_b2 blockchain = load_blockchain() # Add reward to us yay. # my_address_3 = "5adbd7137903135fa2cc5a2de2035a326319e42188a9c6714b26fa016c6ac1bb" # my_private_3 = "91f233e1218135b772ddc87a199e6d3cc18233753623f95385dde62e886304c7" amount_1 = blockchain.get_wallet_amount(my_address) amount_2 = blockchain.get_wallet_amount(my_address_2) # amount_3 = blockchain.get_wallet_amount(my_address_3) if amount_1 < 0: my_private, my_address = generate_keys() public = my_address private = my_private donor_pub = my_address_2 donor_private = my_private_2 donor_amount = amount_2 else: my_private_2, my_address_2 = generate_keys() public = my_address_2 private = my_private_2 donor_pub = my_address donor_private = my_private donor_amount = amount_1 # Add reward to us yay. reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) txns = [] reward.signature = sign(reward.comp(), private) txns.append(reward) donation1 = Transaction( id = gen_uuid(), owner = donor_pub, receiver = "3119281c76dc54009925c9208bedc5bd0162c27034a1649fd7e2e5df62dba557", coins = donor_amount, signature = None ) donation1.signature = sign(donation1.comp(), donor_private) donation2 = Transaction( id = gen_uuid(), owner = donor_pub, receiver = public, coins = donor_amount, signature = None ) donation2.signature = sign(donation2.comp(), donor_private) txns.append(donation1) txns.append(donation2) # Construct a new block. real_b1 = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = blockchain.head.hash_block() ) mine_till_found(real_b1) new_chain = load_blockchain() # print "Adding real block now" # resp1 = get_route('add', data=str(real_b1)) # if resp1['success']: # print "Added real block1!" # else: # print "Couldn't add block:", resp1['message'] if new_chain.head.hash_block() == blockchain.head.hash_block(): print "Adding real block now" resp1 = get_route('add', data=str(real_b1)) if resp1['success']: print "Added real block1!" else: print "Couldn't add block:", resp1['message'] else: print "Someone else mined the block before us :("
def sign(self, device=None): if not self.id: self.id = self.get_uuid() self.signed_by = device or Device.get_own_device() self.signature = crypto.encode_base64(crypto.sign(self._hashable_representation()))
file_name = os.path.basename(args.encrypt) f = open(u.path_archivos + "enc_" + file_name, "wb") f.write(mensaje_cifrado) f.close() except FileNotFoundError: print("El archivo no existe") else: print("--encrypt necesita --dest_id") # Firmamos un fichero y la guardamos en path_archivos elif args.sign: try: f = open(args.sign, 'rb') mensaje = f.read() firma_digital = crypto.sign(mensaje) f.close() # Si se ha firmado correctamente guardamos la firma y el mensaje como: sign_ + nombre del fichero if firma_digital is not None: file_name = os.path.basename(args.sign) f = open(u.path_archivos + "sign_" + file_name, "wb") f.write(firma_digital + mensaje) f.close() except FileNotFoundError: print("El archivo no existe") # Encripta y frima un archivo para un destinatario y lo guarda en path_archivos elif args.enc_sign: if args.dest_id: try:
def sign(self): return crypto.encode_base64(crypto.sign(self._hashable_representation()))