公钥比特币公式的私钥?Python 3.0? [英] private key to public key bitcoin formula? Python 3.0?

查看:96
本文介绍了公钥比特币公式的私钥?Python 3.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Python的新手,请尝试找出私钥(比特币)转换为公钥的公式.我从Github找到了一个代码,并将其翻译为Python 3.0.但这仍然行不通,我不知道问题出在哪里.请帮我修复它.

i am newbie with Python and try to find out the private key (Bitcoin) to public key formula. I found a code from Github and translated it to Python 3.0. But it still does not work, i dont know where the problem is. Please help me to fix it.

# Below are the public specs for Bitcoin's curve - the secp256k1
import binascii
Pcurve = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 -1 # The proven prime
N=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 # Number of points in the field
Acurve = 0; Bcurve = 7 # These two defines the elliptic curve. y^2 = x^3 + Acurve * x + Bcurve
Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424
GPoint = (Gx,Gy) # This is our generator point. Trillions of dif ones possible

#Individual Transaction/Personal Information
privKey = 0xA0DC65FFCA799873CBEA0AC274015B9526505DAAAED385155425F7337704883E #replace with any private key

def modinv(a,n=Pcurve): #Extended Euclidean Algorithm/'division' in elliptic curves
    lm, hm = 1,0
    low, high = a%n,n
    while low > 1:
        ratio = high/low
        nm, new = hm-lm*ratio, high-low*ratio
        lm, low, hm, high = nm, new, lm, low
    return lm % n

def ECadd(a,b): # Not true addition, invented for EC. Could have been called anything.
    LamAdd = ((b[1]-a[1]) * modinv(b[0]-a[0],Pcurve)) % Pcurve
    x = (LamAdd*LamAdd-a[0]-b[0]) % Pcurve
    y = (LamAdd*(a[0]-x)-a[1]) % Pcurve
    return (x,y)

def ECdouble(a): # This is called point doubling, also invented for EC.
    Lam = ((3*a[0]*a[0]+Acurve) * modinv((2*a[1]),Pcurve)) % Pcurve
    x = (Lam*Lam-2*a[0]) % Pcurve
    y = (Lam*(a[0]-x)-a[1]) % Pcurve
    return (x,y)

def EccMultiply(GenPoint,ScalarHex): #Double & add. Not true multiplication
    if ScalarHex == 0 or ScalarHex >= N: raise Exception("Invalid Scalar/Private Key")
    ScalarBin = str(bin(ScalarHex))[2:]; #print(ScalarBin);
    Q=GenPoint
    for i in range (1,len(ScalarBin)): # This is invented EC multiplication.
        Q=ECdouble(Q);  print(("DUB", Q[0])); print(i)
        if ScalarBin[i] == "1":
            Q=ECadd(Q,GenPoint); print(("ADD", Q[0])); print()
    return (Q)

PublicKey = EccMultiply(GPoint,privKey);
print(); print("******* Public Key Generation *********"); 
print()
print("the private key:"); 
print((hex(privKey))); print()
print("the uncompressed public key (not address):"); 
print(PublicKey); print()
print("the uncompressed public key (HEX):"); 
print(("04" + "%064x" % PublicKey[0] + "%064x" % PublicKey[1])); 
print();
print("the official Public Key - compressed:"); 
if PublicKey[1] % 2 == 1: # If the Y value for the Public Key is odd.
    print(("03"+str(hex(PublicKey[0])[2:-1]).zfill(64)))
else: # Or else, if the Y value is even.
    print(("02"+str(hex(PublicKey[0])[2:-1]).zfill(64)))

推荐答案

可以随意检查此脚本,它经过了扩展,但出于教育目的,还引入了一些导入,以显示所有过程.您将从给定的机密中以十六进制值获取压缩和未压缩的公共密钥.

Feel free to check this script, it is more extended, but with a couple of imports for an educational point of view, to show all the process. You will get compressed and uncompressed public keys from a given secret in hexadecimal value.

首先,脚本将以十六进制形式获取未压缩的私钥和压缩的私钥:

First, the script will get uncompressed private key and compressed private key in hex:

'04417A55413D948D79F5194F1F2CD670F078CB7F6D3A2F2B12E8CDF9A3268CAD3BAAA3251D2587D4E57ACBCE7991B72355EA33C44DBCF260D09B6C921879A61AA4'
'02417A55413D948D79F5194F1F2CD670F078CB7F6D3A2F2B12E8CDF9A3268CAD3B'

然后它将同时获得未压缩的公共密钥和压缩的公共密钥.

Then it will get both public uncompressed and compressed public keys.

代码:

#!/usr/bin/python3
from hashlib import sha256, new
import binascii

PCURVE = 2 ** 256 - 2 ** 32 - 2 ** 9 - 2 ** 8 - 2 ** 7 - 2 ** 6 - 2 ** 4 - 1  # The proven prime
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141  # Number of points in the field
ACURVE = 0
BCURVE = 7  # These two defines the elliptic curve. y^2 = x^3 + Acurve * x + Bcurve
Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424
GPOINT = (Gx, Gy)  # This is our generator point. Trillions of dif ones possible


def modinv(a: int, n: int = PCURVE):
    # MAXIMO COMUN DIVISOR: Extended Euclidean Algorithm/'division' in elliptic curves
    lm, hm = 1, 0
    resto = a % n
    high = n
    while resto > 1:
        ratio = high // resto
        nm = hm - lm * ratio
        new = high - resto * ratio
        lm, resto, hm, high = nm, new, lm, resto
    return lm % n


def ECadd(a, b):  # Not true addition, invented for EC. Could have been called anything.
    LamAdd = ((b[1] - a[1]) * modinv(b[0] - a[0], PCURVE)) % PCURVE
    x = (LamAdd * LamAdd - a[0] - b[0]) % PCURVE
    y = (LamAdd * (a[0] - x) - a[1]) % PCURVE
    return x, y


def ECdouble(a):  # This is called point doubling, also invented for EC.
    Lam = ((3 * a[0] * a[0] + ACURVE) * modinv((2 * a[1]), PCURVE)) % PCURVE
    x = (Lam * Lam - 2 * a[0]) % PCURVE
    y = (Lam * (a[0] - x) - a[1]) % PCURVE
    return x, y


def EccMultiply(gen_point: tuple, scalar_hex: int):  # Double & add. Not true multiplication
    if scalar_hex == 0 or scalar_hex >= N:
        raise Exception("Invalid Scalar/Private Key")
    ScalarBin = str(bin(scalar_hex))[2:]  # string binario sin el comienzo 0b
    Q = gen_point  # esto es una tupla de dos integer del punto de generacion de la curva
    for i in range(1, len(ScalarBin)):
        Q = ECdouble(Q)
        if ScalarBin[i] == "1":
            Q = ECadd(Q, gen_point)  #
    return Q


def private_to_hex_publics(hex_private_key: hex):
    public_key = EccMultiply(GPOINT, hex_private_key)
    public_uncompressed = f"04{hex(public_key[0])[2:].upper()}{hex(public_key[1])[2:].upper()}"

    if public_key[1] % 2 == 1:  # If the Y value for the Public Key is odd.
        public_compressed = ("03" + str(hex(public_key[0])[2:]).zfill(64).upper())
    else:  # Or else, if the Y value is even.
        public_compressed = ("02" + str(hex(public_key[0])[2:]).zfill(64).upper())
    return public_uncompressed, public_compressed


def hash_256_from_hex_string_like_bytes(hexstring: str):
    return sha256(bytes.fromhex(hexstring)).hexdigest()


def ripemd160_from_hex_string_like_bytes(hexstring: str):
    return new('ripemd160', bytes.fromhex(hexstring)).hexdigest()


def b58encode(hex_string, expected_length=None):
    v = binascii.unhexlify(hex_string)
    alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
    lev, number = 1, 0
    for char in reversed(v):
        number += lev * char
        lev = lev << 8  # 2^8
    string = ""
    while number:
        number, modulo = divmod(number, 58)
        string = alphabet[modulo] + string
    if not expected_length:
        return string
    elif len(string) != expected_length:
        raise Exception(f"b58encode: Expected length={expected_length} obtained length={len(string)}")
    else:
        return string


def sha256_get_checksum(hex_string_to_checksum):
    hasha1 = hash_256_from_hex_string_like_bytes(hex_string_to_checksum)
    # print("HashA1", hasha1)
    hasha2 = hash_256_from_hex_string_like_bytes(hasha1)
    # print("HashA2", hasha2)
    return hasha2[:8].upper()


def sha_ripe_digest(hex_string_to_checksum):
    hashc1 = hash_256_from_hex_string_like_bytes(hex_string_to_checksum)
    hashc2 = ripemd160_from_hex_string_like_bytes(hashc1)
    return hashc2.upper()


def wif_from_private(privkey: hex):
    # put 80 for bitcoin and concatenate with privkey
    prepend = "80"
    private_key_str = hex(privkey)[2:].zfill(64)
    prepended = (prepend + private_key_str).upper()
    compressed = (prepend + private_key_str + "01").upper()

    if len(prepended) != 66 or len(compressed) != 68:
        raise Exception("WIF conversion: Wrong prepended or compressed private key, length not 66")

    uncompressed_checksum = sha256_get_checksum(prepended)
    compressed_checksum = sha256_get_checksum(compressed)
    private_key_uncompressed_checksum = prepended + uncompressed_checksum
    private_key_compressed_checksum = compressed + compressed_checksum
    private_key_WIF_uncompressed_Base58 = b58encode(private_key_uncompressed_checksum, 51)
    private_key_WIF_compressed_Base58 = b58encode(private_key_compressed_checksum, 52)

    print("PREPENDED:\t\t\t\t", prepended)
    print("PRIV_UNCOMP+CHECKSUM:\t\t\t", private_key_uncompressed_checksum)
    print("Private_key_WIF_uncompressed_Base58:\t", private_key_WIF_uncompressed_Base58)
    print("PRIV_COMP+CHECKSUM:\t\t\t", private_key_compressed_checksum)
    print("Private_key_WIF_compressed_Base58:\t", private_key_WIF_compressed_Base58)
    return private_key_WIF_uncompressed_Base58, private_key_WIF_compressed_Base58


def hex_public_to_public_addresses(hex_publics):
    uncompressed = hex_publics[0]
    public_key_hashC_uncompressed = "00" + sha_ripe_digest(uncompressed)
    checksum = sha256_get_checksum(public_key_hashC_uncompressed)
    PublicKeyChecksumC = public_key_hashC_uncompressed + checksum
    public_address_uncompressed = "1" + b58encode(PublicKeyChecksumC, 33)
    print("Public address uncompressed:\t", public_address_uncompressed)

    compressed = hex_publics[1]
    PublicKeyVersionHashD = "00" + sha_ripe_digest(compressed)
    compressed_checksum = sha256_get_checksum(PublicKeyVersionHashD)
    PublicKeyChecksumC = PublicKeyVersionHashD + compressed_checksum
    public_address_compressed = "1" + b58encode(PublicKeyChecksumC, 33)
    print("Public address compressed:\t", public_address_compressed)
    return public_address_uncompressed, public_address_compressed


if __name__ == "__main__":
    privkey = 0xe41b45e722251672c01a28e4fada590471fea09f90d13b143033ed3a1107ef49
    print(f"PRIVATE KEY:\t {hex(privkey)[2:].zfill(64).upper()}")

    # Public hex test
    hex_publics = private_to_hex_publics(privkey)
    print(hex_publics)
    print()

    # WIF creation test
    wif = wif_from_private(privkey)
    print(wif)

    # Public keys
    public = hex_public_to_public_addresses(hex_publics)
    print(public)

该脚本的灵感来自于网站.

最后,您将获得两个未压缩和已压缩的公钥:

Finally you will obtain the two public keys, uncompressed and compressed:

'12sF1DbBbPaoNYrs28Qm7waiCcAVoF93Nn', '1BMKGYmgjrvmSDtvLZvKjyVMnbi6FLmcVi'

注意:它也会为您提供 WIF格式.

Note: it will give you the WIF format too.

完整输出:

PRIVATE KEY:     E41B45E722251672C01A28E4FADA590471FEA09F90D13B143033ED3A1107EF49
('04417A55413D948D79F5194F1F2CD670F078CB7F6D3A2F2B12E8CDF9A3268CAD3BAAA3251D2587D4E57ACBCE7991B72355EA33C44DBCF260D09B6C921879A61AA4', '02417A55413D948D79F5194F1F2CD670F078CB7F6D3A2F2B12E8CDF9A3268CAD3B')

PREPENDED:                               80E41B45E722251672C01A28E4FADA590471FEA09F90D13B143033ED3A1107EF49
PRIV_UNCOMP+CHECKSUM:                    80E41B45E722251672C01A28E4FADA590471FEA09F90D13B143033ED3A1107EF496CB6A884
Private_key_WIF_uncompressed_Base58:     5KYkFr9FMmBVcwjLbJinAw94b985tgyt4PL9Jhcjsk6J6ZRfxjM
PRIV_COMP+CHECKSUM:                      80E41B45E722251672C01A28E4FADA590471FEA09F90D13B143033ED3A1107EF4901070CD9AC
Private_key_WIF_compressed_Base58:       L4s7vXuQNe1KKeZsURDQNqxaqgrGb9U4MwZVf8GkEyCNTKyEk3iK
('5KYkFr9FMmBVcwjLbJinAw94b985tgyt4PL9Jhcjsk6J6ZRfxjM', 'L4s7vXuQNe1KKeZsURDQNqxaqgrGb9U4MwZVf8GkEyCNTKyEk3iK')
Public address uncompressed:     12sF1DbBbPaoNYrs28Qm7waiCcAVoF93Nn
Public address compressed:       1BMKGYmgjrvmSDtvLZvKjyVMnbi6FLmcVi

有关更多评论和数据,请检查:

For more comments and data check: this

这篇关于公钥比特币公式的私钥?Python 3.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆