/* *********************************************************** * Smart Cards: Toward a Modern Run-time Platform * ETH Zurich, WS 2005/2006 * * Exercise 1 - Solution *************************************************************/ package exercise1; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.Util; public class Calculator extends Applet { public static void install(byte[] bArray, short bOffset, byte bLength) { // GP-compliant JavaCard applet registration new Calculator().register(bArray, (short) (bOffset + 1), bArray[bOffset]); } private static final byte[] CALC = { (byte) 'c', (byte) 'a', (byte) 'l', (byte) 'c', (byte) 'u', (byte) 'l', (byte) 'a', (byte) 't', (byte) 'o', (byte) 'r' }; public void process(APDU apdu) { // Good practice: Return 9000 on SELECT if (selectingApplet()) { return; } byte[] buf = apdu.getBuffer(); switch (buf[ISO7816.OFFSET_INS]) { case (byte) 0x00: apdu.setOutgoingAndSend((short) 0, Util.arrayCopy(CALC, (short) 0, buf, (short) 0, (short) CALC.length)); return; // return here so we won't try to send again case (byte) 0x02: buf[0] = (byte) (buf[ISO7816.OFFSET_P1] + buf[ISO7816.OFFSET_P2]); break; case (byte) 0x04: buf[0] = (byte) (buf[ISO7816.OFFSET_P1] - buf[ISO7816.OFFSET_P2]); break; case (byte) 0x06: buf[0] = (byte) (buf[ISO7816.OFFSET_P1] * buf[ISO7816.OFFSET_P2]); break; case (byte) 0x08: if (buf[ISO7816.OFFSET_P2] == 0) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } buf[0] = (byte) (buf[ISO7816.OFFSET_P1] / buf[ISO7816.OFFSET_P2]); break; case (byte) 0x0a: short n = (short) (ISO7816.OFFSET_CDATA + apdu .setIncomingAndReceive()); byte sum = 0; while (n-- > ISO7816.OFFSET_CDATA) { sum += buf[n]; } buf[0] = sum; break; default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); } apdu.setOutgoingAndSend((short) 0, (short) 1); } }