1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
package pck_calculator;
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
{
private static final byte[] CALC = { //
(byte) 0x63, // c
(byte) 0x61, // a
(byte) 0x6c, // l
(byte) 0x63, // c
(byte) 0x75, // u
(byte) 0x6c, // l
(byte) 0x61, // a
(byte) 0x74, // t
(byte) 0x72, // r
(byte) 0x69, // i
(byte) 0x63, // c
(byte) 0x65 // e
}; // Tableau de bytes (code ASCII) qui va être renvoyé si on envoit l'INS 0x00
//methode d'installation de l'applet dans la carte
public static void install(byte[] bArray, short bOffset, byte bLength)
{
// Enregistrement de l'applet (méthode register()) auprès du JCRE
// Lors de la création de l'applet (new)
new Calculator().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
}
public void process(APDU apdu)
{
//pour verifier que cette applet n'est pas entrain d'être sélectionné
if (selectingApplet())
{
return;
}
//réception de la commande APDU
byte[] buf = apdu.getBuffer();
switch (buf[ISO7816.OFFSET_INS])
{
case (byte) 0x00 :
Util.arrayCopy(CALC, (short) 0, buf, (short) 0, (short) CALC.length);
apdu.setOutgoingAndSend((short) 0, (short) CALC.length);
return;
// Ici, on copie le tableau (défini en haut) dans le buffer et on l'envoi sur la sortie
// En précisant la taille du champ de données
case (byte) 0x01 :
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] + buf[ISO7816.OFFSET_P2]);
// Ici, on additionne P1 et P2
break;
case (byte) 0x02 :
//Soustraction de P1 et P2
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] - buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x03 :
//Multiplication
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] * buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x04 :
//Division
if (buf[ISO7816.OFFSET_P2] == 0)
{
//Test de la division par 0
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
//Envoie de l'exception "mauvais paramètres"
}
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] / buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x05 :
//Somme du champ de données de la commande APDU
short n = (short) (ISO7816.OFFSET_CDATA + apdu.setIncomingAndReceive());
byte sum = 0;
while (n-- > ISO7816.OFFSET_CDATA)
{
sum += buf[n];
}
buf[0] = sum;
break;
default :
//Envoie de l'exception "mauvais champ INS"
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
//Pour tous les cas la réponse APDU a des données de 1 octet
//Sauf pour le cas INS = 00
apdu.setOutgoingAndSend((short) 0, (short) 1);
}
} |
Partager