ECC 密钥对 - 如何打印私钥?
ECC key pair - how to print private key?
我使用 secp192r1 曲线实现 "Key Pair Generation"。但是私钥没有像public key.
那样以字符串形式显示
这是我的代码:
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());
}
}
下面的代码将输出 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);
}
我使用 secp192r1 曲线实现 "Key Pair Generation"。但是私钥没有像public key.
那样以字符串形式显示这是我的代码:
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());
}
}
下面的代码将输出 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);
}