I am writing a JavaCard 2.2.1 applet which do some heavy mathematical processing on the input data and return the result to computer. My code has many for and while loops. The problem is that when I call the card from the PC, the connection to the card not wait for the card to finish all process, and return with a PC/SC protocol error. I use PCSC library in C# for communicating to the card from PC, and get this error: A communication error with the smart card has been detected.
To reproduce the problem, I have prepared a test applet with some dummy calculations:
package my.testapplet;
import javacard.framework.*;
public class TestApplet extends Applet
{
public static void install(byte[] bArray, short bOffset, byte bLength)
{
new TestApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
}
public void process(APDU apdu)
{
if (selectingApplet())
{
return;
}
byte[] buf = apdu.getBuffer();
short result = 0;
if (buf[ISO7816.OFFSET_CLA] == ISO7816.CLA_ISO7816) {
switch (buf[ISO7816.OFFSET_INS])
{
case (byte)0x00:
{
short temp1 = 0;
short temp2, temp3 = 0;
while(temp1 < 30000) {
temp1++;
temp2 = 0;
while(temp2 < 30000) {
temp2++;
if(temp2 > 0) {
temp3 = (short)(temp1 * 2 + 1);
}
}
}
result = 100;
}
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
buf[0] = (byte) (result & 0xff);
buf[1] = (byte) (result >>> 8);
apdu.setOutgoingAndSend((short) 0, (short) 2);
} else {
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
}
I have tested this applet on 3 different java card models (from different vendors), all with the same result. Also I have to note that there is no problem when running the code in the java card simulator. The problem occurs on a real physical java card. It seems the virtual machine on the java card false detects some loops in running code as infinite loop, and breaks the connection.
I have no idea on this problem. Have any one similar experiences with java card? Any idea on why this behavior occurs on java card and how to resolve it? Is there any special instruction/configuration on java card to disable this behavior and wait for the java card to prepare and return the result?