最全面的比特币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

    $ python key-to-address-ecc-example.py
    Private Key (hex) is:
     3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6
    Private Key (decimal) is:
     26563230048437957592232553826663696440606756685920117476832299673293013768870
    Private Key (WIF) is:
     5JG9hT3beGTJuUAmCQEmNaxAuMacCTfXuw1R3FCXig23RQHMr4K
    Private Key Compressed (hex) is:
     3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa601
    Private Key (WIF-Compressed) is:
     KyBsPXxTuVD82av65KZkrGrWi5qLMah5SdNq6uftawDbgKa2wv6S
    Public Key (x,y) coordinates is:
     (41637322786646325214887832269588396900663353932545912953362782457239403430124L,
     16388935128781238405526710466724741593761085120864331449066658622400339362166L)
    Public Key (hex) is:
     045c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec↵
    243bcefdd4347074d44bd7356d6a53c495737dd96295e2a9374bf5f02ebfc176
    Compressed Public Key (hex) is:
     025c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec
    Bitcoin Address (b58check) is:
     1thMirt546nngXqyPEz532S8fLwbozud8
    Compressed Bitcoin Address (b58check) is:
     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

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