在python 3.6中从公钥到公共地址生成比特币密钥对

在python 3.6中从公钥到公共地址生成比特币密钥对,python,python-3.x,hash,cryptography,bitcoin,Python,Python 3.x,Hash,Cryptography,Bitcoin,我有一个问题,我正试图编写一个脚本,为比特币地址生成密钥对。我甚至可以生成一个随机私钥和一个公钥。我知道(或想了很多?)我的第一部分代码是正确的。当我转到并检查生成的私钥以了解详细信息时,我总是获得正确生成的公钥 这就是我现在拥有的 import os import ecdsa import binascii private_key = binascii.hexlify(os.urandom(32)).decode() print("private key = " + private_key)

我有一个问题,我正试图编写一个脚本,为比特币地址生成密钥对。我甚至可以生成一个随机私钥和一个公钥。我知道(或想了很多?)我的第一部分代码是正确的。当我转到并检查生成的私钥以了解详细信息时,我总是获得正确生成的公钥

这就是我现在拥有的

import os
import ecdsa
import binascii

private_key = binascii.hexlify(os.urandom(32)).decode()
print("private key = " + private_key)

Private_key = bytes.fromhex(private_key)

signing_key = ecdsa.SigningKey.from_string(Private_key, curve = ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()

public_key = bytes.fromhex("04") + verifying_key.to_string()
print ("public key = " + public_key.hex())
问题是现在我得到了130个字符的公钥,我想把它转换成比特币地址。我不知道该怎么做。我需要做一些编码/解码,但我不能绕着它转。 这是我在互联网上找到的解释,但我无法理解:


有人能帮我一下吗?

这段代码在Python2和Python3中都运行。 它不仅打印比特币地址,还打印一些中间值。 公钥是pubkey变量中的130个十六进制字符字符串

请注意:未压缩和压缩的表单。更改压缩\u键布尔变量以提取每个变量

#!/usr/bin/env python
# https://en.bitcoin.it/wiki/Protocol_documentation#Addresses

import hashlib
import base58

# ECDSA bitcoin Public Key
pubkey = '0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6'
# See 'compressed form' at https://en.bitcoin.it/wiki/Protocol_documentation#Signatures
compress_pubkey = False


def hash160(hex_str):
    sha = hashlib.sha256()
    rip = hashlib.new('ripemd160')
    sha.update(hex_str)
    rip.update( sha.digest() )
    print ( "key_hash = \t" + rip.hexdigest() )
    return rip.hexdigest()  # .hexdigest() is hex ASCII


if (compress_pubkey):
    if (ord(bytearray.fromhex(pubkey[-2:])) % 2 == 0):
        pubkey_compressed = '02'
    else:
        pubkey_compressed = '03'
    pubkey_compressed += pubkey[2:66]
    hex_str = bytearray.fromhex(pubkey_compressed)
else:
    hex_str = bytearray.fromhex(pubkey)

# Obtain key:

key_hash = '00' + hash160(hex_str)

# Obtain signature:

sha = hashlib.sha256()
sha.update( bytearray.fromhex(key_hash) )
checksum = sha.digest()
sha = hashlib.sha256()
sha.update(checksum)
checksum = sha.hexdigest()[0:8]

print ( "checksum = \t" + sha.hexdigest() )
print ( "key_hash + checksum = \t" + key_hash + ' ' + checksum )
print ( "bitcoin address = \t" + base58.b58encode( bytes(bytearray.fromhex(key_hash + checksum)) ) )

请原谅我问;我忘了在问题中添加我到目前为止的代码,但是更新了它。我是一个新手“开发人员”,正在尽我最大的努力去了解它。我的印象是我的问题很具体。如果不够具体,请说明您使用的是哪个ecdsa模块?谢谢您的回复!我使用的是ecdsa 0.13(全名为:ecdsa-0.13+26.gc877639-py3.6.egg)。好的,在这个过程中有5-10个步骤。你到底想问哪一个?为什么?对不起,我问了你一些愚蠢的问题。我只想告诉你,我真的很感激你花时间自愿帮助我。我会尽量具体一点,不要浪费你的时间。正如你已经注意到的,我两周前开始编写代码,每天花10多个小时。只是爱它到目前为止,想学习所有!相信我,我确实搜索过:)我的问题:我现在有公开密钥了。我需要执行sha256哈希,但在Python3.6中找不到任何示例或清晰的文档说明如何执行此操作。我不仅仅想使用ext.lib。因为我想学习。