javabitcoinbitcoinj

BitcoinJ generate address from private key


I'm facing an issue regarding generating address from private key.

I got the master private key from electrum as well as from bitcoin core that is starts from

xprv9s21xxxxxxxxxxxxxxxxxxxxxxxxxxxx

in bitcoinJ:

ECKey key=ECKey.fromPrivate(prv); // it accepts bytes[] or BigInteger

how can i convert 9s21xxxxxxxxxxxxxxxxx into bytes[] or BigInteger.

Try:

String prvkey=9s21xxxxxxxxxxxxxxxxxxxxx
BigInteger bytes=new BigInteger(priv,16);

it throws exception as it can't convert due to number format.

Try 2:

byte[] bytes=prvkey.getBytes(StandardCharsets.UTF_16);

it generates valid address from ECKey and i send transaction to that address via electrum. but wallet didn't receive money. Don't know where the money gone.

what should i do to convert master private key into BigInteger or bytes[]

PS: I'm beginner in cryptocurrency


Solution

  • Convert string private key into bytes[]:

    ECKey key = ECKey.fromPrivate(prv.getBytes());
    

    Or, convert string private key into BigInteger:

    BigInteger privKey = Base58.decodeToBigInteger(prv);
    ECKey key = ECKey.fromPrivate(privKey);
    

    Example from bitcoinj's github repo