• 4.4 用Python实现密钥和比特币地址

    4.4 用Python实现密钥和比特币地址

    最全面的比特币Python库是 Vitalik Buterin写的 pybitcointools。在例4-5中,我们使用pybitcointools库(导入 为“bitcoin”)来生成和显示不同格式的密钥和比特币地址。

    例4-5 使用pybitcointools库的密钥和比特币地址的生成和格式化

    link:code/key-to-address-ecc-example.py[]

    例4-6是上例代码运行输出的内容。

    例4-6 运行key-to-address-ecc-example.py

    1. $ python key-to-address-ecc-example.py
    2. Private Key (hex) is:
    3. 3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6
    4. Private Key (decimal) is:
    5. 26563230048437957592232553826663696440606756685920117476832299673293013768870
    6. Private Key (WIF) is:
    7. 5JG9hT3beGTJuUAmCQEmNaxAuMacCTfXuw1R3FCXig23RQHMr4K
    8. Private Key Compressed (hex) is:
    9. 3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa601
    10. Private Key (WIF-Compressed) is:
    11. KyBsPXxTuVD82av65KZkrGrWi5qLMah5SdNq6uftawDbgKa2wv6S
    12. Public Key (x,y) coordinates is:
    13. (41637322786646325214887832269588396900663353932545912953362782457239403430124L,
    14. 16388935128781238405526710466724741593761085120864331449066658622400339362166L)
    15. Public Key (hex) is:
    16. 045c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec
    17. 243bcefdd4347074d44bd7356d6a53c495737dd96295e2a9374bf5f02ebfc176
    18. Compressed Public Key (hex) is:
    19. 025c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec
    20. Bitcoin Address (b58check) is:
    21. 1thMirt546nngXqyPEz532S8fLwbozud8
    22. Compressed Bitcoin Address (b58check) is:
    23. 14cxpo3MBCYYWCgF74SWTdcmxipnGUsPw3

    例4-7是另外一个示例,使用的是Python ECDSA库来做椭圆曲线计算而非bitcoin的库。

    例4-7 用于比特币密钥的椭圆曲线算法演示脚本

    link:code/ec-math.py[]

    例4-8是上述脚本的输出。

    警告:例4-7中使用的os.urandom,表明的是底层操作系统的加密安全随机数生成器(cryptographically secure random number generator (CSRNG) )。注意:根据操作系统的不同,os.urandom的实现缺乏足够的安全性,也可能没有正确的种子,并且不适合产生高质量的比特币密钥。

    例4-8 安装Python ECDSA 库,运行脚本running the ec_math.py

    1. $ # Install Python PIP package manager
    2. $ sudo apt-get install python-pip
    3. $ # Install the Python ECDSA library
    4. $ sudo pip install ecdsa
    5. $ # Run the script
    6. $ python ec-math.py
    7. Secret: 38090835015954358862481132628887443905906204995912378278060168703580660294000
    8. EC point: (70048853531867179489857750497606966272382583471322935454624595540007269312627, 105262206478686743191060800263479589329920209527285803935736021686045542353380)
    9. BTC public key: 029ade3effb0a67d5c8609850d797366af428f4a0d5194cb221d807770a1522873