def generate_keys(self, save=False, filen='default_key'): """ Generate new Private and Public key pair. (optional) save keys in a pem file :param save: (optional) False to not save the new generated private/public key pair, True to save them :type save: Boolean :param filen: (optional) is the pem file name of key to load :type filen: str :return: None """ self.private_key, self.public_key = keys.gen_keypair(secp256k1) if save: keys.export_key(self.private_key, curve=secp256k1, filepath=self.path + 'cryp/.private/' + filen + 'prv.pem') keys.export_key(self.public_key, curve=secp256k1, filepath=self.path + 'cryp/public/' + filen + 'pub.pem')
def recordTimeECC(sizes, message): """ This function documents the times taken to generate the key, encrypt, and decrypt using the ECC cryptosystem Inputs: sizes: ECC key sizes message: message to encrypt Outputs: keyTime, encryptTime, decryptTime: times taken to do task """ keyTime, encryptTime, decryptTime = [], [], [] for size in sizes: print("Starting Size: ", size) startK = time.time() priv_key, pub_key = keys.gen_keypair(size) endK = time.time() keyTime.append((endK - startK)) startE = time.time() (r, s) = ecdsa.sign(message, priv_key, size) endE = time.time() encryptTime.append((endE - startE)) startD = time.time() ecdsa.verify((r, s), message, pub_key, size) endD = time.time() decryptTime.append((endD - startD)) return keyTime, encryptTime, decryptTime
def __init__(self, district, vid): """voter has a uniquely identifying number called a vid""" private_key, public_key = keys.gen_keypair(curve.P256) self.public_key = public_key self.district = district self.vid = vid voter_private_keys[vid] = private_key
def __init__(self): """ Constructor """ self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1) pub_key_tmp = hex(self.public_key.x << 256 | self.public_key.y).encode(encoding="utf-8") self.address = hashlib.sha256(pub_key_tmp).hexdigest()
def sign(m): #generate public key private_key, public_key = gen_keypair(secp256k1) #generate signature r, s = ecdsa.sign(m, private_key, curve=secp256k1, hashfunc=sha256) return (public_key, [r, s])
def __init__(self, pem=None): if pem is None: self._key, self._pubkey = fe_keys.gen_keypair(self.CURVE) return self._key, self._pubkey = fe_pem.PEMEncoder.decode_private_key( pem.strip()) if self._pubkey is None: self._pubkey = fe_keys.get_public_key(self._key, self.CURVE)
def sign_transaction(self): """ Sign transaction with private key """ private_key = keys.gen_keypair(curve.P256) signer = PKCS1_v1_5.new(private_key) h = SHA.new(str(self.to_dict()).encode('utf8')) return binascii.hexlify(signer.sign(h)).decode('ascii')
def __init__(self, Scrooge): # MUST USE secp256k1 curve from fastecdsa self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1) # create the address using public key, and bitwise operation, may need hex(value).hexdigest() self.address = hashlib.sha256( hex(self.public_key.x << 256 | self.public_key.y).encode()).hexdigest()
def generate_keypair(self): priv_key, pub_key = keys.gen_keypair(curve.secp256k1) if (pub_key.y % 2): compressed_pub_key = '03' + str(hex(pub_key.x))[2:] else: compressed_pub_key = '02' + str(hex(pub_key.x))[2:] self.keypairs[compressed_pub_key] = priv_key self.uncompressed_keys[str(hex(pub_key.x))] = int(pub_key.y) return compressed_pub_key
def generate_key_pair(self): pvt, pub = gen_keypair(curve.secp256k1) export_key(pvt, curve=curve.secp256k1, filepath='/home/zatosh/keys/secp256k1.key') export_key(pub, curve=curve.secp256k1, filepath='/home/zatosh/keys/secp256k1.pub') return True
def digital_signature(curve, message): sk, pk = keys.gen_keypair(curve) # hash message and sign r, s = ecdsa.sign(message, sk, hashfunc=sha256) # verify signature valid = ecdsa.verify((r, s), message, pk, hashfunc=sha256) return valid
def generateByteKeys(): priv_key, pub_key = gen_keypair(fast_curve.secp256k1) curve = ecdsa.curves.SECP256k1.curve order = ecdsa.curves.SECP256k1.order pyec_point = ecdsa.ellipticcurve.Point(curve, pub_key.x, pub_key.y, order) pyec_publicKey = ecdsa.keys.VerifyingKey.from_public_point(pyec_point, ecdsa.curves.SECP256k1) pyec_privateKey = ecdsa.keys.SigningKey.from_secret_exponent(priv_key, ecdsa.curves.SECP256k1) vk = pyec_publicKey.to_string() sk = pyec_privateKey.to_string() return vk, sk
def main(): node1Key, node1Address = keys.gen_keypair(curve.P256) node2Key, node2Address = keys.gen_keypair(curve.P256) dlt = Blockchain() tx1 = Transaction(None, node1Address, 'sheep', 50) dlt.addTransactions(tx1) tx2 = Transaction(node1Address, node2Address, 'sheep', 10) tx2.signTransaction((node1Key, node1Address)) dlt.addTransactions(tx2) print("Registering transactions to blockchain.....") dlt.mineRemainingTransactions() print(dlt.getBalanceOfNode(node1Address, "sheep")) print(dlt.getBalanceOfNode(node2Address, "sheep")) print(dlt.displayChain())
def __init__(self): # MUST USE secp256k1 curve from fastecdsa self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1) # create the address using public key, and bitwise operation, may need hex(value).hexdigest() self.address = hashlib.sha256(hex(self.public_key.x << 256 | self.public_key.y).encode()).hexdigest() # list of all the blocks self.chain = [] # list of all the current transactions self.current_transactions = []
def generate_wallet(): """ Generate Veo wallet :return: address, private_key, passphrase """ private_key_raw, public_key = keys.gen_keypair(curve.secp256k1) private_key = keys.hexlify(int_to_string(private_key_raw)) address = base64.b64encode(b'\x04' + int_to_string(public_key.x) + int_to_string(public_key.y)) private_key = private_key.decode("utf-8") passphrase = private_key_raw address = address.decode("utf-8") return address, private_key, passphrase
def test_generate_and_parse_pem(self): d, Q = gen_keypair(P256) export_key(d, curve=P256, filepath='p256.key') export_key(Q, curve=P256, filepath='p256.pub') parsed_d, parsed_Q = import_key('p256.key') self.assertEqual(parsed_d, d) self.assertEqual(parsed_Q, Q) parsed_d, parsed_Q = import_key('p256.pub') self.assertTrue(parsed_d is None) self.assertEqual(parsed_Q, Q) remove('p256.key') remove('p256.pub')
def generate_secp256r1_key_pairs(save_path): """Generate the key pairs of secp256r1 :param str save_path: The save file path of private key :rtype:tuple :return: The hex string of public key """ private_key, public_key = keys.gen_keypair(curve.P256) keys.export_key(private_key, curve.P256, filepath=save_path) x = str(hex(public_key.x))[2:] y = str(hex(public_key.y))[2:] if len(x) < 64: x = '0' * (64 - len(x)) + x if len(y) < 64: y = '0' * (64 - len(y)) + y public_key = '0x' + x + y return public_key
def __init__(self): """ Constructor """ # generate a secret key (<class 'int'>) and a corresponding public key # (<class 'fastecdsa.point.Point'> which is an integer pair), # using the Bitcoin elliptic curve secp256k1 (fastecdsa.curve.secp256k1) self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1) # create the address, or a hash of a public key, using SHA-256 pub_key_tmp = hex(self.public_key.x << 256 | self.public_key.y).encode(encoding="utf-8") self.address = hashlib.sha256(pub_key_tmp).hexdigest() # list of all the blocks self.chain = [] # list of all the current transactions (a ledger) self.current_transactions = []
def __init__(self, env, iden, conn_count): self.env = env self.iden = iden self.out_links = [] self.conn_count = conn_count self.message_sequence_id = 0 self.recieved_id_cache = list() #TODO self.stake = np.random.randint(1, 51) self.sk, self.pk = keys.gen_keypair(curve.P256) self.input_buffer = dict() self.count_value = dict() self.blockchain = list() self.blockchain.append(prev_block) self.prev_block = prev_block
def setUp(self): self.cryp = Cryp() self.private_key, self.public_key = keys.gen_keypair(secp256k1)
def gerar_chave(): # Cria um novo par de chaves (privada, pública) privateKey, publicKey = keys.gen_keypair(curve.secp256k1) return privateKey, publicKey
def new_wallet(): random_gen = Crypto.Random.new().read private_key = keys.gen_keypair(curve.P256) public_key = private_key.publickey() response = { 'private_key': binascii.hexlify(private_key.exportKey(format='DER')).decode('ascii'), 'public_key': binascii.hexlify(public_key.exportKey(format='DER')).decode('ascii') } return jsonify(response), 200 @app.route('/generate/transaction', methods=['POST']) def generate_transaction(): sender_address = request.form['sender_address'] sender_private_key = request.form['sender_private_key'] recipient_address = request.form['recipient_address'] value = request.form['amount'] transaction = Transaction(sender_address, sender_private_key, recipient_address, value) response = {'transaction': transaction.to_dict(), 'signature': transaction.sign_transaction()} return jsonify(response), 200 class Blockchain: def __init__(self): self.transactions = [] self.chain = [] self.nodes = set() #Generate random number to be used as node_id self.node_id = str(uuid4()).replace('-', '') #Create genesis block self.create_block(0, '00') def register_node(self, node_url): """ Add a new node to the list of nodes """ ... def verify_transaction_signature(self, sender_address, signature, transaction): """ Check that the provided signature corresponds to transaction signed by the public key (sender_address) """ ... def submit_transaction(self, sender_address, recipient_address, value, signature): """ Add a transaction to transactions array if the signature verified """ ... def create_block(self, nonce, previous_hash): """ Add a block of transactions to the blockchain """ ... def hash(self, block): """ Create a SHA-256 hash of a block """ ... def proof_of_work(self): """ Proof of work algorithm """ ... def valid_proof(self, transactions, last_hash, nonce, difficulty=MINING_DIFFICULTY): """ Check if a hash value satisfies the mining conditions. This function is used within the proof_of_work function. """ ... def valid_chain(self, chain): """ check if a bockchain is valid """ ... def resolve_conflicts(self): """ Resolve conflicts between blockchain's nodes by replacing our chain with the longest one in the network. """ app = Flask(__name__) CORS(app) blockchain = Blockchain() @app.route('/') def index(): return render_template('./index.html') @app.route('/configure') def configure(): return render_template('./configure.html') @app.route('/transactions/new', methods=['POST']) def new_transaction(): values = request.form # Check that the required fields are in the POST'ed data required = ['sender_address', 'recipient_address', 'amount', 'signature'] if not all(k in values for k in required): return 'Missing values', 400 # Create a new Transaction transaction_result = blockchain.submit_transaction(values['sender_address'], values['recipient_address'], values['amount'], values['signature']) if transaction_result == False: response = {'message': 'Invalid Transaction!'} return jsonify(response), 406 else: response = {'message': 'Transaction will be added to Block '+ str(transaction_result)} return jsonify(response), 201 @app.route('/transactions/get', methods=['GET']) def get_transactions(): #Get transactions from transactions pool transactions = blockchain.transactions response = {'transactions': transactions} return jsonify(response), 200 @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain), } return jsonify(response), 200 @app.route('/mine', methods=['GET']) def mine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.chain[-1] nonce = blockchain.proof_of_work() # We must receive a reward for finding the proof. blockchain.submit_transaction(sender_address=MINING_SENDER, recipient_address=blockchain.node_id, value=MINING_REWARD, signature="") # Forge the new Block by adding it to the chain previous_hash = blockchain.hash(last_block) block = blockchain.create_block(nonce, previous_hash) response = { 'message': "New Block Forged", 'block_number': block['block_number'], 'transactions': block['transactions'], 'nonce': block['nonce'], 'previous_hash': block['previous_hash'], } return jsonify(response), 200 @app.route('/nodes/register', methods=['POST']) def register_nodes(): values = request.form nodes = values.get('nodes').replace(" ", "").split(',') if nodes is None: return "Error: Please supply a valid list of nodes", 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'New nodes have been added', 'total_nodes': [node for node in blockchain.nodes], } return jsonify(response), 201 @app.route('/nodes/resolve', methods=['GET']) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'Our chain was replaced', 'new_chain': blockchain.chain } else: response = { 'message': 'Our chain is authoritative', 'chain': blockchain.chain } return jsonify(response), 200 @app.route('/nodes/get', methods=['GET']) def get_nodes(): nodes = list(blockchain.nodes) response = {'nodes': nodes} return jsonify(response), 200
def main(): """ pip install fastecdsa Refer following links for more curves and parameters - https://pypi.org/project/fastecdsa/ - https://pypi.org/project/fastecdsa/ - https://github.com/AntonKueltz/fastecdsa """ # INFO or DEBUG logging.basicConfig(level=logging.INFO) # Input file filename = sys.argv[1] # EC parameters param_curve = curve.secp256k1 # bitcoin curve param_hash = hashlib.sha256 # Timing variables key_time = 0 sign_time = 0 verify_time = 0 logging.info("Started Fast ECDSA with curve: %s, sha: %s", param_curve, str(param_hash.__name__)) with open(filename, "r") as f: # skip file reading time as well start = time.time() for m in f: logging.debug(m) # This is no longer required as message will be hashed during ecdsa.sign() # m = hashlib.sha256(m.encode()).hexdigest() # logging.debug(m) start_keygen = time.time() private_key, public_key = keys.gen_keypair(param_curve) key_time += time.time() - start_keygen start_sign = time.time() r, s = ecdsa.sign(m, private_key, curve=param_curve, hashfunc=param_hash) sign_time += time.time() - start_sign start_verify = time.time() valid = ecdsa.verify((r, s), m, public_key, curve=param_curve, hashfunc=param_hash) logging.debug("Verified: %s" % valid) verify_time += time.time() - start_verify sum_time = key_time + sign_time + verify_time logging.info("Total time cost for generating key is: " + str(key_time) + " s") logging.info("Total time cost for signing the message is: " + str(sign_time) + " s") logging.info("Total time cost for verifying the message is: " + str(verify_time) + " s") logging.info( "Total time cost for key generating, message signing and verifying: " + str(sum_time) + " s") logging.info("Total time cost for system time: " + str(time.time() - start) + " s")
def genkey(self): d, Q = keys.gen_keypair(curve.secp256k1) self.keys.append((d,Q))
def KeyGen(self): return keys.gen_keypair(curve.secp256k1)
def generate_new_keypair(curve=BASE_CURVE): priv_key, pub_key = keys.gen_keypair(curve) return KeyPair(pub_key, priv_key, curve)
def main(): # dict - defined using {key:value, key:value, ...} or dict[key] = value # they are used in this code for blocks, transactions, and receivers # can be interated through using dict.items() # https://docs.python.org/3/tutorial/datastructures.html#dictionaries # lists -defined using [item, item, item] or list.append(item) as well as other ways # used to hold lists of blocks aka the blockchain # https://docs.python.org/3/tutorial/datastructures.html#more-on-lists # fastecdsa - https://pypi.org/project/fastecdsa/ # hashlib - https://docs.python.org/3/library/hashlib.html # json - https://docs.python.org/3/library/json.html # Example of how the code will be run print("[+] Initializing Script...") sleep(0.5) Scrooge = ScroogeCoin() users = [User() for i in range(10)] print("[+] Users 0-9 are created\n") sleep(.5) Scrooge.create_coins({ users[0].address: 10, users[1].address: 20, users[3].address: 50 }) Scrooge.mine() tx_num = 0 block_num = 1 print("[+] 10 coins are created for user[0]\n" + "[+] 20 coins are created for user[1]\n" + "[+] 50 coins are created for user[3]\n") sleep(1) while True: sig_check = False if block_num > 1: show_bl = True more_options = int( input( "Enter 2 to show balance, 3 to show block, 4 to send an invalid signature, or 5 to continue: " )) if more_options == 2: show_bl = False what_balance = int( input( "Enter the user number's balance you would like to see: " )) print("\n") Scrooge.show_user_balance(users[what_balance].address, True) elif more_options == 3: what_block = int( input("Enter the block number you would like to see: ")) print("\n") Scrooge.show_block(what_block) elif more_options == 5: pass elif more_options == 4: sig_check = True show_bl = False print( "[+] Generating invalid public_key to send to next transaction..." ) sleep(1) print( "Done! The next transaction will have an invalid signature" ) if show_bl: print("You are now building") print("\nBlock number: ", block_num) print("Transaction Number: ", tx_num, "\n") else: pass sender = int( input("Enter the user number who will send a transaction: ")) if sender >= 10 or sender < 0: sender = int(input("Please enter a user number between 0 and 9: ")) send_amt = int(input("Enter the coin amount being sent: ")) receiver = int( input("Enter the user number who will recieve this transaction: ")) if receiver >= 10 or receiver < 0: receiver = int( input("Please enter a user number between 0 and 9: ")) remainer = int( input("Enter the coin amount the sender should have left: ")) print("\n") sender_locations = Scrooge.get_user_tx_positions(users[sender].address) pub_key = users[sender].public_key if sig_check: # Generate brand new keypair to invalidate transaction priv_key, pub_key = keys.gen_keypair(curve.secp256k1) input_tx = users[sender].send_tx( { users[receiver].address: send_amt, users[sender].address: remainer }, sender_locations) Scrooge.add_tx(input_tx, pub_key) mine_tx = int( input( "Enter 0 to mine, 1 to add another transaction to the block, or -1 to quit: " )) more_options = 0 print("\n") if mine_tx == 0: Scrooge.mine() print("[+] Block number " + str(block_num) + " is added to the blockchain \n") block_num += 1 tx_num = 0 elif mine_tx == 1: tx_num += 1 elif mine_tx == -1: print("Goodbye!") break
def generate_key_pair(): """ Returns fastecdsa public and private keys (fastecdsa.privKey, fastecdsa.pubKey). """ private_key, public_key = keys.gen_keypair(curve.P256) return private_key, public_key
group.add_argument("-d", "--decrypt", action="store_true") group.add_argument("-e", "--encrypt", action="store_true") # for the file parser.add_argument("filename", type=str, help="file") args = parser.parse_args() with open(args.filename) as file: text = file.read() #creates a random nonce from the system nonce = os.urandom(12) #generates both a private and a public key key, pub_key = keys.gen_keypair(curve.P256) #converts that key intro a string and chops it to 32 characters key = str(key) key = key[0:32] #encodes the key encoded = str.encode(key) #uses ChaCha20Poly1305 algorithm on it cip = ChaCha20Poly1305(encoded) #encrypts and saves in cipthertext variable ciphertext = cip.encrypt(nonce, str.encode(text).strip())
def gen_key(): return keys.gen_keypair(curve.P256)