def encrypt(message: bytes, enckey: (int, int)) -> bytes: # This is an implementation of ECIES # https://en.wikipedia.org/wiki/Integrated_Encryption_Scheme util.validate_curve_point(enckey) r = util.random_private_value() R = bitcoin.fast_multiply(bitcoin.G, r) S = bitcoin.fast_multiply(enckey, r) kEkM = sha3.keccak_256(S[0].to_bytes(32, byteorder='big')).digest() kE, kM = kEkM[0:16], kEkM[16:32] # Use CTR mode to do encryption 256 bits at a time # https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#CTR num_trunc_bytes = (32 - len(message)) % 32 iv = util.random.randrange(2**256).to_bytes(32, byteorder='big') num_chunks = len(message) // 32 + (1 if num_trunc_bytes > 0 else 0) c = b''.join(( int.from_bytes(message[32*i:32*(i+1)].ljust(32, b'\0'), 'big') ^ int.from_bytes(sha3.keccak_256(kE + iv + i.to_bytes(32, 'big')).digest(), 'big') ).to_bytes(32, byteorder='big') for i in range(num_chunks)) # Quote from http://keccak.noekeon.org/: # Unlike SHA-1 and SHA-2, Keccak does not have the length-extension weakness, # hence does not need the HMAC nested construction. Instead, MAC computation # can be performed by simply prepending the message with the key. d = sha3.keccak_256(kM + c).digest() return (b''.join(x.to_bytes(32, byteorder='big') for x in R) + # 64 byte ephemeral key bytes((num_trunc_bytes,)) + # 1 byte truncation descriptor iv + # 32 byte initialization vector c + # arbitrary length 32 byte aligned enciphered message d) # 32 byte message authentication code (MAC)
async def handle_key_verification_phase(self): global own_address for participant in self.participants: share1 = participant.secret_share1 share2 = participant.secret_share2 if share1 is not None and share2 is not None: vlhs = bitcoin.fast_add( bitcoin.fast_multiply(bitcoin.G, share1), bitcoin.fast_multiply(G2, share2)) vrhs = functools.reduce( bitcoin.fast_add, (bitcoin.fast_multiply(ps, pow(own_address, k, bitcoin.N)) for k, ps in enumerate(participant.verification_points))) if vlhs != vrhs: # TODO: Produce complaints and continue instead of halting here raise ProtocolError('verification of shares failed') else: # TODO: Produce complaints and continue instead of halting here raise ProtocolError( 'missing share from address {:040x}'.format(address)) self.phase = ECDKGPhase.key_check db.Session.commit()
def generate_public_shares(poly1, poly2): if len(poly1) != len(poly2): raise ValueError('polynomial lengths must match ({} != {})'.format( len(poly1), len(poly2))) return (bitcoin.fast_add(bitcoin.fast_multiply(bitcoin.G, a), bitcoin.fast_multiply(G2, b)) for a, b in zip(poly1, poly2))
def get_kG(e, P, s=None): '''Use EC operation: kG = sG +eP. If s (signature) is not provided, it is generated randomly and returned. e - hash value, 32 bytes binary P - verification pubkey s - 32 bytes binary''' if not s: s = os.urandom(32) sG = btc.fast_multiply(btc.G, btc.decode(s, 256)) eP = btc.fast_multiply(P, btc.decode(e, 256)) return (btc.fast_add(sG, eP), s)
def get_kG(e, P, s=None): '''Use EC operation: kG = sG +eP. If s (signature) is not provided, it is generated randomly and returned. e - hash value, 32 bytes binary P - verification pubkey s - 32 bytes binary''' if not s: s = os.urandom(32) sG = btc.fast_multiply(btc.G,btc.decode(s,256)) eP = btc.fast_multiply(P,btc.decode(e,256)) return (btc.fast_add(sG, eP), s)
def ecdsa_raw_verify_one_to_one(msghash, vrs, sender_pub, receiver_priv): v, r, s = vrs w = bitcoin.inv(s, N) z = bitcoin.hash_to_int(msghash) u1, u2 = z * w % N, r * w % N receiver_pub = bitcoin.decode_pubkey(bitcoin.privtopub(receiver_priv)) receiver_sender_shared = bitcoin.fast_multiply( bitcoin.decode_pubkey(sender_pub), bitcoin.decode_privkey(receiver_priv)) u1Qr = bitcoin.fast_multiply(receiver_pub, u1) u2Qs = bitcoin.fast_multiply(receiver_sender_shared, u2) x, y = bitcoin.fast_add(u1Qr, u2Qs) return bool(r == x and (r % N) and (s % N))
def best_neighbor(vector, base, level): if level > 0: best_fitness = fitness(fast_multiply(G, bytes2int(vector)), base) best_candidate = vector for i in range(BYTES): temp_vector = vector[:] temp_vector[i] = 0 if temp_vector[i] == 1 else 1 temp_vector = best_neighbor(temp_vector, base, level-1) temp_fitness = fitness(fast_multiply(G, bytes2int(temp_vector)), base) if temp_fitness < best_fitness: best_fitness = temp_fitness best_candidate = temp_vector return best_candidate else: return vector
def generate_address(secret_bytes): int_privkey = int.from_bytes(secret_bytes, 'big') print('privkey (int): {privkey}'.format(privkey=int_privkey)) wif_not_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif') print('privkey (wif, not compressing): {privkey}'.format( privkey=wif_not_compressing_privkey)) wif_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif_compressed') print('privkey (wif, compressing): {privkey}'.format( privkey=wif_compressing_privkey)) print() public_key = bitcoin.fast_multiply(bitcoin.G, int_privkey) print('pubkey pair (int): {pubkey}'.format(pubkey=public_key)) pubkey_not_compressed = bitcoin.encode_pubkey(public_key, 'hex') print('pubkey (not compressed, hex): {pubkey}'.format( pubkey=pubkey_not_compressed)) pubkey_compressed = bitcoin.encode_pubkey(public_key, 'hex_compressed') print( 'pubkey (compressed, hex): {pubkey}'.format(pubkey=pubkey_compressed)) address_not_compressed = bitcoin.pubkey_to_address(public_key) print('address (not compressed, b58check): {address}'.format( address=address_not_compressed)) address_compressed = bitcoin.pubkey_to_address(pubkey_compressed) print('address (compressed, b58check): {address}'.format( address=address_compressed)) return address_compressed
def run(): global num_btc_wallets_searched # while True: valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) num_btc_wallets_searched += 1 r = requests.get("https://blockchain.info/q/getsentbyaddress/" + bitcoin.pubkey_to_address(public_key)) sys.stdout.flush() print("Number of BTC wallets searched: " + str(num_btc_wallets_searched), end='\r') print_pub_key = str(bitcoin.pubkey_to_address(public_key)) print_priv_key = str(wif_encoded_private_key) print_bal = str(r.text) if int(r.text) > 0: sys.stdout.flush() print() print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key)) print("Private Key is: ", wif_encoded_private_key) print("Balance is: ", r.text) send_email(print_pub_key, print_priv_key, print_bal) exit(0)
def decrypt(ciphertext: bytes, deckey: int, foo=False) -> bytes: util.validate_private_value(deckey) R = tuple(int.from_bytes(ciphertext[i:i+32], byteorder='big') for i in (0, 32)) util.validate_curve_point(R) S = bitcoin.fast_multiply(R, deckey) num_trunc_bytes = ord(ciphertext[64:65]) iv = ciphertext[65:97] c = ciphertext[97:-32] if len(c) % 32 != 0: raise ValueError('enciphered message not properly aligned') kEkM = sha3.keccak_256(S[0].to_bytes(32, byteorder='big')).digest() kE, kM = kEkM[0:16], kEkM[16:32] num_chunks = len(c) // 32 message = b''.join(( int.from_bytes(c[32*i:32*(i+1)], 'big') ^ int.from_bytes(sha3.keccak_256(kE + iv + i.to_bytes(32, 'big')).digest(), 'big') ).to_bytes(32, byteorder='big') for i in range(num_chunks)) if num_trunc_bytes > 0: message, padding = message[:-num_trunc_bytes], message[-num_trunc_bytes:] if padding != b'\0' * num_trunc_bytes: raise ValueError('invalid padding') d = ciphertext[-32:] if d != sha3.keccak_256(kM + c).digest(): raise ValueError('message authentication code does not match') if foo: return int.from_bytes(sha3.keccak_256(message).digest(), 'big') return message
def ecdsa_raw_sign_one_to_one(msghash, sender_priv, receiver_pub): z = bitcoin.hash_to_int(msghash) k = bitcoin.deterministic_generate_k(msghash, sender_priv) r, y = bitcoin.fast_multiply(bitcoin.decode_pubkey(receiver_pub), k) s = bitcoin.inv(k, N) * (z + r * bitcoin.decode_privkey(sender_priv)) % N v, r, s = 27 + ((y % 2) ^ (0 if s * 2 < N else 1)), r, s if s * 2 < N else N - s return v, r, s
def generate_key(): #generate a random private key valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N #print ('Private Key (hex) is: ' + private_key) #print ('private Key (decimal) is: ' + str(decoded_private_key)) #convert private key to WIF format wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') #print('Private Key (WIF) is: ' + wif_encoded_private_key) # Add sufix '01' to indicate a compressed private Key compressed_private_key = private_key + '01' #print ('Private Key Compressed (hex) is: ' + compressed_private_key) # generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') #print ('Private Key (WIF-compressed) is: ' + wif_compressed_private_key) # Multiply de EC generator G with the priveate key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) #print ('Public Key (x,y) coordinates are: ' + str(public_key)) # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') #print ('Public Key (hex) is: ' + hex_encoded_public_key) # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key if public_key_y % 2 == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) #print ('Compressed Public Key is: ' + hex_compressed_public_key) # Generate bitcoin address from public Key #print ('Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(public_key)) # Generate compressedd bitcoin address from compressed public key #print ('Compressed Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(hex_compressed_public_key)) compressed_address_base58check = bitcoin.pubkey_to_address( hex_compressed_public_key) kson = { "wif1": wif_encoded_private_key, "wif": wif_compressed_private_key, "key": compressed_address_base58check } return kson
def create_bitcoin_public_key(private_key): decoded_private_key = bitcoin.decode_privkey(private_key, "hex") public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) (public_key_x, public_key_y) = public_key compressed_prefix = "02" if (public_key_y % 2) == 0 else "03" # 64 represents the minimum length of the string required returned back. # Zeros will be prepended to a string until it meets the length requirement. # Less characters than 64 will result in an invalid public key. return compressed_prefix + bitcoin.encode(public_key_x, 16, 64)
def demo_private_to_public(decoded_private_key): # 计算公钥坐标 K = k * G public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) # 计算公钥 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') # 计算压缩公钥 # if public_key[1] % 2 == 0: # 两种方式均可 compressed_prefix = '02' if public_key[1] & 1 == 0 else '03' # 转十六也可用 bitcoin_core.encode(xxx, 16) hex_compressed_public_key = compressed_prefix + hex(public_key[0])[2:] return public_key, hex_encoded_public_key, compressed_prefix, hex_compressed_public_key
def test_can_decrypt_encrypted_random_messages(): # TODO: Fix populus compat # ies, _ = chain.provider.get_or_deploy_contract('IntegratedEncryptionScheme') num_runs = 10 average_gas_cost = 0 for _ in range(num_runs): message = os.urandom(util.random.randrange(1, 100)) deckey = util.random_private_value() enckey = bitcoin.fast_multiply(bitcoin.G, deckey) ciphertext = crypto.encrypt(message, enckey) assert message == crypto.decrypt(ciphertext, deckey) # assert crypto.decrypt(ciphertext, deckey, foo=True) == ies.call().decrypt(ciphertext, deckey) # average_gas_cost += ies.estimateGas().decrypt(ciphertext, deckey) average_gas_cost /= num_runs
async def handle_uninitialized_phase(self): for addr in networking.channels.keys(): self.get_or_create_participant_by_address(addr) # everyone should on agree on participants self.threshold = math.ceil(THRESHOLD_FACTOR * (len(self.participants) + 1)) spoly1 = random_polynomial(self.threshold) spoly2 = random_polynomial(self.threshold) self.secret_poly1 = spoly1 self.secret_poly2 = spoly2 self.encryption_key_part = bitcoin.fast_multiply( bitcoin.G, self.secret_poly1[0]) self.verification_points = tuple( bitcoin.fast_add(bitcoin.fast_multiply(bitcoin.G, a), bitcoin.fast_multiply(G2, b)) for a, b in zip(spoly1, spoly2)) self.phase = ECDKGPhase.key_distribution db.Session.commit()
def run(): while True: valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey( decoded_private_key, 'wif') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) r = requests.get("https://blockchain.info/q/getsentbyaddress/" + bitcoin.pubkey_to_address(public_key)) if int(r.text) > 0: print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key)) print("Private Key is: ", wif_encoded_private_key) print("Balance is: ", r.text)
def main(args): logging.basicConfig(level=args.log_level, format=args.log_format) ecdkg.private_key = util.get_or_generate_private_value( args.private_key_file) own_public_key = bitcoin.fast_multiply(bitcoin.G, ecdkg.private_key) ecdkg.own_address = util.curve_point_to_eth_address(own_public_key) ecdkg.accepted_addresses = util.get_addresses(args.addresses_file) ecdkg.accepted_addresses.difference_update((ecdkg.own_address, )) locations = util.get_locations(args.locations_file) logging.debug( 'own pubkey: ({0[0]:064x}, {0[1]:064x})'.format(own_public_key)) logging.info('own address: {:040x}'.format(ecdkg.own_address)) if ecdkg.accepted_addresses: logging.info('accepted addresses: {{\n {}\n}}'.format('\n '.join( '{:040x}'.format(a) for a in ecdkg.accepted_addresses))) else: logging.warn('not accepting any addresses') db.init() def shutdown(signum, frame): logging.info('\nShutting down...') sys.exit() for signum in (signal.SIGINT, signal.SIGTERM): signal.signal(signum, shutdown) loop = asyncio.get_event_loop() loop.run_until_complete(networking.server(args.host, args.port, loop=loop)) for hostname, port in locations: loop.create_task( networking.attempt_to_establish_channel(hostname, port)) loop.create_task(networking.emit_heartbeats()) try: loop.run_forever() except SystemExit: pass finally: for task in asyncio.Task.all_tasks(loop): task.cancel() loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() logging.info('Goodbye')
def sarah(hexli): private_key = hexli decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') compressed_private_key = private_key + '01' wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(private_key, 'hex'), 'wif_compressed') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') (public_key_x, public_key_y) = public_key if public_key_y % 2 == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) non_compressed_adress = bitcoin.pubkey_to_address(public_key) compressed_address = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf8")) return non_compressed_adress, compressed_address, wif_encoded_private_key, wif_compressed_private_key, private_key
def address_search(search_for='1Love'): privkey = random.randrange(2**256) address = '' count = 0 start = timeit.default_timer() print("Searching for %s (pid %s)" % (search_for, os.getpid())) while not search_for in address: privkey += 1 pubkey_point = fast_multiply(G, privkey) address = pubkey_to_address(pubkey_point) count += 1 if not count % 1000: print("Searched %d in %d seconds (pid %d)" % (count, timeit.default_timer() - start, os.getpid())) private_key, public_key, pid, wif_key = key_data(privkey) key_data_output(private_key, public_key, pid, wif_key, search_for, address, count, start)
def function_keys(): valid_private_key = False #randomize private key while not valid_private_key: private_key = bitcoin.random_key() decode_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decode_private_key < bitcoin.N print "Private Key (hex) is:", private_key print "Private Key (decimal) is:", decode_private_key wif_encode_private_key = bitcoin.encode_privkey(decode_private_key, 'wif') print "Private key (WIF) is:", wif_encode_private_key # convert private key to wif format compressed_private_key = private_key + '01' print "Private key Compressed (hex) is:", compressed_private_key # add '01' to indicate compressed private key wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print "Private Key (Wif-compressed) is:", wif_compressed_private_key public_key = bitcoin.fast_multiply( bitcoin.G, decode_private_key ) # multiply EC generator with the private key to have public key point print "Public Key (x, y) coordinates is:", public_key hex_encoded_public_key = bitcoin.encode_pubkey( public_key, 'hex') # encoded public key with '04' print "Public Key (hex) is:", hex_encoded_public_key (public_key_x, public_key_y) = public_key # compressed public key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) print "Compressed Public Key (hex) is:", hex_compressed_public_key print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address( public_key) print "Compressed Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address( hex_compressed_public_key)
def test_nodes_match_enckey_and_deckeys(nodes, request_timeout): wait_for_all_nodes_connected(nodes, request_timeout) deccond = 'past {}'.format(datetime.utcnow().isoformat()) enckeys = [ requests.post('https://localhost:{}'.format(n.port), verify=False, timeout=request_timeout, data=json.dumps({ 'id': 'honk', 'method': 'get_encryption_key', 'params': [deccond], })).json()['result'] for n in nodes ] enckeys = [tuple(int(ek[i:i + 64], 16) for i in (0, 64)) for ek in enckeys] for ek in enckeys: util.validate_curve_point(ek) assert (all(ek == enckeys[0] for ek in enckeys[1:])) deckeys = [ requests.post('https://localhost:{}'.format(n.port), verify=False, timeout=request_timeout, data=json.dumps({ 'id': 'honk', 'method': 'get_decryption_key', 'params': [deccond], })).json()['result'] for n in nodes ] deckeys = [int(dk, 16) for dk in deckeys] for dk in deckeys: util.validate_private_value(dk) assert (all(dk == deckeys[0] for dk in deckeys[1:])) assert (bitcoin.fast_multiply(bitcoin.G, deckeys[0]) == enckeys[0])
def sign_donation_tx(tx, i, priv): k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) #k = deterministic_generate_k(msghash, priv) r, y = btc.fast_multiply(btc.G, k) s = btc.inv(k, btc.N) * (z + r*btc.decode_privkey(priv)) % btc.N rawsig = 27+(y % 2), r, s sig = btc.der_encode_sig(*rawsig)+btc.encode(hashcode, 16, 2) #sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def sign(tx_hash: bytes, private_key: str): msg_hash = tx_hash z = bitcoin.hash_to_int(msg_hash) k = bitcoin.deterministic_generate_k(msg_hash, private_key) r, y = bitcoin.fast_multiply(bitcoin.G, k) s = bitcoin.inv(k, bitcoin.N) * ( z + r * bitcoin.decode_privkey(private_key)) % bitcoin.N v, r, s = 27 + ((y % 2) ^ (0 if s * 2 < bitcoin.N else 1) ), r, s if s * 2 < bitcoin.N else bitcoin.N - s if 'compressed' in bitcoin.get_privkey_format(private_key): v += 4 hex_str_r = hex(r)[2:] if len(hex_str_r) < 64: hex_str_r = ((64 - len(hex_str_r)) * "0") + hex_str_r hex_str_s = hex(s)[2:] if len(hex_str_s) < 64: hex_str_s = ((64 - len(hex_str_s)) * "0") + hex_str_s signature = hex_str_r + hex_str_s recovery = v - 27 return signature, recovery
def sign_donation_tx(tx, i, priv): k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) #k = deterministic_generate_k(msghash, priv) r, y = btc.fast_multiply(btc.G, k) s = btc.inv(k, btc.N) * (z + r * btc.decode_privkey(priv)) % btc.N rawsig = 27 + (y % 2), r, s sig = btc.der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2) #sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def KeyToAddress(key): private_key = str(key) decoded_private_key = bitcoin.decode_privkey(private_key.encode("utf-8"), 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') keys = wif_encoded_private_key public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) address1 = bitcoin.pubkey_to_address(public_key) #address2 = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf-8")) #balance1 = balanceApi(address1) #balance1 = btcApi(address1) #if balance1 ==None: # balance1 = 0 if Address.objects.filter(address=address1): balance = "可能有余额" else: balance = "没有" return keys, address1, balance
#!/usr/bin/env python from bitcoin import G, fast_multiply import random # use with an even number nbits = 16 # generate private and public key k = random.randint(0, 2**nbits - 2**(nbits / 2)) q = fast_multiply(G, k)[0] print("SEARCH - {0}".format(k)) for n in range(2**nbits - 2**(nbits / 2)): candidate = fast_multiply(G, n) if candidate[0] == q: print("FOUND - {0}".format(n)) break
def private_key_to_public_key(privKeyHex: str) -> (int, int): privateKey = int(privKeyHex, 16) return bitcoin.fast_multiply(bitcoin.G, privateKey)
def ecdsa_sign_k(z, d, k): r, y = bitcoin.fast_multiply(bitcoin.G, k) s = bitcoin.inv(k, bitcoin.N) * (z + r * d) % bitcoin.N v, r, s = 27 + ((y % 2) ^ (0 if s * 2 < bitcoin.N else 1) ), r, s if s * 2 < bitcoin.N else bitcoin.N - s return v, r, s
import bitcoin import hashlib import random def ecdsa_sign_k(z, d, k): r, y = bitcoin.fast_multiply(bitcoin.G, k) s = bitcoin.inv(k, bitcoin.N) * (z + r * d) % bitcoin.N v, r, s = 27 + ((y % 2) ^ (0 if s * 2 < bitcoin.N else 1) ), r, s if s * 2 < bitcoin.N else bitcoin.N - s return v, r, s # Generate secret key & the corresponding public key and address sk = random.SystemRandom().randrange(1, bitcoin.N) Q = bitcoin.fast_multiply(bitcoin.G, sk) # Sign 2 differents messages with same k signing_k = random.SystemRandom().randrange(1, bitcoin.N) z1 = bitcoin.hash_to_int(hashlib.sha256('first_message').hexdigest()) z2 = bitcoin.hash_to_int(hashlib.sha256('second_message').hexdigest()) v1, r1, s1 = ecdsa_sign_k(z1, sk, signing_k) v2, r2, s2 = ecdsa_sign_k(z2, sk, signing_k) assert r1 == r2 print('+ R used = {:x}'.format(r1)) # Calculate k candidates k_candidates = [(z1 - z2) * bitcoin.inv(s1 - s2, bitcoin.N) % bitcoin.N, (z1 - z2) * bitcoin.inv(s1 + s2, bitcoin.N) % bitcoin.N] for k in k_candidates: priv_key = (s1 * k - z1) * bitcoin.inv(r1, bitcoin.N) % bitcoin.N
# Convert private key to WIF format wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print("Private Key (WIF) is: ", wif_encoded_private_key) # Add suffix "01" to indicate a compressed private key compressed_private_key = private_key + '01' print("Private Key Compressed (hex) is: ", compressed_private_key) # Generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print("Private Key (WIF-Compressed) is: ", wif_compressed_private_key) # Multiply the EC generator point G with the private key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print("Public Key (x,y) coordinates is:", public_key) # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print("Public Key (hex) is:", hex_encoded_public_key) # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key compressed_prefix = '02' if (public_key_y % 2) == 0 else '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) print("Compressed Public Key (hex) is:", hex_compressed_public_key) # Generate bitcoin address from public key print("Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(public_key))
#the set of all signature values (s(i,j)) s = {} #for each OR loop, the index at which we start #the signature calculations, the one after the #the signing index (the one we have the privkey for) start_index = {} #the random value set as the k-value for the signing index k = [os.urandom(32) for i in range(len(vks))] to_be_hashed = '' for i, loop in enumerate(vks): e[i]=[None]*len(vks[loop]) s[i] = [None]*len(vks[loop]) kG = btc.fast_multiply(btc.G, btc.decode(k[i],256)) start_index[i] = (signing_indices[i]+1)%len(vks[loop]) if start_index[i]==0: to_be_hashed += btc.encode_pubkey(kG,'bin_compressed') #in this case, there are no more vertices to process in the first stage continue e[i][start_index[i]] = borr_hash(M, kG, i, start_index[i]) for x in range(start_index[i]+1,len(vks[loop])): y,s[i][x-1] = get_kG(e[i][x-1], vks[i][x-1]) e[i][x] = borr_hash(M,y,i,x) #kGend is the EC point corresponding to the k-value #for the vertex before zero, which will be included in the hash for e0 kGend, s[i][len(vks[i])-1] = get_kG(e[i][len(vks[i])-1],vks[i][len(vks[i])-1])
import bitcoin valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print("Private key in hexadecimal is {}".format(private_key)) print("Private key in decimal is {}".format(decoded_private_key)) wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print("Private key in WIF is {}".format(wif_encoded_private_key)) compressed_private_key = private_key + '01' print("Private key compressed in hexadecimal {}".format(compressed_private_key)) wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print("Private key WIF compressed is {}".format(wif_compressed_private_key)) public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print("Public key (x,y) coordinates is".format(public_key)) hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print("Hex encoded public key is {}".format(hex_encoded_public_key)) (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) print("Compressed Public Key (hex) is {}".format(hex_compressed_public_key)) print("Bitcoin Address (b58check) is {}".format(bitcoin.pubkey_to_address(public_key))) print("Compressed Bitcoin Address (b58check) is: {}".format(bitcoin.pubkey_to_address(hex_compressed_public_key)))
return pow(a, (2 * p - 1) / 3, p) if (p % 9) == 4: root = pow(a, (2 * p + 1) / 9, p) assert pow(root, 3, p) == a % p return root if (p % 9) == 7: root = pow(a, (p + 2) / 9, p) assert pow(root, 3, p) == a % p return root else: print "Not implemented yet. See the second paper" # Generate secret key & the corresponding public key and address d = random.SystemRandom().randrange(1, N) (x, y) = fast_multiply(G, d) # Double Q, works only when A = 0 in ECDSA curve Q2 = ((9 * x**4 * inv(4 * y**2, P) - (2 * x)) % P, (9 * x**3 * inv(2 * y, P) - (27 * x**6) * inv(8 * y**3, P) - y) % P) assert Q2 == fast_multiply(G, d * 2) # Double and triple Qx, works only for secp256k1 curve Q2x = ((x**4 - 56 * x) * inv(4 * x**3 + 28, P)) % P Q3x = ( (x**9 - 672 * x**6 + 2352 * x**3 + 21952) * inv(9 * x**2 * (x**3 + 28)**2, P)) % P assert Q2x == fast_multiply(G, d * 2)[0] assert Q3x == fast_multiply(G, d * 3)[0] # Double Qx and add G