Skip to content

Instantly share code, notes, and snippets.

@adricasti
Created July 3, 2020 11:28
Show Gist options
  • Save adricasti/63fb9649601c96842cd46b1738179b5f to your computer and use it in GitHub Desktop.
Save adricasti/63fb9649601c96842cd46b1738179b5f to your computer and use it in GitHub Desktop.
Extended length APDU read and write
package storage;
import javacard.framework.*;
import javacardx.apdu.ExtendedLength;
public class Vault extends Applet implements ExtendedLength {
final static byte GET_DATA = (byte) 0xCB;
final static byte PUT_DATA = (byte) 0xDB;
private byte[] objBuffer;
private Vault() {
register();
}
public static void install(byte[] buffer, short offset, byte length) {
new Vault();
}
public boolean select() {
return true;
}
@Override
public void process(APDU apdu) throws ISOException {
byte[] buffer = apdu.getBuffer();
if (this.selectingApplet()) {
return;
}
if (!apdu.isISOInterindustryCLA())
ISOException.throwIt (ISO7816.SW_CLA_NOT_SUPPORTED);
switch(buffer[ISO7816.OFFSET_INS])
{
case GET_DATA:
GetData(apdu);
break;
case PUT_DATA:
PutData(apdu);
break;
default:
ISOException.throwIt (ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void GetData(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if (objBuffer == null)
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
short sendLen = apdu.setOutgoing();
if (sendLen > objBuffer.length)
sendLen = (short)objBuffer.length;
apdu.setOutgoingLength(sendLen);
apdu.sendBytesLong(objBuffer, (short)0, sendLen);
if (objBuffer.length > sendLen)
ISOException.throwIt((short)(ISO7816.SW_CORRECT_LENGTH_00 + ((objBuffer.length - sendLen) & 0x00FF)));
}
private void PutData(APDU apdu) {
byte[] buffer = apdu.getBuffer();
short recvLen = apdu.setIncomingAndReceive();
short dataLen = apdu.getIncomingLength();
short dataOffset = apdu.getOffsetCdata();
if (objBuffer != null)
JCSystem.requestObjectDeletion();
objBuffer = new byte[dataLen];
Util.arrayCopyNonAtomic(buffer, dataOffset, objBuffer, (short)0, recvLen);
short totalRead = recvLen;
while (totalRead < dataLen) {
recvLen = apdu.receiveBytes((short)0);
Util.arrayCopyNonAtomic(buffer, (short)0, objBuffer, totalRead, recvLen);
totalRead += recvLen;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment