0

我使用 secp192r1 曲线实现“密钥对生成”。但是私钥没有像公钥那样以字符串形式显示。

在此处输入图像描述

这是我的代码:

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()); 
    }
}
4

1 回答 1

2

下面的代码将为 secp192r1 曲线输出 24 字节的私钥:

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);
}
于 2017-02-07T15:04:36.623 回答