def get_public_key(private_key): if sys.version_info.major > 2: return (bytes.fromhex("04") + SigningKey.from_string( private_key, curve=SECP256k1).verifying_key.to_string()) else: return (bytearray.fromhex("04") + SigningKey.from_string( private_key, curve=SECP256k1).verifying_key.to_string())
def from_string(key_str: str, curve='r1'): assert len(key_str) == 64 if curve == 'r1': _signing_key = EcdsaSigningKey.from_string(bytes.fromhex(key_str), curve=curves.NIST256p) else: _signing_key = EcdsaSigningKey.from_string(bytes.fromhex(key_str), curve=curves.SECP256k1) return PrivateKey(_signing_key, curve)
def get_public_key(key): # this returns the concatenated x and y coordinates for the supplied private address # the prepended 04 is used to signify that it's uncompressed if sys.version_info.major > 2: return bytes.fromhex("04") + SigningKey.from_string( key, curve=SECP256k1).verifying_key.to_string() else: return (bytearray.fromhex("04") + SigningKey.from_string( key, curve=SECP256k1).verifying_key.to_string())
def get_public_key(private_key): # this returns the concatenated x and y coordinates for the supplied private address # the prepended 04 is used to signify that it's uncompressed print( '测试', binascii.hexlify( SigningKey.from_string(private_key, curve=SECP256k1).verifying_key.to_string())) return (bytearray.fromhex("04") + SigningKey.from_string( private_key, curve=SECP256k1).verifying_key.to_string())
def create_from_private_key(self, private_key): if not isinstance(private_key, SigningKey): if isinstance(private_key, bytes): private_key = SigningKey.from_string(private_key, curve=self.curve, hashfunc=hashlib.sha256) elif isinstance(private_key, str): private_key = base58.b58decode(private_key) private_key = SigningKey.from_string(private_key, curve=self.curve, hashfunc=hashlib.sha256) else: raise Exception("Unrecognized Private Key format") public_key = private_key.verifying_key address = self.create_address(public_key) return Account(address=address, public_key=public_key, private_key=private_key, key_type=self.key_type)
def signTransaction(self, signingKey): if SigningKey.from_string( bytearray.fromhex(signingKey), curve=SECP256k1).verifying_key != VerifyingKey.from_string( bytearray.fromhex(self.fromAddress), curve=SECP256k1): print("You cannot sign transactions for other wallets") exit() hashTrans = bytearray.fromhex(self.calculateHash()) sig = SigningKey.from_string(bytearray.fromhex(signingKey), curve=SECP256k1).sign(hashTrans) self.signature = sig.hex()
def new_transaction(self, ins, outs, sk, coinbase=False): """ Creates a new transaction to go into the next mined block. IMPORTANT NOTE: transaction inputs MUST include b58 encoded public keys or later signatures will NOT verify. :param ins: <dict> {tx_hash, addr, output_index, amount} Source(s) of funds. :param outs: <dict> {amount, addr} Recipient(s) of funds. :param sk: <SigningKey or str> The secret key used by payee to sign transaction. Must be the other half of the keypair used in the inputs to the transaction. :return: <int> The index of the Block that will hold this transaction """ if coinbase: tx = {'ins': [], 'outs': [{'amount': self.reward, 'addr': self.key_to_addr(self.vk)}], # need to fix this 'time': time(), 'coinbase': True } else: tx = {'ins': [i for i in ins], 'outs': [o for o in outs], 'time': time(), # Basically a nonce so you don't get the same transaction twice. 'coinbase': False } if self.valid_tx(tx) != True: # Return the error code. return self.valid_tx(tx) # If it's valid, add the hash and put it in the current_txs pool. tx['hash'] = self.hash(tx) if coinbase: # Node will sign coinbase transaction with its own secret key. # Can't verify this because there's no associated public key to check. tx = self.sign_tx(tx, SigningKey.from_string(self.sk)) self.current_transactions = [tx] + self.current_transactions else: if type(sk) is str: # assume base58 encoding here. sk = self.decode_sk(sk) elif type(sk) is bytes: # assume bytestring here. sk = SigningKey.from_string(sk) tx = self.sign_tx(tx, sk) if not self.verify_signature(tx): return 'Signature not valid.', 400 self.current_transactions.append(tx) self.msgr.publish_message(Message.NEW_TX, json.dumps(tx)) self.update_utxo_pool(tx) if len(self.chain) == 0: return 0 else: return self.last_block['index'] + 1
def _compress_public_key(self, private_key): """ Compute ECDSA compressed public key :param private_key: private key (bytes) :return: compressed public key (string) """ order = SigningKey.from_string( private_key, curve=SECP256k1).curve.generator.order() point = SigningKey.from_string( private_key, curve=SECP256k1).get_verifying_key().pubkey.point return hexlify( chr(2 + (point.y() & 1)).encode() + number_to_string(point.x(), order))
def sign_message(privkey, message): sk = SigningKey.from_string(binascii.unhexlify(privkey), curve=SECP256k1) vk = sk.get_verifying_key() pubkey_sig = binascii.hexlify(vk.to_string()).decode('utf-8') sig = binascii.hexlify(sk.sign(bytes(message, 'ascii'))).decode('utf-8') sig = binascii.hexlify(sk.sign(bytes(message, 'ascii'))).decode('utf-8') return sig, pubkey_sig
def derive_publicKey(priv_key: bytes) -> bytes: ''' Derive public key from a private key(uncompressed). Parameters ---------- priv_key: bytes The private key in bytes. Returns ------- bytes The public key(uncompressed) in bytes, which starts with 04. Raises ------ ValueError If the private key is not valid. ''' if not _is_valid_private_key(priv_key): raise ValueError('Private Key not valid.') _a = SigningKey.from_string(priv_key, curve=SECP256k1) return _a.verifying_key.to_string("uncompressed")
def get_pubkeys_from_secret(secret): # public key private_key = SigningKey.from_string(secret, curve=SECP256k1) public_key = private_key.get_verifying_key() K = public_key.to_string() K_compressed = GetPubKey(public_key.pubkey, True) return K, K_compressed
def Make_RegisterTransaction(Prikey, Redeem_script, Name, Issuer, Admin, Inputs, Index, Count, Amount=-0.00000001): ''' Name:发行的资产名 Issuer:发行者 Admin:管理员 Inputs Count:inputs Amount:发行资产总量,默认无上限-0.00000001 ''' Name = '5b7b276c616e67273a277a682d434e272c276e616d65273a27{0}277d5d'.format(name_to_hex(Name)) Amount = float_2_hex(Amount) #不需要找零 #Antcoin:f252a09a24591e8da31deec970871cc7678cb55023db049551e91f7bac28e27b Outputs = big_or_little('f252a09a24591e8da31deec970871cc7678cb55023db049551e91f7bac28e27b') + float_2_hex(Count-100) + Admin if Count > 100 else '' #暂时支持1个inputs之后再改,'00'为索引 RegisterTransaction = '4060' + hex(len(Name)/2)[2:] + Name + Amount + Issuer + Admin + '0001' + big_or_little(str(Inputs)) + '00' if Count > 100: RegisterTransaction += '0001' + Outputs else: RegisterTransaction += '0000' GetHashForSigning = big_or_little(sha256(binascii.unhexlify(RegisterTransaction)))#txid #print GetHashForSigning sk = SigningKey.from_string(binascii.unhexlify(Prikey), curve=NIST256p, hashfunc=hashlib.sha256) signature = binascii.hexlify(sk.sign(binascii.unhexlify(RegisterTransaction),hashfunc=hashlib.sha256)) return RegisterTransaction + '014140' + signature + '23' + Redeem_script
def sign_ecdsa(self, _msg_bytes, _authorPrivateKey): sk = SigningKey.from_string(_authorPrivateKey, curve=SECP256k1, hashfunc=hashlib.sha256) signature = sk.sign(_msg_bytes,sigencode=sigencode_der) return signature.hex()
def recover_pub(signkey): if not isinstance(signkey, str): raise ValueError("Sign key is not a string.") sk = SigningKey.from_string(signkey, curve=SECP256k1) pub = sk.get_verifying_key().to_string() return pub
def sign_message_hex(message, privkey): sk = SigningKey.from_string(unhexlify(privkey), curve=ecdsa.SECP256k1, hashfunc=hashlib.sha256) return hexlify( sk.sign(message.encode('utf-8'), hashfunc=hashlib.sha256)).decode('utf-8')
def __init__(self, string, soft=True): # Get Private Key private_key = NewPrivateKey(string, soft) self.printable_pk = private_key self.private_key = unhexlify(private_key.encode('ascii')) # Generate Seed seed = mnemonic.mn_encode( self.printable_pk) # TODO Create MyEther Mnemonic Seed seed.append(mnemonic.mn_checksum(seed)) self.seed = seed self.readable_seed = self.readable_seed(seed) self.readable_seed_for_terminal_app = self.readable_seed_for_terminal_app( seed) # Get Public Key self.sk = SigningKey.from_string(self.private_key, curve=SECP256k1) self.vk = self.sk.verifying_key public_key_bytes = hexlify(self.vk.to_string()) # Get Ethereum Address public_key_bytes = decode(public_key_bytes, 'hex') k = keccak.new(digest_bits=256) k.update(public_key_bytes) raw_address = k.hexdigest() self.address = "0x" + raw_address[-40:]
def import_key(self, key): WIF = key try: first_encode = b58decode(WIF) except ValueError: return 'Wrong WIF!' private_key_full = hexlify(first_encode) private_key = private_key_full[2:-8] private_key_bytes = unhexlify(private_key) try: key = SigningKey.from_string(private_key_bytes, curve=SECP256k1, hashfunc=hashlib.sha256).verifying_key except AssertionError: return 'Wrong WIF!' key_bytes = key.to_string() key_hex = codecs.encode(key_bytes, 'hex') public_key = '04' + key_hex.decode('utf-8').upper() hash160 = ripemd160(hashlib.sha256( unhexlify(public_key)).digest()).digest() publ_addr_a = b"\x00" + hash160 checksum = hashlib.sha256( hashlib.sha256(publ_addr_a).digest()).digest()[:4] publ_addr_b = b58encode(publ_addr_a + checksum) address = publ_addr_b.decode() content = private_key.decode( 'utf-8').upper() + ',' + WIF + ',' + public_key + ',' + address return content
def getAddFromPriv(pk): keccak = sha3.keccak_256() private = SigningKey.from_string(bytes().fromhex(pk), curve=SECP256k1) public = private.get_verifying_key().to_string() keccak.update(public) address = "0x{}".format(keccak.hexdigest()[24:]) return Web3.toChecksumAddress(address)
def __init__(self, seed, key="Bitcoin seed"): I = hmac.digest(b"Bitcoin seed", seed, 'sha512') I_L, I_R = I[:32], I[32:] self.m = parse256(I_L) self.M = SigningKey.from_string(I_L, curve=SECP256k1) \ .get_verifying_key().pubkey.point self.c = I_R
def derive(self, path="m"): tokens = path.split('/') if tokens[0] == "m": k = self.m c = self.c for r in tokens[1:]: if not rformat.match(r): raise self.path_error if r[-1] == "'": i = iH(int(r[:-1])) else: i = int(r) k, c = ckd_prv(k, c, i) return SigningKey.from_string(k.to_bytes(32, byteorder='big'), curve=SECP256k1) elif tokens[0] == "M": K = self.M c = self.c for r in tokens[1:]: if not rformat.match(r): raise self.path_error if r[-1] == "'": i = iH(int(r[:-1])) else: i = int(r) K, c = ckd_pub(K, c, i) return VerifyingKey.from_public_point(K, curve=SECP256k1) else: raise self.path_error
def pub(self, compressed=True): raw_pubkey = bytearray(SigningKey.from_string(self.key, curve=SECP256k1).get_verifying_key().to_string()) uncompressed = PublicKey(bytearray([0x04]) + raw_pubkey) if compressed: return PublicKey(uncompressed.compressed) else: return uncompressed
def __init__(self, string, soft=True): # Get Private Key private_key = NewPrivateKey(string, soft) self.printable_pk = private_key self.private_key = unhexlify(private_key.encode('ascii')) # Generate Seed seed = mnemonic.mn_encode(self.printable_pk) seed.append(mnemonic.mn_checksum(seed)) self.seed = seed self.readable_seed = self.readable_seed(seed) self.readable_seed_for_terminal_app = self.readable_seed_for_terminal_app( seed) # Get Public Key self.sk = SigningKey.from_string(self.private_key, curve=SECP256k1) self.vk = self.sk.verifying_key self.public_key = b"04" + hexlify(self.vk.to_string()) # Get Litecoin Address ripemd160 = new('ripemd160') ripemd160.update(sha256(unhexlify(self.public_key)).digest()) self.hashed_public_key = b"30" + hexlify(ripemd160.digest()) self.checksum = hexlify( sha256(sha256(unhexlify( self.hashed_public_key)).digest()).digest()[:4]) self.binary_addr = unhexlify(self.hashed_public_key + self.checksum) self.address = b58encode(self.binary_addr) self.public_key = str(self.public_key)[2:-1] self.address = str(self.address)[2:-1]
def submit(contract_instance, start_id, end_id): avg_e = 0 start_t = time.time() for i in range(start_id, end_id): # use bytes encoded epc as signature message. # sign the epc use a private key sk = SigningKey.from_string(open(privateKey_file, 'rb').read()) # sign and padding 48 bytes to 64 bytes to prevent extraction error sig = sk.sign(str(i + 274877906944).encode()).ljust(64, b"\x0f") time.sleep(0.01) # send transaction for adding a new review contract_instance.adduReview(int(i + 274877906944), sig, rating, content, transact={ 'from': w3.eth.accounts[0], 'gas': 1000000 }) # (timer: review submitted) avg_e = avg_e + time.time() / 2000 end_t = time.time() print( str(start_id) + " - " + str(end_id) + ": " + str(start_t) + " - " + str(end_t)) print("avg_endtime: " + str(avg_e)) print("submission rate: " + str(2000 / (end_t - start_t)))
def sign(priv, msg): sk = SigningKey.from_string(binascii.unhexlify(priv), curve=SECP256k1) public_key = sk.get_verifying_key() sig = sk.sign(bytes(msg, 'utf-8'), sigencode=ecdsa.util.sigencode_der_canonize) return (codecs.encode(sig, 'hex'), binascii.hexlify(public_key.to_string()).decode())
def load_keys(pos_filename='poswallet.json', verbose=False): """ Load the keys from wallet json file. :param pos_filename: :param verbose: boolean, print out address and pubkey :return: True or raise. """ global PUB_KEY global PRIV_KEY global ADDRESS if not os.path.exists(pos_filename): # Create new keys if none there. gen_keys_file(pos_filename) with open(pos_filename, 'r') as fp: wallet = json.load(fp) # TODO: handle encrypted wallet PRIV_KEY = SigningKey.from_string(b64decode(wallet['privkey'].encode('ascii')), curve=SECP256k1) # TODO: We could verify pubkey also, and warn if there is an error PUB_KEY = VerifyingKey.from_string(b64decode(wallet['pubkey'].encode('ascii')), curve=SECP256k1) # We recreate address rather than relying on address.txt ADDRESS = pub_key_to_addr(PUB_KEY.to_string()) assert ADDRESS == wallet['address'] if verbose: print("Loaded address ", ADDRESS) print("Loaded pubkey ", raw_to_hex(PUB_KEY.to_string())) return True
def getECDAPublicKeyWithPrefix(prefix, privateKey): signingKey = SigningKey.from_string(privateKey.decode("hex"), curve=SECP256k1) verifyingKey = signingKey.verifying_key publicKeyWithPrefix = (prefix + verifyingKey.to_string()).encode("hex") return publicKeyWithPrefix
def __init__(self, priv_key_raw, network_type, key_fmt): '''Create a Bitcoin account from private key''' self.signing_key = SigningKey.from_string(priv_key_raw, curve=SECP256k1) self.priv_key_raw = priv_key_raw self.network_type = network_type self.key_fmt = key_fmt
def checkwallet(request): data = {} prikey = request.POST.get('prikey').strip() message = b"hello" try: sk = SigningKey.from_string(bytes.fromhex(prikey), curve=SECP256k1) vk = sk.get_verifying_key() #public_key print(vk.to_string().hex()) except UnicodeDecodeError: data["response"] = "Check your wallet details" return HttpResponse(json.dumps(data), content_type="application/json") except TypeError: data["response"] = "Check your wallet details" return HttpResponse(json.dumps(data), content_type="application/json") except ValueError: data["response"] = "Check your wallet details ValueError" return HttpResponse(json.dumps(data), content_type="application/json") try: sig = sk.sign(message) test = vk.verify(sig, b"hello") # True except BadSignatureError: data["response"] = "access_denied" return HttpResponse(json.dumps(data), content_type="application/json") request.session['pubkey'] = vk.to_string().hex() request.session['prikey'] = prikey data["response"] = "access_approved" return HttpResponse(json.dumps(data), content_type="application/json")
def generate_keys(self): private_key = SigningKey.generate(curve=SECP256k1, hashfunc=hashlib.sha256) private_key = hexlify(private_key.to_string()).decode('ascii').upper() extended_key = '80' + private_key first_sha256 = hashlib.sha256(unhexlify(extended_key)).hexdigest() second_sha256 = hashlib.sha256(unhexlify(first_sha256)).hexdigest() final_key = extended_key + second_sha256[:8] WIF = b58encode(unhexlify(final_key)).decode('utf-8') private_key_bytes = unhexlify(private_key) key = SigningKey.from_string(private_key_bytes, curve=SECP256k1, hashfunc=hashlib.sha256).verifying_key key_bytes = key.to_string() key_hex = codecs.encode(key_bytes, 'hex') public_key = '04' + key_hex.decode('utf-8').upper() hash160 = ripemd160(hashlib.sha256( unhexlify(public_key)).digest()).digest() publ_addr_a = b"\x00" + hash160 checksum = hashlib.sha256( hashlib.sha256(publ_addr_a).digest()).digest()[:4] publ_addr_b = b58encode(publ_addr_a + checksum) address = publ_addr_b.decode() content = private_key + ',' + WIF + ',' + public_key + ',' + address return content
def CreateSignature(senderPrivateKey, sender, recipient, amount): senderPrivateKey.replace(' ', '') sender.replace(' ', '') recipient.replace(' ', '') amount.replace(' ', '') HashedPrivateKey = str( hashlib.sha256(senderPrivateKey.encode()).hexdigest()) PublicConfirm = Verify(senderPrivateKey) sender = SigningKey.from_string(bytes.fromhex(sender), curve=SECP256k1) s_pub_key = sender.get_verifying_key().to_string().hex() r_pub_key = recipient transaction = { 'sender': s_pub_key, 'recipient': r_pub_key, 'amount': amount, 'signature': sender.sign(f"{s_pub_key} -{amount}-> {r_pub_key}".encode()).hex() } return sender.sign(f"{s_pub_key} -{amount}-> {r_pub_key}".encode()).hex()
def run(): key = SigningKey.from_string(get_key_from_wif(settings['wif']), SECP256k1, sha256) rs = compileASM(REDEEM_SCRIPT) txs = parsetxsfile(settings['file']) for tx in txs: tx.signatures = sign_detached(tx.tx, key, rs) print(",".join(tx.signatures))
def makeTransaction(self, tx, account): """Make Transaction""" if tx.outputs == None: raise ValueError, 'Not correct Address, wrong length.' if tx.attributes == None: tx.attributes = [] coins = self.findUnSpentCoins(account.scriptHash) tx.inputs, tx.outputs = self.selectInputs(tx.outputs, coins, account, tx.systemFee) # Make transaction stream = MemoryStream() writer = BinaryWriter(stream) tx.serializeUnsigned(writer) reg_tx = stream.toArray() tx.ensureHash() txid = tx.hash # RedeenScript contract = Contract() contract.createSignatureContract(account.publicKey) Redeem_script = contract.redeemScript # Add Signature sk = SigningKey.from_string(binascii.unhexlify(account.privateKey), curve=NIST256p, hashfunc=hashlib.sha256) signature = binascii.hexlify(sk.sign(binascii.unhexlify(reg_tx),hashfunc=hashlib.sha256)) regtx = reg_tx + '014140' + signature + '23' + Redeem_script # sendRawTransaction print regtx response = self.node.sendRawTransaction(regtx) import json print response return txid
def generate_pairs(self): if os.path.isfile('key.dat'): # if key.dat exist file = open("key.dat", "rb") # open file read-only pv_key = SigningKey.from_string( file.readline(), curve=NIST256p) # get private key from the file as an object pb_key = pv_key.get_verifying_key( ) # generate public key from private key as an object file.close() # close file pv_string = pv_key.to_string() # change object type to string pb_string = pb_key.to_string() # change object type to string else: pv_key = SigningKey.generate( curve=NIST256p) # generate a new random private key pv_string = pv_key.to_string() # change object type to string pb_key = pv_key.get_verifying_key( ) # generate public key from private key as an object pb_string = pb_key.to_string() # change object type to string file = open("key.dat", "wb") # create new file called key.dat file.write(pv_string) # write into key.dat file.close() # close file self.private = pv_string self.private_decode = pv_string.hex() self.public = pb_string self.public_decode = pb_string.hex() return pv_string.hex(), pb_string.hex()
def check_for_privkey(keydir, jid, stderr): # the "anonymous ID" case if jid.startswith("anonid0-"): return None # the "old-style ID" case # FIXME: once it is possible for addons to change from old-style IDs # to new, cryptographic IDs on AMO and in Firefox, warn users that # continuing to use old-style IDs is less secure, and provide them with # instructions for changing to new IDs. if not jid.startswith("jid0-"): return None keypath = os.path.join(keydir, jid) if not os.path.isfile(keypath): msg = """\ Your package.json says our ID is: %(jid)s But I don't have a corresponding private key in: %(keypath)s If you are the original developer of this package and have recently copied the source code from a different machine to this one, you should copy the private key into the file named above. Otherwise, if you are a new developer who has made a copy of an existing package to use as a starting point, you need to remove the 'id' property from package.json, so that we can generate a new id and keypair. This will disassociate our new package from the old one. If you're collaborating on the same addon with a team, make sure at least one person on the team has the private key. In the future, you may not be able to distribute your addon without it. """ print >> stderr, msg % {"jid": jid, "keypath": keypath} return None keylines = open(keypath, "r").readlines() keydata = {} for line in keylines: line = line.strip() if line: k, v = line.split(":", 1) keydata[k.strip()] = v.strip() if "private-key" not in keydata: raise ValueError("invalid keydata: can't find 'private-key' line") sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data") from ecdsa import SigningKey, VerifyingKey, NIST256p sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p) vk = sk.get_verifying_key() jid_2 = vk_to_jid(vk) if jid_2 != jid: raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid)) vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data") vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p) if vk.to_string() != vk2.to_string(): raise ValueError("invalid keydata: public-key mismatch") return sk
def __init__(self, privkey, pubkey = None, compressed = True): self.private_key = SigningKey.from_string(privkey, SECP256k1, sha256) if (compressed): # use the compressed public key self.public_key = BlockIo.Helper.compress_pubkey(self.private_key.get_verifying_key().to_string()) else: # use the uncompressed public key self.public_key = unhexlify('04' + hexlify(self.private_key.get_verifying_key().to_string()))
def hex2key(hex_key): key_bytes = unhexlify(hex_key) if len(hex_key) == 64: return SigningKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) elif len(hex_key) == 128: return VerifyingKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) else: raise ValueError("Key in hex form is of the wrong length.")
def load_db_private_key(self): with Transaction() as tx: sql = "SELECT * FROM `ecdsa_pairs` WHERE `public_key`=?;" tx.execute(sql, (self.get_public_key(),)) rows = tx.fetchall() if not len(rows): return row = rows[0] self.private_key = self.parse_private_key(row["private_key"]) self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) self.verify_key = self.sign_key.get_verifying_key()
def __init__(self, key=None): self.secretKey = self.verifKey = None # Recuperation if key is not None: self.secretKey = SigningKey.from_string(key, curve=NIST384p) # Auto-generation else: self.secretKey = SigningKey.generate(curve=NIST384p) self.verifKey = self.secretKey.get_verifying_key()
def sign(self, msg, private_key=None): if private_key == None: sign_key = self.sign_key else: private_key = self.parse_private_key(private_key) sign_key = SigningKey.from_string(private_key, SECP256k1) if sign_key == None: raise Exception("Private key for ECDSA keypair not known.") if type(msg) == str: msg = msg.encode("ascii") return base64.b64encode(sign_key.sign(msg)).decode("utf-8")
def sign(self, msg, private_key=None): if private_key == None: sign_key = self.sign_key else: private_key = self.parse_private_key(private_key) sign_key = SigningKey.from_string(private_key, SECP256k1) if sign_key == None: raise Exception("Private key for ECDSA keypair not known.") if type(msg) == str: msg = msg.encode("ascii") return binascii.hexlify(sign_key.sign(msg, sigencode=ecdsa.util.sigencode_der, hashfunc=hashlib.sha256)).decode("utf-8")
def Make_IssueTransaction(Prikey, Redeem_script, Outputs, Txid): Nonce = random.randint(268435456, 4294967295) Nonce = hex(Nonce)[2:-1] if len(Nonce)%2==1: Nonce = '0'+Nonce value = 1 if len(Outputs)> 16777215 or 'L' in Nonce: #未测试,L会出现其中? assert False IssueTransaction = '01'+ big_or_little(Nonce) + hex(len(Outputs))[2:].zfill(6) for o in Outputs: IssueTransaction = IssueTransaction + big_or_little(Txid) + float_2_hex(o['value']) + big_or_little(o['scripthash']) sk = SigningKey.from_string(binascii.unhexlify(Prikey), curve=NIST256p, hashfunc=hashlib.sha256) signature = binascii.hexlify(sk.sign(binascii.unhexlify(IssueTransaction),hashfunc=hashlib.sha256)) return IssueTransaction + '014140' + signature + '23' + Redeem_script
def __init__(self, identity, private, public): """Configure HTDSA signed request/response authentication. To perform the cryptographic operations required for the HTDSA protocol you must pass in either instances of `ecdsa` signing and verifying keys, or their hex-encoded versions which will be converted automatically. Additionally, the identity token (opaque identifier) assigned to your client application by the provider will need to be passed in so we can identify ourselves. The private key is your application's private key. The public key is the provider's service key you were given when registering your application. """ self.identity = identity self.private = SigningKey.from_string(unhexlify(private), NIST256p) if isinstance(private, (str, unicode)) else private self.public = VerifyingKey.from_string(unhexlify(public), NIST256p) if isinstance(public, (str, unicode)) else public
def new(cls, string=None): """Returns a new Address object. If a string is passed, the Address object will be created using that string and will be deterministic. If no string is passed, the Address object will be generated randomly. """ # Generates warner ECDSA objects if string: # deterministic private key ecdsaPrivkey = SigningKey.from_string( string=string, curve=SECP256k1) else: # random private key ecdsaPrivkey = SigningKey.generate( curve=SECP256k1, entropy=None) return cls.fromPrivkey(ecdsaPrivkey)
def check_for_privkey(keydir, jid, stderr): keypath = os.path.join(keydir, jid) if not os.path.isfile(keypath): msg = """\ Your package.json says our ID is: %(jid)s But I don't have a corresponding private key in: %(keypath)s If you are the original developer of this package and have recently copied the source code from a different machine to this one, you need to copy the private key into the file named above. Otherwise, if you are a new developer who has made a copy of an existing package to use as a starting point, you need to remove the 'id' property from package.json, so that we can generate a new id and keypair. This will disassociate our new package from the old one. """ print >>stderr, msg % {"jid": jid, "keypath": keypath} return None keylines = open(keypath, "r").readlines() keydata = {} for line in keylines: line = line.strip() if line: k,v = line.split(":", 1) keydata[k.strip()] = v.strip() if "private-key" not in keydata: raise ValueError("invalid keydata: can't find 'private-key' line") sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data") from ecdsa import SigningKey, VerifyingKey, NIST256p sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p) vk = sk.get_verifying_key() jid_2 = vk_to_jid(vk) if jid_2 != jid: raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid)) vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data") vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p) if vk.to_string() != vk2.to_string(): raise ValueError("invalid keydata: public-key mismatch") return sk
def get_transaction_signature(transaction, private_key): """ Gets the sigscript of a raw transaction private_key should be in bytes form """ packed_raw_transaction = get_packed_transaction(transaction) hash = hashlib.sha256(hashlib.sha256(packed_raw_transaction).digest()).digest() public_key = bitcoin_address_utils.get_public_key(private_key) key = SigningKey.from_string(private_key, curve=SECP256k1) signature = key.sign_digest(hash, sigencode=util.sigencode_der_canonize) signature += bytes.fromhex("01") #hash code type sigscript = struct.pack("<B", len(signature)) sigscript += signature sigscript += struct.pack("<B", len(public_key)) sigscript += public_key return sigscript
def __init__(self, public_key=None, private_key=None): self.id = 0 if public_key is not None: public_key = "#" + public_key if private_key is not None: private_key = "#" + private_key self.public_key = auto_bytes(public_key) self.private_key = private_key self.addr_version = None self.use_compression = 1 if private_key == "": private_key = None #Generate key pairs. if self.public_key == None and private_key == None: self.sign_key = SigningKey.generate(curve=SECP256k1) self.verify_key = self.sign_key.get_verifying_key() self.private_key = self.sign_key.to_string() self.public_key = self.verify_key.to_string() return #Init public key. self.old_verify_str = None if self.public_key != None: self.public_key = self.parse_public_key(self.public_key) self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1) self.sign_key = None self.old_verify_str = self.verify_key.to_string() #Init private key. if self.private_key != None: #Construct keys from private key. self.private_key = self.parse_private_key(private_key) self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) self.verify_key = self.sign_key.get_verifying_key() #Check private key corrosponds to public key. if self.old_verify_str != None: if self.old_verify_str != self.verify_key.to_string(): raise Exception("Private key doesn't corrospond to stored public key.")
def get_public_key(private_key): # this returns the concatenated x and y coordinates for the supplied private address # the prepended 04 is used to signify that it's uncompressed return (bytes.fromhex("04") + SigningKey.from_string(private_key, curve=SECP256k1).verifying_key.to_string())
def __init__(self, privkey, pubkey = None): self.private_key = SigningKey.from_string(privkey, SECP256k1, sha256) self.public_key = BlockIo.Helper.compress_pubkey(self.private_key.get_verifying_key().to_string())
def pay(payer_id, payees, asset): wallet_db = IndexedDBWallet() # step 1: get payer account payer = wallet_db.queryAccount(work_id=payer_id) if payer == None: print '%s : not exist payer block chain account' % payer_id return 2 payer_acc = Account(payer['pri_key']) contract = Contract() contract.createSignatureContract(payer_acc.publicKey) # step 2: load payer available coins coins = wallet_db.loadCoins(address=payer['address'],asset=asset) # step 3: select coins wallet = Wallet() selected_coins = wallet.selectCoins(coins, payees) if len(selected_coins) == 0: print 'no enough coins' return 5 change = sum([int(c.value) for c in selected_coins]) - sum([int(p['amount']) for p in payees]) # step 4: construct outputs outputs = [] payee_accs = {} for p in payees: payee = wallet_db.queryAccount(work_id=p['work_id']) if payee == None: print '%s : not exist payee block chain account' % payer_id return 3 acc = Account(payee['pri_key']) output = TransactionOutput(AssetId=asset, Value=p['amount'], ScriptHash=acc.scriptHash) outputs.append(output) payee_accs[acc.scriptHash] = acc # add change output if change > 0: outputs.append(TransactionOutput(AssetId=asset,Value=change,ScriptHash=payer_acc.scriptHash)) payee_accs[payer_acc.scriptHash] = payer_acc # step 5: construct inputs inputs = [TransactionInput(prevHash=c.txid, prevIndex=c.idx) for c in selected_coins] # step 6: make transaction tx = Transaction(inputs, outputs) stream = MemoryStream() writer = BinaryWriter(stream) tx.serializeUnsigned(writer) reg_tx = stream.toArray() txid = tx.ensureHash() print 'TX ->', repr(reg_tx) print 'TXID ->',txid # step 7: Signature Redeem_script = contract.redeemScript sk = SigningKey.from_string(binascii.unhexlify(payer_acc.privateKey), curve=NIST256p, hashfunc=hashlib.sha256) signature = binascii.hexlify(sk.sign(binascii.unhexlify(reg_tx),hashfunc=hashlib.sha256)) regtx = reg_tx + '014140' + signature + '23' + Redeem_script # step 8: sendRawTransaction node = RemoteNode(url='http://10.84.136.112:20332') response = node.sendRawTransaction(regtx) # step 9: update coin status if response['result'] == True: incoming = [] for i in range(len(outputs)): coin = Coin(txid=txid, idx=i, value=outputs[i].Value, asset=asset, address=payee_accs[outputs[i].ScriptHash].address,status=CoinState.Unconfirmed) incoming.append(coin) wallet_db.onSendTransaction(spending=selected_coins,incoming=incoming) return 0 else: return 6
def ecdsaPrivkey(self): """Returns a SigningKey object for this address. Useful for being able to sign a transaction. """ return SigningKey.from_string( string=self.rawPrivkey(), curve=SECP256k1)
def pop_auth_values(post_dict): endpoint = post_dict.pop('coreproxy_endpoint') identity = post_dict.pop('coreproxy_identity') private = SigningKey.from_string(unhexlify(post_dict.pop('coreproxy_private')), curve=NIST256p, hashfunc=sha256) public = VerifyingKey.from_string(unhexlify(post_dict.pop('coreproxy_public')), curve=NIST256p, hashfunc=sha256) return endpoint, identity, private, public
def from_secret(cls, secret): key = SigningKey.from_string(secret, curve=SECP256k1) return cls(key)