APDU I/O API Examples

The following are examples of how to use the APDU I/O API:

To Connect To a Simulator

To establish a connection to a simulator such as cref:

  1. Use the following code snippet:
    CadClientInterface cad;
    Socket sock;
    sock = new Socket("localhost", 9025);
    InputStream is = sock.getInputStream();
    OutputStream os = sock.getOutputStream();
    cad=CadDevice.getCadClientInstance(CadDevice.PROTOCOL_T0, is, os);
  2. The code establishes a T=0 connection to a simulator listening to port 9025 on localhost.

    To open a T=1 connection instead, replace PROTOCOL_T0 in the last line with PROTOCOL_T1.

    For dual-interface simulation, open two T=1 connections on ports (n) and (n+1), as described in Two-interface Card Simulation.

To Power Up And Power Down the Card

The dual-interface RI is implemented in such a way that once the client establishes connection to a port, the next command must be powerUp on that port. For example, the following sequence is valid:

  1. Connect on "contacted" port.

  2. Send powerUp to it.

  3. Exchange some APDUs.

  4. Connect on "contactless" port.

  5. Send powerUp to it.

  6. Exchange more APDUs

However, the following sequence is not valid:

  1. Connect on "contacted" port.

  2. Connect on "contactless" port.

  3. Send powerUp to any port.

To power up and power down the card:

  1. Use the following code:


  2. To power down the card and close the socket connection (for simulators only), use either of the following code lines:


  3. To power down, but leave the socket open, use the following code.

    If the simulator continues to run (which is true if this is contactless interface of the RI) you can issue powerUp() on this card again and continue exchanging APDUs.

To Exchange APDUs

To exchange APDUs:

  1. Create a new APDU object using the following code:
    Apdu apdu = new Apdu();
  2. Copy the header (CLA, INS, P1, P2) of the APDU to be sent into the apdu.command field.
  3. Set the data to be sent and the Lc using the following code:

    apdu.setDataIn(dataIn, Lc);

    where the array dataIn contains the C-APDU data, and the Lc contains the data length.

  4. Set the number of bytes expected into the apdu.Le field.
  5. Exchange the APDU with a card or simulator using the following code:

    After the exchange, apdu.Le contains the number of bytes received from the card or simulator, apdu.dataOut contains the data received, and apdu.sw1sw2 contains the SW1 and SW2 status bytes.

    These fields can be accessed through the corresponding get methods.

To Print the APDU

To print the APDU:

  1. The following code prints both C-APDU and R-APDU in the apdutool output format.