FIT_hardware_security/lab01-03_java_card/Applet1.java

87 lines
2.6 KiB
Java

package hwb1;
import javacard.framework.*;
//import javacardx.annotations.*;
import javacard.security.*;
import javacardx.crypto.*;
public class Applet1 extends Applet {
byte str[] = JCSystem.makeTransientByteArray((short)20, JCSystem.CLEAR_ON_RESET);
OwnerPIN pin;
public static void install(byte[] bArray, short bOffset, byte bLength) {
new Applet1(bArray, bOffset, bLength);
}
protected Applet1(byte[] bArray, short bOffset, byte bLength) {
byte iLen = bArray[bOffset];
byte cLen = bArray[(short)(bOffset + iLen + (short)1)];
byte aLen = bArray[(short)(bOffset + cLen + (short)1)];
pin = new OwnerPIN((byte)3, (byte)4);
pin.update(bArray, (short)(bOffset + iLen + cLen + 3), aLen);
str = new byte[21];
register();
}
private void sendName(APDU apdu) {
short len = apdu.setOutgoing();
byte name[] = {'o','n','d','r','a'};
if (len > name.length) ISOException.throwIt((short)
(ISO7816.SW_CORRECT_LENGTH_00 + (short)(name.length)));
apdu.setOutgoingLength((short)len);
apdu.sendBytesLong(name, (short)0, (short)len);
}
private void storeData(APDU apdu) {
if (!pin.isValidated()) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
short bufLen = apdu.setIncomingAndReceive();
if (bufLen >= str.length) {
short err = ISO7816.SW_WRONG_LENGTH;
err |= (short)(str.length - (short)1);
ISOException.throwIt(err);
}
byte [] buf = apdu.getBuffer();
Util.arrayCopyNonAtomic(buf, ISO7816.OFFSET_CDATA, str, (short)0, bufLen);
str[(short)(str.length - (short)1)] = (byte)bufLen;
}
private void sendData(APDU apdu) {
if (!pin.isValidated()) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
short len = apdu.setOutgoing();
if (len > (short)str[(short)(str.length - (short)1)]) ISOException.throwIt((short)
(ISO7816.SW_CORRECT_LENGTH_00 + (short)(str.length - (short)1)));
apdu.setOutgoingLength((short)(str.length - (short)1));
apdu.sendBytesLong(str, (short)0, (short)(str.length - (short)1));
}
public void process(APDU apdu) {
byte [] buf = apdu.getBuffer();
if (buf[ISO7816.OFFSET_CLA] != 0x00) {
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
}
byte ins = buf[ISO7816.OFFSET_INS];
switch(ins) {
case 0x00: sendName (apdu); return;
case 0x02: storeData(apdu); return;
case 0x04: sendData (apdu); return;
}
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}