Web3j – How to Get Public Key from Private Key

ethereumjweb3j

I am developing Dapp by web3j and I attempt to convert private key to public key. I found this question this question that provides a way converting private key to public key in class ECKey, but I need to also add Ethereumj core as dependency.

I am wondering if there is a method in web3j rather than ethereumj to convert private key to public key.

If there is not, why doesn't they add this logic as a function to web3j?

Best Answer

Yes, you can do it using following code

import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair; 

public static String getPublicKeyInHex(String privateKeyInHex) {
    BigInteger privateKeyInBT = new BigInteger(privateKeyInHex, 16);
    ECKeyPair aPair = ECKeyPair.create(privateKeyInBT);
    BigInteger publicKeyInBT = aPair.getPublicKey();
    String sPublickeyInHex = publicKeyInBT.toString(16);
    return sPublickeyInHex;
}
Related Topic