I am executing the following command to generate ecdsa keypair on my machine:
openssl ecparam -genkey -name secp256k1 -noout -outform DER -out private.key
and on executing this next command openssl ec -inform DER -in private.key -noout -text
, I get the following output:
read EC key
Private-Key: (256 bit)
priv:
//private key
pub:
04:64:0a:f7:e6:e1:a9:7f:d3:b2:ec:ad:f1:41:96:
ee:c1:c2:e7:02:4a:54:42:ab:e8:da:9f:88:e1:02:
46:aa:32:91:38:b5:9e:37:fc:96:d9:36:02:07:de:
74:59:c4:a8:e0:2b:21:3a:d4:70:7d:5e:92:54:22:
65:80:0f:df:fd
ASN1 OID: secp256k1
Now what I'm interested in is the above public key without colons i.e. 04640af7e6e1a97fd3b2ecadf14196eec1c2e7024a5442abe8da9f88e10246aa329138b59e37fc96d9360207de7459c4a8e02b213ad4707d5e92542265800fdffd
. I need to send to this public key to an api call which validates whether the key is valid or not. The key generated by openssl
when sent with the api call is accepted by the server as valid.
But the public ecdsa key generated in java when sent with the api call is rejected. I'm using following code to generate keypair
public KeyPair getECDSAKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", "SC");
ECGenParameterSpec spec = new ECGenParameterSpec("secp256k1");
keyPairGenerator.initialize(spec, new SecureRandom());
return keyPairGenerator.generateKeyPair();
}
public String getHexPublicKeyString(KeyPair keypair) {
PublicKey publicKey = keypair.getPublic();
return Hex.toHexString(publicKey.getEncoded());
}
My question is how can I generate same type of ECDSA keypair as generated by the OpenSSL? And what is the difference between the keys generated by OpenSSL and the code generated by java such that key generated by OpenSSL is accepted whereas key generated by java is rejected?
I was able to generate the required public through following method using SpongyCastle:
public static String getHexEncodedPublicKey(PublicKey publicKey) throws IOException, InvalidKeyException {
ECPublicKeyParameters ecPublicKeyParameters
= (ECPublicKeyParameters) ECUtil.generatePublicKeyParameter(publicKey);
byte[] encoded = ecPublicKeyParameters.getQ().getEncoded(false);
return Hex.toHexString(encoded);
}