Search code examples
phpsha256bitcoin

Using PHP to convert Bitcoin Private Key but get wrong SHA256?


https://en.bitcoin.it/wiki/Wallet_import_format

Trying to follow this example here to do this in PHP, but I get stuck at step 3.

I can't seem to get the same SHA256 hash.

I take the extended key from step 2 800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D

and SHA256 it.

I should get 8147786C4D15106333BF278D71DADAF1079EF2D2440A4DDE37D747DED5403592 according to step 3 but I just get E2E4146A36E9C455CF95A4F259F162C353CD419CC3FD0E69AE36D7D1B6CD2C09

What am I doing wrong?


Solution

  • This is because you are hashing the literal string

    "800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D"
    

    This is not what what needs to happen. This is a string of bytes. It's in HEX format just to make viewing it easier. In reality, this represents a binary string. That's what you need to be hashing.

    hex2bin is your friend here.

    <?php
    $hex = '800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D';
    echo hash('sha256', hex2bin($hex));
    

    DEMO: https://eval.in/69440

    Another example:

    <?php
    $key = '0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D';
    $binKey = hex2bin($key);
    
    $binKey = hex2bin(80).$binKey;
    
    echo hash('sha256', $binKey);
    

    DEMO: https://eval.in/69443