Skip to content
Advertisement

Get compressed public key and the bitcoin address using only the private key in BitcoinJ

I already know to get the public key from base58 encoded private key using an ECKey object in BitcoinJ. See the example code.

String base58PrivateKeyString = "---------------------private key here---------------------";
NetworkParameters params = MainNetParams.get();
ECKey key;

if (base58PrivateKeyString.length() == 51 || base58PrivateKeyString.length() == 52) {
    DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, base58PrivateKeyString);
    key = dumpedPrivateKey.getKey();
} else {
    BigInteger privKey = Base58.decodeToBigInteger(base58PrivateKeyString);
    key = ECKey.fromPrivate(privKey);
}

// I'm not sure that I'm correct. Is this the correct compressed public key?
String publicKey = Hex.toHexString(ECKey.publicKeyFromPrivate(Base58.decodeToBigInteger(base58PrivateKeyString), true));

String bitcoin address; // I don't know how to get

But I still don’t understand to take the compressed private key and the bitcoin address from the “key” object. I tried some with compressPoint() method. But I didn’t succeed.

Advertisement

Answer

In order to get the compressed public key for a qualified WIF just use the following function in the bitcoinJ library.

String publicKey = key.getPublicKeyAsHex();
Advertisement