Private-Key

如何使用 ECKey 獲取壓縮的公鑰

  • January 20, 2021

這裡有一些java程式碼。我需要更改什麼才能在 getPublicAddress 中獲取壓縮的公共地址?

import com.google.bitcoin.core.Address;
import com.google.bitcoin.core.ECKey;
import com.google.bitcoin.params.MainNetParams;
import org.spongycastle.crypto.digests.RIPEMD160Digest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtil {

   public static byte[] RIPEMD160(byte[] input) {
       RIPEMD160Digest d = new RIPEMD160Digest();

       d.update(input, 0, input.length);

       byte[] o = new byte[d.getDigestSize()];

       d.doFinal(o, 0);

       return o;
   }

   public static byte[] SHA256(byte[] input) {
       byte[] hash = null;

       try {
           MessageDigest md = MessageDigest.getInstance("SHA-256");
           md.update(input);
           hash = md.digest();
       } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
       }

       return hash;
   }

   public static ECKey createAddress(byte[] secret) {
       byte[] hash = SHA256(secret);

       ECKey key = new ECKey(hash, null);

       return key;
   }

   public static String getPublicAddress(String input) {
       ECKey address = createAddress(input.getBytes());

       byte[] hash160 = RIPEMD160(SHA256(address.getPubKey()));

       Address addr = new Address(MainNetParams.get(), hash160);

       return addr.toString();
   }

}
Address address = new Address(params, dk.decompress().getPubKeyHash());

其中 dk 是 DeterministicKey

要麼

key.decompress().getPubKey();

其中 key 是 ECKey

如果有人想在他們的程式碼中實現壓縮:

private static final String EVEN = "02";
private static final String ODD = "03";

public String compressPublicKey(String toCompress) {
   if (Integer.parseInt(toCompress.substring(128, 130), 16) % 2 == 0)
       return  EVEN + toCompress.substring(2, 66);
   return ODD + toCompress.substring(2, 66);
} 

引用自:https://bitcoin.stackexchange.com/questions/68064