Bitcoind

python比特幣公鑰解決程式碼錯誤

  • June 4, 2018
import hashlib

b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

def hex_open_key_to_hex_hesh160(hex_open_key):
h160 = hashlib.new('ripemd160')
h160.update(hashlib.sha256(('04'+hex_open_key).decode('hex')).hexdigest().decode('hex'))
return h160.hexdigest()

def hex_hesh160_to_hex_addr_v0(hex_hesh160):
return '00'+hex_hesh160+hashlib.sha256(hashlib.sha256(('00'+hex_hesh160).decode('hex')).hexdigest().decode('hex')).hexdigest()[0:8]

def hex_addr_v0_to_hex_hesh160(hex_addr_v0):
return hex_addr_v0[2:-8]


def hex_to_base58(hex_data):
base58 = ''
int_data = int(hex_data, 16)
while int_data >= len(b58chars):
   base58 = b58chars[int_data%len(b58chars)] + base58
   int_data = int_data/len(b58chars)
base58 = b58chars[int_data%len(b58chars)] + base58
for i in xrange(len(hex_data)/2):
   if hex_data[i*2:i*2+2] == '00':
       base58 = '1' + base58
   else:
       break
return base58

def base58_to_hex(base58):
hex_data = ''
int_data = 0
for i in xrange(-1, -len(base58)-1, -1):
   int_data += (b58chars.index(base58[i]))*58**(-i-1)
hex_data = hex(int_data)[2:-1]
for i in xrange(len(base58)):
   if base58[i] == '1':
       hex_data = '00' + hex_data
   else:
       break
return hex_data

hex_open_key = '5bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac786ef3a1fa082da527a3a51bcd71104b4e6ef91b62b2e93bcfdbc4ac7c35e9fddb'
print hex_to_base58(hex_hesh160_to_hex_addr_v0(hex_open_key_to_hex_hesh160(hex_open_key)))

上面的程式碼獲取比特幣公鑰地址,一些公鑰錯誤發生

private key is 0x5c58d

public key pairs

x =  0x5bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac786L
y1 =  0xef3a1fa082da527a3a51bcd71104b4e6ef91b62b2e93bcfdbc4ac7c35e9fddbL
y2  =  0xf10c5e05f7d25ad85c5ae4328eefb4b19106e49d4d16c430243b5382ca15fe54L

公鑰 x 和 y1 出錯

5bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac786ef3a1fa082da527a3a51bcd71104b4e6ef91b62b2e93bcfdbc4ac7c35e9fddb

Traceback (most recent call last):
  File "<module3>", line 45, in <module>
  File "<module3>", line 7, in hex_open_key_to_hex_hesh160
  File "C:\Python27\lib\encodings\hex_codec.py", line 42, in hex_decode
  output = binascii.a2b_hex(input)
TypeError: Odd-length string

公鑰 x 和 y2 沒有錯誤

5bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac786f10c5e05f7d25ad85c5ae4328eefb4b19106e49d4d16c430243b5382ca15fe54

address
   17MnDMuqhiTnQ1Yc38H2RYdSHkfUq6wmrq

您收到錯誤是因為您提供的十六進製字元串長度為 127 個字元。你需要用零填充。

即使您用零填充05bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac786ef3a1fa082da527a3a51bcd71104b4e6ef91b62b2e93bcfdbc4ac7c35e9fddb也不是有效的公鑰。它必須以 04 開頭。

您的公鑰的座標 y1、y2 也不在曲線上。我不知道你從哪裡得到你的鑰匙,但它是無效的。

Private Key對應的Public Key0x5bd8834885082d9e9775f2084610bea79d2bd7acde2fc28b4dba85b0902ac78604b302d50e6afaea3eb3194fced5b12ba45aa170d2d717d5a598511a96187a7a90e8c84b1f57a822bda9ecf111374c9e92fe0d1fb5a192a45790f437828d17f009,P2PKH地址是14pFAXD2uQpdpToL5LS4oh1bsSGXnVpA2r

引用自:https://bitcoin.stackexchange.com/questions/75857