繁体   English   中英

从文件文本转换比特币私钥

[英]Convert Bitcoin private key from file text

朋友们下午好,我刚开始学习python,我找到了适合我需要的代码,但是在输出的路上所有东西都在一行中同步,帮助我解决这个问题。

import ecdsa
import hashlib
import base58


with open("my_private_key.txt", "r") as f:    #Input file path
  for line in f:

              #Convert hex private key to bytes
     private_key = bytes.fromhex(line)      

              #Derivation of the 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()

             #Hashes of public key
     sha256_1 = hashlib.sha256(public_key)
     ripemd160 = hashlib.new("ripemd160")
     ripemd160.update(sha256_1.digest())

             #Adding prefix to identify Network
     hashed_public_key = bytes.fromhex("00") + ripemd160.digest()

             #Checksum calculation
     checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
     checksum = checksum_full[:4]

             #Adding checksum to hashpubkey         
     bin_addr = hashed_public_key + checksum

             #Encoding to address
     address = str(base58.b58encode(bin_addr))
     final_address = address[2:-1]

     print(final_address)

     with open("my_addresses.txt", "a") as i:
        i.write(final_address)

print在写完所有 arguments 后写一个尾随换行符。 write不会; 你必须自己提供。

with open("my_addresses.txt", "a") as i:
    i.write(final_address + "\n")

或者,您可以使用print

with open("my_addresses.txt", "a") as i:
    print(final_address, file=i)

忽略它的许多关键字 arguments, print的定义类似于

def print(*args, end='\n', sep=' ', file=sys.stdout):
    file.write(sep.join(args))
    file.write(end)
    

另请注意,您无需重复打开 output 文件。 您可以在输入的同时打开它,并在循环期间保持打开状态。

with open("my_private_key.txt", "r") as f, \
     open("my_addresses.txt", "a") as i:
    for line in f:
        ...
        print(final_address, file=i)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM