0

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()); 
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
ThanhLam112358
  • 878
  • 1
  • 20
  • 51
  • Welcome to Stack Overflow! Please review our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to help you to ask a good question, and thus get a good answer. – Joe C Oct 30 '16 at 17:50

1 Answers1

2

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);
}
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114