PCSC sample in Java

Here is the PCSC sample in Java language I promised in PC/SC sample in different languages.

Installation


Since Java 1.6 the JRE includes the package javax.smartcardio which was defined in the JSR 268. No need to compile additional source code.

For the example I used Eclipse Galileo and the Java 1.6 provided by Apple on a Mac OS X Snow Leopard (10.6.4).

Source code


import java.util.List;
import javax.smartcardio.*;

public class Blog {
 public static void main(String[] args) {
  try {
   // Display the list of terminals
   TerminalFactory factory = TerminalFactory.getDefault();
   List<CardTerminal> terminals = factory.terminals().list();
   System.out.println("Terminals: " + terminals);

   // Use the first terminal
   CardTerminal terminal = terminals.get(0);

   // Connect wit hthe card
   Card card = terminal.connect("*");
   System.out.println("card: " + card);
   CardChannel channel = card.getBasicChannel();

   // Send Select Applet command
   byte[] aid = {(byte)0xA0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x06, 0x01};
   ResponseAPDU answer = channel.transmit(new CommandAPDU(0x00, 0xA4, 0x04, 0x00, aid));
   System.out.println("answer: " + answer.toString());

   // Send test command
   answer = channel.transmit(new CommandAPDU(0x00, 0x00, 0x00, 0x00));
   System.out.println("answer: " + answer.toString());
   byte r[] = answer.getData();
   for (int i=0; i<r.length; i++)
    System.out.print((char)r[i]);
   System.out.println();

   // Disconnect the card
   card.disconnect(false);
  } catch(Exception e) {
   System.out.println("Ouch: " + e.toString());
  }
 }
}


Output



Terminals: [PC/SC terminal Gemplus GemPC Twin 00 00]
card: PC/SC card in Gemplus GemPC Twin 00 00, protocol T=1, state OK
answer: ResponseAPDU: 2 bytes, SW=9000
answer: ResponseAPDU: 14 bytes, SW=9000
Hello world!

Conclusion


Nothing special to add. The major advantage here is that the wrapper is included in the runtime. So you do not have to install much on a system before you can use your program, just the JRE :-)