Jijo
Jijo

Reputation: 107

Compress a ethereum public key using java spring boot

I have generated a private-public key pair using the web3j library.

ECKeyPair ecKeyPair = Keys.createEcKeyPair();
BigInteger publicKey = ecKeyPair.getPublicKey();

This returns an uncompressed form of the public key. I wanted to convert the same to a compressed format to generate the wallet using the below website.

https://lab.miguelmota.com/ethereum-public-key-to-address/example/

I know we can create the wallet directly using the Keypair, but I need this to work on the above website when I paste the public key.

I am using web3j version 5.0.0, and there is no built-in method to compress the public key.

Are there any other libraries or methods we can use to achieve the same

Upvotes: 1

Views: 301

Answers (1)

John Williams
John Williams

Reputation: 5460

Try this for compressed public key - info from here

DeterministicSeed seed = new DeterministicSeed("some seed code here", null, "", 1409478661L);
DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).build();
DeterministicKey addrKey = chain.getKeyByPath(HDUtils.parsePath("M/44H/60H/0H/0/0"), true);
System.out.println("Address: " + Keys.getAddress(Sign.publicKeyFromPrivate(addrKey.getPrivKey())));     // mapper();
System.out.println("Uncompressed public key: " + Sign.publicKeyFromPrivate(addrKey.getPrivKey()).toString(16));
System.out.println("Compressed key: " + addrKey.getPublicKeyAsHex());

-- Output --

Address: 97f2582fec180600268ebae9a0052e676d876c27
Uncompressed public key: 37efe8e46dc39bee0f099871de99fe68a931730c02ef2918f832f30572b3f1a54f8d52fcaea129e31ac836063e2c432aac815cb86664165d1a226fe51a851d47
Compressed key: 0337efe8e46dc39bee0f099871de99fe68a931730c02ef2918f832f30572b3f1a5

Dependencies are as follows:

import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDUtils;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.mapstruct.AfterMapping;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.Sign;

    <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>crypto</artifactId>
        <version>3.3.1-android</version>
    </dependency>
    <dependency>
        <groupId>org.bitcoinj</groupId>
        <artifactId>bitcoinj-core</artifactId>
        <version>0.16.2</version>
    </dependency>

Upvotes: 1

Related Questions