2

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?

Frank Kong
  • 645
  • 1
  • 6
  • 16

2 Answers2

6

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;
}
Mikhail Vladimirov
  • 7,313
  • 1
  • 23
  • 38
pyang
  • 381
  • 2
  • 4
5

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);
Mikhail Vladimirov
  • 7,313
  • 1
  • 23
  • 38
Frank Kong
  • 645
  • 1
  • 6
  • 16