Search code examples
javaprivate-keyelliptic-curveecdsakey-pair

ECC key pair - how to print private key?


I implement "Key Pair Generation" using secp192r1 curve. But private key did not display in string form like public key.

enter image description here

Here is my code:

package lam.bk;
import java.security.*;
import java.security.spec.*;

public class ECCKeyGeneration {
    public static void main(String[] args) throws Exception {
        KeyPairGenerator kpg;
        kpg = KeyPairGenerator.getInstance("EC","SunEC");
        ECGenParameterSpec ecsp;
        ecsp = new ECGenParameterSpec("secp192r1");
        kpg.initialize(ecsp);

        KeyPair kp = kpg.genKeyPair();
        PrivateKey privKey = kp.getPrivate();
        PublicKey pubKey = kp.getPublic();

        System.out.println(pubKey.toString());
        System.out.println(privKey.toString()); 
    }
}

Solution

  • The code below will output 24 bytes private key for secp192r1 curve:

    private String getPrivateKeyAsHex(PrivateKey privateKey) {
    
        ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
        byte[] privateKeyBytes = new byte[24];
        writeToStream(privateKeyBytes, 0, ecPrivateKey.getS(), 24);
    
        return Hex.toHexString(privateKeyBytes);
    }
    
    private void writeToStream(byte[] stream, int start, BigInteger value, int size) {
        byte[] data = value.toByteArray();
        int length = Math.min(size, data.length);
        int writeStart = start + size - length;
        int readStart = data.length - length;
        System.arraycopy(data, readStart, stream, writeStart, length);
    }