def gen_privatekey(self): """ Generate new Private key. :return: None """ self.private_key = keys.gen_private_key(secp256k1)
def fast_ecdsa(count, loop): private_key = keys.gen_private_key(curve.P256) public_key = keys.get_public_key(private_key, curve.P256) # standard signature, returns two integers with open("message.txt", "rb") as f: m = f.read() time_list_sign = [] for l in range(loop): start = time.time() for c in range(count): r, s = ecdsa.sign(m, private_key) end = time.time() - start # print("["+str(l)+"th fast_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature") time_list_sign.append(end) ave_sign = numpy.mean(numpy.array(time_list_sign)) time_list_vrfy = [] for l in range(loop): start = time.time() for c in range(count): valid = ecdsa.verify((r, s), m, public_key) end = time.time() - start # print("["+str(l)+"th fast_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature") time_list_vrfy.append(end) ave_vrfy = numpy.mean(numpy.array(time_list_vrfy)) print("fast_ecdsa:sign average second is " + str(ave_sign) + "/" + str(count) + " signature") print("fast_ecdsa:vrfy average second is " + str(ave_vrfy) + "/" + str(count) + " signature") return time_list_sign, time_list_vrfy
def generate_private_key(): """ Generate a random 32-byte hex integer which serves as a randomly generated Bitcoin private key. Average Time: 0.0000061659 seconds """ return keys.gen_private_key(curve.secp256k1)
def generate_wallet(): """ Generate wallet key pair and encode public_key to base58check format :return: Accurately function returns private_key corresponded with wallet_address """ ###256b Private key generation priv_key = keys.gen_private_key(curve.P256) ###Change private key to hex priv_key_hex = hex(priv_key) ###Change private key from hex to dec #priv_key_from_hex = int(f"{priv_key_hex}", 16) # Get public key from private key as point pub_key = keys.get_public_key(priv_key, curve.P256) # Public key (K) as 128bit string str(x)+str(y) pub_key_128 = f"{format(pub_key.x, 'x')}" + f"{format(pub_key.y, 'x')}" # SHA256(K) - binary pub_key_hash_bin = hashlib.sha256(pub_key_128.encode()).digest() # RIPEMD160(SHA256(K)) pub_key_hash_ripemd = hashlib.new('ripemd160', pub_key_hash_bin).digest() # Base58Check address pub_key_base58 = base58.b58encode_check(pub_key_hash_ripemd) # Add 'B' as network sign wallet_address = "B" + str(pub_key_base58) key_pair = [wallet_address, priv_key_hex] return key_pair
def sign(m): #generate public key & private key myCurve = curve.secp256k1 private_key = keys.gen_private_key(myCurve) public_key = keys.get_public_key(private_key, myCurve) #print("this is the point:", public_key ) #print("this is th public key:", public_key) #print("this is th private key:", private_key) #generate signature k = random.randint(1, 100) n = myCurve.q d = private_key G = myCurve.G print("this is n:", n) x1y1 = k * G r = pow(x1y1.x, 1, n) z = int.from_bytes((hashlib.sha256(m.encode('utf-8')).digest()), 'big') s = modinv(k, n) * (z + r * d) % n #r = 0 #s = 0 return (public_key, [r, s])
def verify(pub_key, data, signature, hashfunc=sha256, curve=curve.P256, sign_fmt='DER', sign_size=32, pub_key_fmt='RAW'): if pub_key_fmt == 'RAW': pub_key_encoded = pub_key.encode() elif pub_key_fmt == '04': pub_key_encoded = pub_key[2:].encode() else: raise UnknownPublicKeyFormatError("fmt: '%s'" % sign_fmt) x, y = split_str_to_halves(pub_key_encoded) x, y = int(x, 16), int(y, 16) pub_key_point = Point(x, y, curve=curve) if sign_fmt in ['RAW', 'DER']: r, s = decode_sig(bytes.fromhex(signature), fmt=sign_fmt) else: raise UnknownSignatureFormatError("fmt: '%s'" % sign_fmt) priv_key = keys.gen_private_key(curve) valid = ecdsa.verify((r, s), data, pub_key_point, curve=curve, hashfunc=hashfunc) return valid
def generate_keypairs(): try: private_key = keys.gen_private_key(ccurve) public_key = keys.get_public_key(private_key, ccurve) return private_key, public_key except ecdsa.EcdsaError as encode_err: print("Error when generating key pairs: {0}".format(encode_err)) raise
def gen_keypair(curve=curve.P256, hashfunc=sha256, pub_key_fmt='RAW'): if pub_key_fmt in ['RAW', '04']: priv_key = keys.gen_private_key(curve=curve) pub_key = keys.get_public_key(priv_key, curve=curve) return int_to_hex_str(priv_key), point_to_hex_str(pub_key, fmt=pub_key_fmt) else: raise UnknownPublicKeyFormatError("fmt: '%s'" % fmt)
def new_keypair(self): """ 生成公私钥的键值对""" priv_key = keys.gen_private_key(curve.P256) pub_key = keys.get_public_key(priv_key, curve.P256) pub_key = "".join([str(pub_key.x), str(pub_key.y)]) return priv_key, pub_key
def generate_bn_config(i, epoch_time, reg_difficulty): return { 'host': '0.0.0.0', 'port': 30000 + i, 'private_key': keys.gen_private_key(curve.secp256k1), 'id': 30000 + i, 'log_level': 1, 'epoch_timeout': epoch_time, 'min_difficulty': reg_difficulty }
def new_keypair(self): priv_key = keys.gen_private_key(curve.P256) pub_key = keys.get_public_key(priv_key, curve.P256) pub_key = "".join([str(pub_key.x), str(pub_key.y)]) self.private_key = priv_key self.pub_key = pub_key return priv_key, pub_key
def generate_peer_config(i: int, bns, byzantine: bool, altruistic: bool, reg_number: int, mean_lvl_byz, std_lvl_byz): return { 'host': '0.0.0.0', 'port': 10000 + i, 'private_key': keys.gen_private_key(curve.secp256k1), 'bn_nodes': get_bns(bns, reg_number), 'id': 10000 + i, 'log_level': 1, 'byzantine': get_level_of_byz(byzantine, mean_lvl_byz, std_lvl_byz), 'altruistic': altruistic, }
def keyGen(username, type): privateKeyFile = username + '_privkey.pem' publicKeyFile = username + '_pubkey.pem' privateKey = keys.gen_private_key(curve.P256) publicKey = keys.get_public_key(privateKey, curve.P256) keys.export_key(privateKey, curve=curve.P256, filepath="keys/" + type + "Key/" + privateKeyFile) keys.export_key(publicKey, curve=curve.P256, filepath="keys/" + type + "Key/" + publicKeyFile) return True
def sign(m): #generate public key #Your code here private_key = keys.gen_private_key(curve.secp256k1) public_key = keys.get_public_key(private_key, curve.secp256k1) #generate signature #Your code here r, s = ecdsa.sign(m,private_key,curve=curve.secp256k1,hashfunc=sha256) assert isinstance( public_key, point.Point ) assert isinstance( r, int ) assert isinstance( s, int ) return( public_key, [r,s] )
def generate_iCloud_keypair(): """ When Bob sets up Find My for the first time and checks the "enable offline discovery" box, Find My generates an EC P-224 private encryption key pair. Returns: Tuple of (privateKey, publicKey) """ # Generate a private key using the P-224 curve. privateKey = keys.gen_private_key(curve.P224) # Generate the public key corresponding to the private key we just generated. publicKey = keys.get_public_key(privateKey, curve.P224) return (privateKey, publicKey)
def make_keys(self): #self.session_private=0x2E38AFE3D563398E5962D2CDEA7FE16D3CFEA36656A9DEC412C648EE3A232D21 self.session_private = gen_private_key(P256) self.session_public = get_public_key(self.session_private, P256) pre_master_secret = self.session_private*self.ecdh_q pre_master_secret = pre_master_secret.x pre_master_secret = to_bytes(pre_master_secret)[::-1] seed = self.client_random + self.server_random self.master_secret = prf(pre_master_secret, b'master secret'+seed, 0x30) key_block = prf(self.master_secret, b'key expansion'+seed, 0x120) self.sign_key = key_block[0x00:0x20] self.validation_key = key_block[0x20:0x20+0x20] self.encryption_key = key_block[0x40:0x40+0x20] self.decryption_key = key_block[0x60:0x60+0x20]
def init_flash(): assert_status(usb.cmd(reset_blob)) client_private = gen_private_key(P256) client_public = get_public_key(client_private, P256) partition_flash(flash_layout_hardcoded, client_public) rsp = usb.cmd(unhex('01')) assert_status(rsp) # ^ get device info, contains firmware version which is needed to lookup pubkey for server cert validation rsp = usb.cmd(unhex('50')) assert_status(rsp) flush_changes() rsp = rsp[2:] l, = unpack('<L', rsp[:4]) if len(rsp) != l: raise Exception('Length mismatch') zeroes, rsp = rsp[4:-400], rsp[-400:] if zeroes != b'\0' * len(zeroes): raise Exception('Expected zeroes') tls.handle_ecdh(rsp) tls.handle_priv(encrypt_key(client_private, client_public)) tls.open() # Wipe newly created partitions clean erase_flash(1) erase_flash(2) erase_flash(5) erase_flash(6) erase_flash(4) # Persist certs and keys on cert partition. write_flash(1, 0, tls.makeTlsFlash()) # Reboot reboot()
def __init__(self, pub_key: Optional[str] = None, priv_key: Optional[int] = None): if priv_key is None: keys = get_wallet_from_db(PORT) if keys: self.private_key, self.public_key = keys logger.info("Wallet: Restoring Existing Wallet") return self.private_key = keys.gen_private_key(curve.P256) self.public_key = Wallet.gen_public_key(self.private_key) logger.info("Wallet: Creating new Wallet") logger.info(self) add_wallet_to_db(PORT, self) elif pub_key is None: self.private_key = priv_key self.public_key = Wallet.gen_public_key(priv_key) else: self.public_key = pub_key self.private_key = priv_key
def generate_private_key(self): private_key = keys.gen_private_key(curve.secp256k1) return private_key
#!/usr/bin/env python3 from blockchain import Blockchain, Transaction from fastecdsa import curve, ecdsa, keys # Your private key goes here priv_key = keys.gen_private_key(curve.secp256k1) # From that we can calculate your public key(which doubles as your wallet address) pub_key = keys.get_public_key(priv_key, curve.secp256k1) myWalletAddress = hex(int(str(pub_key.x) + str(pub_key.y))) # Create new instance of Blockchain class print('Initialize coin') rebelCoin = Blockchain() # Create a transaction & sign it with your key print('1st trans') tx1 = Transaction(myWalletAddress, '123456789', 100) tx1.signTransaction(priv_key) # These try/except blocks are neccessary for now due to a bug i have where # there's either an ecdsa error or a key error, but reruning fixes it try: try: rebelCoin.addTransaction(tx1) except ecdsa.EcdsaError: rebelCoin.addTransaction(tx1) except: rebelCoin.addTransaction(tx1) print() # Mine block
from fastecdsa import keys, curve, ecdsa #generating the private key over secp224k1 curve private_key = keys.gen_private_key(curve=curve.secp224k1) #get the public key from the corresponding private key public_key = keys.get_public_key(private_key, curve=curve.secp224k1) msg = "Sign this message with secp224k1" r, s = ecdsa.sign(msg, private_key, curve.secp224k1) print(ecdsa.verify((r, s), msg, public_key, curve.secp224k1))
def get_new_priv_key() -> str: ''' Returns a random private key in hex format ''' return '{:x}'.format(keys.gen_private_key(curve.P256))
h = hashlib.sha256() def file_hash(filename): with open(filename, 'rb', buffering=0) as f: for b in iter(lambda: f.read(128 * 1024), b''): h.update(b) return h.hexdigest() file_to_hash = file_hash('program.py.enc') file_data_to_hash = file_hash('data.txt.enc') file_pubKey = "Key/public_key" private_key = keys.gen_private_key(curve.P256) public_key = keys.get_public_key(private_key, curve.P256) with open(file_pubKey, 'wb') as pub: publicKey = pickle.Pickler(pub) publicKey.dump(public_key) r, s = ecdsa.sign(file_to_hash, private_key) with open('Key/rFile', 'wb') as rVariable: rPickle = pickle.Pickler(rVariable) rPickle.dump(r) with open('Key/sFile', 'wb') as sVariable: sPickle = pickle.Pickler(sVariable) sPickle.dump(s)
def __init__(self): self.sec_key = keys.gen_private_key(curve.P256) self.pub_key = keys.get_public_key(self.sec_key, curve.P256) self.v = 0
def gen_private_key() -> int: """Generate a private key.""" return keys.gen_private_key(CURVE)
def gen_private_key(self): return keys.gen_private_key(curve.P256)
def generate_private_key(): """ Return randomly generated private key in hex """ return keys.gen_private_key(curve.secp256k1)
def create() -> 'PrivateKey': a = keys.gen_private_key(curve) b = keys.gen_private_key(curve) return PrivateKey(a, b)
def createPrivKey(self): priv_key = keys.gen_private_key(curve.P256) return priv_key
def __init__(self): self.clave_privada = keys.gen_private_key(curve.P256) self.clave_publica = keys.get_public_key(self.clave_privada, curve.P256)