1

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?

2

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;
}
1

I posted my own answer here in case someone else has the question. Web3j provides a ECKeyPair as util to process key and address conversion. Please see codes below:

String privateKey = "{your private key}";
Credentials cs = Credentials.create(privateKey);

String privateKey = cs.getEcKeyPair().getPrivateKey().toString(16);
String publicKey = cs.getEcKeyPair().getPublicKey().toString(16);
String addr = cs.getAddress();

System.out.println("Private key: " + privateKey);
System.out.println("Public key: " + publicKey);
System.out.println("Address: " + addr);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.