Reputation: 697
Below, you see a java card program that returns "Hello Word" when it receive APDU Command =8000000000
(its source)
package helloWorldPackage;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.Util;
public class HelloWorldApplet extends Applet
{
private static final byte[] helloWorld = {(byte)'H',(byte)'e',(byte)'l',(byte)'l',(byte)'o',(byte)' ',(byte)'W',(byte)'o',(byte)'r',(byte)'l',(byte)'d',};
private static final byte HW_CLA = (byte)0x80;
private static final byte HW_INS = (byte)0x00;
public static void install(byte[] bArray, short bOffset, byte bLength)
{
new HelloWorldApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
}
public void process(APDU apdu)
{
if (selectingApplet())
{
return;
}
byte[] buffer = apdu.getBuffer();
byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);
if (CLA != HW_CLA)
{
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
}
switch ( INS )
{
case HW_INS:
getHelloWorld( apdu );
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void getHelloWorld( APDU apdu)
{
byte[] buffer = apdu.getBuffer();
short length = (short) helloWorld.length;
Util.arrayCopyNonAtomic(helloWorld, (short)0, buffer, (short)0, (short) length);
apdu.setOutgoingAndSend((short)0, length);
}
}
I understand it, but I can't understand why the programmer used &0XFF
in the lines :
byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);
Why he normally doesn't use the below line instead?
byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA]);
byte INS = (byte) (buffer[ISO7816.OFFSET_INS]);
And also in the line :
ew HelloWorldApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
What does he mean by the +1
?
Upvotes: 1
Views: 1837
Reputation: 94038
Although we cannot see intent of an author, the line:
byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
is 100% equivalent to:
byte CLA = buffer[ISO7816.OFFSET_CLA];
Java does often use integers as result of operations, and because Java Card usually does not support int
values, it is often needed to cast to byte
or short
. I can only guess that the & 0xFF
and cast are present because of an over-enthusiastic attempt to get rid of intermediate int
values. It could also be a bad attempt to get Java to support unsigned bytes.
The register
method expects the instance AID. That AID is within the user parameters given during the Global Platform INSTALL for INSTALL
, but it is preceded by a byte containing the length of the AID (between 5 and 15, inclusive). So the + 1
is to skip that length byte - which is in turn present at the last argument of the register
method: bArray[bOffset]
.
Upvotes: 5