bitcoin 秘密鍵の生成

import os
import binascii

private_key = os.urandom(32)
print(private_key)
print(binascii.hexlify(private_key))

32バイトの乱数を生成して、バイナリデータを16進数に変換

$ python3 wallet.py
b’W~\x9cj\xcc}\x0f1J\xab\xa6Hh\x87\xe7\xa6x2\xb1c,\xe9\x1dZp{R\xc3\x8e9-\xe2′
b’577e9c6acc7d0f314aaba6486887e7a67832b1632ce91d5a707b52c38e392de2′

公開鍵に楕円曲線暗号を使用します。
$ pip install ecdsa

import os
import ecdsa
import binascii

private_key = os.urandom(32)
public_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1).verifying_key.to_string()

print(binascii.hexlify(private_key))
print(binascii.hexlify(public_key))

y^2 = x^3 + 7 mod p

import os
import ecdsa
import binascii

private_key = os.urandom(32)
public_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1).verifying_key.to_string()

print(binascii.hexlify(private_key))
print(binascii.hexlify(public_key))

# public_key y-axis
public_key_y = int.from_bytes(public_key[32:], "big")

# create compressed public_key
if public_key_y % 2 == 0:
    public_key_compressed = b"\x02" + public_key[:32]
else:
    public_key_compressed = b"\x03" + public_key[:32]

print(binascii.hexlify(public_key_compressed))