Bitcoin public key to address python

Keys and Addresses in Python

The most comprehensive bitcoin library in Python is “pybitcointools”by Vitalik Buterin (https://github.com/vbuterin/pybitcointools). In the following code example, we use the pybitcointools library (imported as “bitcoin”) to generate and display keys and addresses in various formats:

Example – Key and Address generation and formatting with the pybitcointools library

import bitcoin # 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: ", 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 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.base10_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 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 # Generate bitcoin address from public key print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(public_key) # Generate compressed bitcoin address from compressed public key print "Compressed Bitcoin Address (b58check) is:", \ bitcoin.pubkey_to_address(hex_compressed_public_key)

Here’s the output from running this code:

Читайте также:  Java пауза в консоли

Example – Running key-to-address-ecc-example.py

$ python key-to-address-ecc-example.py Private Key (hex) is: 3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6 Private Key (decimal) is: 26563230048437957592232553826663696440606756685920117476832299673293013768870 Private Key (WIF) is: 5JG9hT3beGTJuUAmCQEmNaxAuMacCTfXuw1R3FCXig23RQHMr4K Private Key Compressed (hex) is: 3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa601 Private Key (WIF-Compressed) is: KyBsPXxTuVD82av65KZkrGrWi5qLMah5SdNq6uftawDbgKa2wv6S Public Key (x,y) coordinates is: (41637322786646325214887832269588396900663353932545912953362782457239403430124L, 16388935128781238405526710466724741593761085120864331449066658622400339362166L) Public Key (hex) is: 045c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec 243bcefdd4347074d44bd7356d6a53c495737dd96295e2a9374bf5f02ebfc176 Compressed Public Key (hex) is: 025c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec Bitcoin Address (b58check) is: 1thMirt546nngXqyPEz532S8fLwbozud8 Compressed Bitcoin Address (b58check) is: 14cxpo3MBCYYWCgF74SWTdcmxipnGUsPw3

Here’s another example, using the Python ECDSA library for the Elliptic Curve math and without using any specialized bitcoin libraries:

Example – A script demonstrating Elliptic Curve math used for bitcoin keys

import ecdsa import random from ecdsa.util import string_to_number, number_to_string # secp256k1, http://www.oid-info.com/get/1.3.132.0.10 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L _b = 0x0000000000000000000000000000000000000000000000000000000000000007L _a = 0x0000000000000000000000000000000000000000000000000000000000000000L _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L curve_secp256k1 = ecdsa.ellipticcurve.CurveFp(_p, _a, _b) generator_secp256k1 = ecdsa.ellipticcurve.Point(curve_secp256k1, _Gx, _Gy, _r) oid_secp256k1 = (1, 3, 132, 0, 10) SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1) ec_order = _r curve = curve_secp256k1 generator = generator_secp256k1 def random_secret(): random_char = lambda: chr(random.randint(0, 255)) convert_to_int = lambda array: int("".join(array).encode("hex"), 16) byte_array = [random_char() for i in range(32)] return convert_to_int(byte_array) def get_point_pubkey(point): if point.y() & 1: key = '03' + '%064x' % point.x() else: key = '02' + '%064x' % point.x() return key.decode('hex') def get_point_pubkey_uncompressed(point): key = '04' + \ '%064x' % point.x() + \ '%064x' % point.y() return key.decode('hex') # Generate a new private key. secret = random_secret() print "Secret: ", secret # Get the public key point. point = secret * generator print "EC point:", point print "BTC public key:", get_point_pubkey(point).encode("hex") # Given the point (x, y) we can create the object using: point1 = ecdsa.ellipticcurve.Point(curve, point.x(), point.y(), ec_order) assert point1 == point Running the script: Example 4-6. Installing the Python ECDSA library and running the ec_math.py script $ # Install Python PIP package manager $ sudo apt-get install python-pip $ # Install the Python ECDSA library $ sudo pip install ecdsa $ # Run the script $ python ec-math.py Secret: 38090835015954358862481132628887443905906204995912378278060168703580660294000 EC point: (70048853531867179489857750497606966272382583471322935454624595540007269312627,\ 105262206478686743191060800263479589329920209527285803935736021686045542353380) BTC public key: 029ade3effb0a67d5c8609850d797366af428f4a0d5194cb221d807770a1522873

This article has been published from the source link without modifications to the text. Only the headline has been changed.

Источник

Читайте также:  Api для погоды kotlin

Как конвертировать публичные ключи Bitcoin-PUBKEY HEX в Bitcoin-адрес Base58 и проверить баланс на наличие монет BTC

В итоге мы с особой легкостью будем проверять баланс Биткоина, сканируя Блокчейн в терминале Google Colab [TerminalGoogleColab]

Ранее я записывал видеоинструкцию: «TERMINAL в Google Colab создаем все удобства для работ в GITHUB»

Давайте перейдем в репозиторию «CryptoDeepTools» и разберем в детали работу Bash-скрипта: getbalance.sh

КомандыФайлыКод нашего Bash-скрипта: getbalance.sh

grep 'PUBKEY = ' signatures.json > pubkeyall.json

Утилита grep собирает все публичные ключи в один общий файл: pubkeyall.json

sort -u pubkeyall.json > pubkey.json

Утилита sort сортирует и удаляет дубли отбирает уникальные публичные ключи и результат сохраняет в файл: pubkey.json

Утилита rm удаляет pubkeyall.json

sed -i 's/PUBKEY = //g' pubkey.json

Утилита sed стирает префикс PUBKEY =

Запускаем Python-скрипт pubtoaddr.py конвертируем из файла pubkey.json где хранятся наши публичные ключи Биткоина PUBKEY (HEX) в файл addresses.json результат сохранится как Биткойн Адреса (Base58)

import hashlib import base58 def hash160(hex_str): sha = hashlib.sha256() rip = hashlib.new('ripemd160') sha.update(hex_str) rip.update(sha.digest()) return rip.hexdigest() # .hexdigest() is hex ASCII pub_keys = open('pubkey.json', 'r', encoding='utf-8') new_file = open('addresses.json', 'a', encoding='utf-8') compress_pubkey = False for pub_key in pub_keys: pub_key = pub_key.replace('\n', '') if compress_pubkey: if (ord(bytearray.fromhex(pub_key[-2:])) % 2 == 0): pubkey_compressed = '02' else: pubkey_compressed = '03' pubkey_compressed += pub_key[2:66] hex_str = bytearray.fromhex(pubkey_compressed) else: hex_str = bytearray.fromhex(pub_key) key_hash = '00' + hash160(hex_str) sha = hashlib.sha256() sha.update(bytearray.fromhex(key_hash)) checksum = sha.digest() sha = hashlib.sha256() sha.update(checksum) checksum = sha.hexdigest()[0:8] # new_file.write("" + (base58.b58encode(bytes(bytearray.fromhex(key_hash + checksum)))).decode('utf-8')) new_file.write((base58.b58encode(bytes(bytearray.fromhex(key_hash + checksum)))).decode('utf-8') + "\n") pub_keys.close() new_file.close()

Мы получили файл addresses.json теперь проверим баланс монет Биткоина используя для этого Python-скрипт bitcoin-checker.py

Запускаем Python-скрипт: python2 bitcoin-checker.py

import sys import re from time import sleep try: # if is python3 from urllib.request import urlopen except: # if is python2 from urllib2 import urlopen def check_balance(address): #Modify the value of the variable below to False if you do not want Bell Sound when the Software finds balance. SONG_BELL = True #Add time different of 0 if you need more security on the checks WARN_WAIT_TIME = 0 blockchain_tags_json = [ 'total_received', 'final_balance', ] SATOSHIS_PER_BTC = 1e+8 check_address = address parse_address_structure = re.match(r' *([a-zA-Z1-9])', check_address) if ( parse_address_structure is not None ): check_address = parse_address_structure.group(1) else: print( "\nThis Bitcoin Address is invalid" + check_address ) exit(1) #Read info from Blockchain about the Address reading_state=1 while (reading_state): try: htmlfile = urlopen("https://blockchain.info/address/%s?format=json" % check_address, timeout = 10) htmltext = htmlfile.read().decode('utf-8') reading_state = 0 except: reading_state+=1 print( "Checking. " + str(reading_state) ) sleep(60*reading_state) print( "\nBitcoin Address = " + check_address ) blockchain_info_array = [] tag = '' try: for tag in blockchain_tags_json: blockchain_info_array.append ( float( re.search( r'%s":(\d+),' % tag, htmltext ).group(1) ) ) except: print( "Error '%s'." % tag ); exit(1) for i, btc_tokens in enumerate(blockchain_info_array): sys.stdout.write ("%s \t %.8f Bitcoin" % (btc_tokens/SATOSHIS_PER_BTC) ); else: print( "0 Bitcoin" ); if (SONG_BELL and blockchain_tags_json[i] == 'final_balance' and btc_tokens > 0.0): #If you have a balance greater than 0 you will hear the bell sys.stdout.write ('\a\a\a') sys.stdout.flush() arq1.write("Bitcoin Address: %s" % check_address) arq1.write("\t Balance: %.8f Bitcoin" % (btc_tokens/SATOSHIS_PER_BTC)) arq1.write("\n") arq1.close() if (WARN_WAIT_TIME > 0): sleep(WARN_WAIT_TIME) #Add the filename of your list of Bitcoin Addresses for check all. with open("addresses.json") as file: for line in file: arq1 = open('balance.json', 'a') address = str.strip(line) print ("__________________________________________________\n") check_balance(address) print "__________________________________________________\n" arq1.close()

В итоге результат сохранится в файле: balance.json

Файл: balance.json

Теперь мы научились:

  • Конвертировать публичные ключи Биткоина PUBKEY (HEX) в Биткойн Адрес (Base58)
  • Проверять все Биткойн Адреса (Base58) на наличие монет Биткоина
  • Применить это для криптоанализа

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

This python script will convert compressed, uncompressed and levelDB-compressed (chainstate) public keys to addresses

beiex/bitcoin_pub2addr

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Bitcoin public keys converted to addresses

This python script will "batch" convert compressed, uncompressed and levelDB-compressed (chainstate) public keys to addresses

This my differ depending on your system!

$ sudo -H python3 pip install cryptos 

If this doesn't work for you primal100/pybitcointools can be found here or here

$ python3 bitcoin_pub2addr.py source.txt 

Afterwards you will find a source_pud2addr.txt in the same folder where source.txt is located.

About

This python script will convert compressed, uncompressed and levelDB-compressed (chainstate) public keys to addresses

Источник

Оцените статью