[Ethereum] Generate Ethereum address from a private key

etherphpprivate-key

My question was first asked on stackoverflow but due lack of privileges I couldn't move it here directly.

I am trying to generate an Ethereum address based on a given private key following this "How are ethereum addresses generated?" and using this Keccak-256 Ethereum implementation. But it show this error:

Warning: openssl_pkey_get_details() expects parameter 1 to be resource, boolean given in /localweb/getethaddress.php on line 15

openssl_pkey_get_private error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long
openssl_pkey_get_private error:0D068066:asn1 encoding routines:ASN1_CHECK_TLEN:bad object header
openssl_pkey_get_private error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
openssl_pkey_get_private error:10092010:elliptic curve routines:d2i_ECPrivateKey:EC lib
openssl_pkey_get_private error:100DE08E:elliptic curve routines:OLD_EC_PRIV_DECODE:decode error
openssl_pkey_get_private error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long
openssl_pkey_get_private error:0D068066:asn1 encoding routines:ASN1_CHECK_TLEN:bad object header
openssl_pkey_get_private error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
openssl_pkey_get_private error:0907B00D:PEM 

routines:PEM_READ_BIO_PRIVATEKEY:ASN1 lib

My implementation:

<?php
    require_once 'keccak256.php';


    // Format the private key as PEM
    $header_private_key = "-----BEGIN EC PRIVATE KEY-----\n";
    $footer_private_key = "\n-----END EC PRIVATE KEY-----";
    //echo hex2bin("1a63b5c735d66d827f40f7d3a257da777cd7997d48bd5d319c36683c0ad3b1de");
    $eth_private_key = $header_private_key . "1a63b5c735d66d827f40f7d3a257da777cd7997d48bd5d319c36683c0ad3b1de" . $footer_private_key;

    // Load private key from a string
    $private_key = openssl_pkey_get_private($eth_private_key);
    var_dump($private_key);
    while ($msg = openssl_error_string())
        echo "openssl_pkey_get_private " . $msg . "<br />\n";

    // Get the Public key
    $_public_key = openssl_pkey_get_details($private_key)['key'];
    $eth_public_key = openssl_pkey_get_public($_public_key);

    // hash the public key
    $hash_public_key = Keccak256\Keccak256::hash($eth_public_key, 256);; 
    $eth_address = '0x' . substr($hash_public_key, -40);


    echo 'Your generated address: ' . $eth_address . '<br>';
    echo 'Myetherwallet address: 0x47180b59dd8c81f46186900bbd29cbf675b3fbd9';


    /*
        a generated address from Myetherwallet 40: 47180b59dd8c81f46186900bbd29cbf675b3fbd9
        private key 64: 1a63b5c735d66d827f40f7d3a257da777cd7997d48bd5d319c36683c0ad3b1de
    */
?>

Best Answer

There are some functions in web3p toolset, but I have no Idea if it will work.

https://github.com/web3p/ethereum-util/blob/0815348c3513e004d7dfa65ebeb31cda9d41f77e/src/Util.php#L133-L172