I'm trying to get Elliptic Curve Diffie Hellman to work on a JavaCard (version 2.2.1).
On the JavaCard, I have the following code right now:
byte temp[] = new byte[100];
byte secret[] = new byte[100];
byte size = buf[ISO7816.OFFSET_LC];
Util.arrayCopy(buf, ISO7816.OFFSET_CDATA, temp, (byte) 0, size);
// the public key is in temp
short len = dh.generateSecret(temp, (byte) 0, size, secret, (byte) 0);
Util.arrayCopy(temp, (byte) 0, buf, ISO7816.OFFSET_CDATA, size);
//Util.arrayCopy(secret, (byte) 0, buf, ISO7816.OFFSET_CDATA, len);
apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, size);
And I initialize dh
as follows:
keyPair = new KeyPair(KeyPair.ALG_EC_FP, KeyBuilder.LENGTH_EC_F2M_163);
keyPair.genKeyPair();
dh = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH, false);
dh.init(keyPair.getPrivate());
All of this seems to work, except for the dh.generateSecret
call, where the applet simply seems to crash. If I leave the call out, and return other data, that works nicely. In which I import the data that is sent by the terminal. In the terminal, I have the following:
// generate an ecdh keypair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(163);
KeyPair keyPair = keyGen.generateKeyPair();
// initialize DH
KeyAgreement dh = KeyAgreement.getInstance("ECDH");
dh.init(keyPair.getPrivate());
//byte encKey[] = keyPair.getPublic().getEncoded();
// X9.62 encoding, no compression
int qLength = (163+7)/8;
byte[] xArr = ((ECPublicKey) keyPair.getPublic()).getW().getAffineX().toByteArray();
byte[] yArr = ((ECPublicKey) keyPair.getPublic()).getW().getAffineY().toByteArray();
byte[] enc2 = new byte[1+2*qLength];
enc2[0] = (byte) 0x04;
System.arraycopy(xArr, 0, enc2, qLength - xArr.length, xArr.length);
System.arraycopy(yArr, 0, enc2, 2* qLength - yArr.length, yArr.length);
byte res[] =send((byte) 0x00, enc2).getData();
I have tried several things. Right now, the code that sends the public key tries to encode it in X9.62 encoding (uncompressed) as specified by the JavaCard docs. However, I've also tried the default encode
method, which gives exactly the same result.
I don't seem to be able to get any error out of the JavaCard about what is going wrong. Does anyone know what is going wrong? Or does anyone have a working example on how to do a key-exchange on a JavaCard?