Reputation: 1372
I am new to java ecc encryption. So I got ECC public key data array from java card.the size is 49 byte length. So I need to generate Eccpublic key. So I have created public key. but it gives error:
java.security.spec.InvalidKeySpecException: encoded key spec not recognised
This is my code. How to generate Eccpublickey using data array?
byte[] pub = new byte[] {
/*(Public data) 49 length byte ARRAY
*/
};
System.out.println("Length :" + pub.length);
X509EncodedKeySpec ks = new X509EncodedKeySpec(pub);
KeyFactory kf;
try {
kf = KeyFactory.getInstance("ECDH");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return;
}
ECPublicKey remotePublicKey;
try {
remotePublicKey = (ECPublicKey) kf.generatePublic(ks);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
return;
} catch (ClassCastException e) {
e.printStackTrace();
return;
}
System.out.println(remotePublicKey);
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Views: 1657
Reputation: 6288
The Java Card key is encoded in plain text form. I tried to use mostly plain Java, but the decoding process from the byte array representation requires still BouncyCastle's ECPointUtil
. Maybe there is a built-in way to do this, but I have not come across one.
The format is simple: It starts with 04
and then the x
, y
coordinates are each on 32 bytes and can be used with a positive BigInteger
when e.g. secp256r1
is used.
Example:
042b495a9b4142dc317624626ad108d4896c12a97af1a1372e9a7b0f29adcaeb49dee377c97fbb17b61480e857f5ce72408488e2763619159d032d3be091266dd6
BigInteger x = new BigInteger(1, pubKey, 1, 32)
BigInteger y = new BigInteger(1, pubKey, 32, 32)
The tricky part is the use of AlgorithmParameters
which is simple but in general an unknown API.
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance("EC");
algorithmParameters.init(ecGenParameterSpec);
ECParameterSpec ecParameterSpec = algorithmParameters.getParameterSpec(ECParameterSpec.class);
ECPoint point = ECPointUtil.decodePoint(ecParameterSpec.getCurve(), pubKey);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(point, ecParameterSpec);
ECPublicKey ecPublicKey = (ECPublicKey) keyFactory.generatePublic(ecPublicKeySpec);
Upvotes: 1
Reputation: 1372
The reason is the code not working the keyspec can't use in ECC.so i found how to use ECPublicKeySpec
in ECC.In here it has good explanation.https://bitcointalk.org/index.php?topic=2899.0;wap2 Thanks.
Upvotes: 0