I have pieced together the following code example to detect Mifare smartcards using the javax.smartcardio library. This code works great for the listed Mifare types.
public class DetectCardTester {
private static final String PROTOCOL = "T=1";
static Map<String,String> KNOWN_CARD_TYPES = ImmutableMap.<String, String>builder()
.put("00-01", "Mifare 1K")
.put("00-02", "Mifare 4K")
.put("00-03", "Mifare Ultralight")
.put("00-26", "Mifare Mini")
.build();
public static void main(String... args) {
try {
final TerminalFactory terminalFactory = SmartcardTerminalFactory.create();
System.out.println("Place card on the reader");
final Card card = awaitCard(terminalFactory, 3, SECONDS);
final ATR atr = card.getATR();
final byte[] bytes = atr.getBytes();
System.out.println("ATR=" + String.valueOf(Hex.encodeHex(bytes, false)));
if (bytes != null && bytes.length > 13) {
String typeCode = String.format("%02X-%02X", bytes[13], bytes[14]);
if (KNOWN_CARD_TYPES.containsKey(typeCode)) {
System.out.println("Known Type:" + KNOWN_CARD_TYPES.get(typeCode));
} else {
System.out.println("Unknown Type:" + typeCode);
}
}
// TODO: Detect Desfire Card
} catch (Throwable t) {
t.printStackTrace();
}
}
public static Card awaitCard(final TerminalFactory terminalFactory, final int qty, final TemporalUnit unit) throws CardException {
LocalDateTime timeout = now().plus(qty, unit);
while (now().isBefore(timeout)) {
Optional<CardTerminal> cardTerminal = getCardPresentTerminal(terminalFactory);
if (cardTerminal.isPresent()) {
return cardTerminal.get().connect(PROTOCOL);
}
}
throw new CardNotPresentException("Timed out waiting for card");
}
private static Optional<CardTerminal> getCardPresentTerminal(final TerminalFactory terminalFactory) throws CardException {
List<CardTerminal> terminals = terminalFactory.terminals().list();
for (CardTerminal cardTerminal : terminals) {
if (cardTerminal.isCardPresent()) {
return Optional.of(cardTerminal);
}
}
for (CardTerminal cardTerminal : terminals) {
// waitForCardPresent / Absent doesn't work with some Jacax.smartcard.io implementations
// i.e. OSX http://bugs.java.com/view_bug.do?bug_id=7195480
// This is why we have the imediate check above
if (cardTerminal.waitForCardPresent(250)) {
return Optional.of(cardTerminal);
}
}
return Optional.empty();
}
}
I used the following resources to put this code together:
- http://downloads.acs.com.hk/drivers/en/API-ACR122U-2.02.pdf
- How to get SAK to Identify smart card type using JAVA?
I would like to implement the TODO comment to detect Desfire cards. If I place a Desfire card on the read this code just outputs:
Place card on the reader
ATR=3B8180018080
I found this question Determine card type from ATR which helps a bit but I am missing something. The HistoricalByte for the card in question is 0x80 for which I am unable to find any information.
If possible I would greatly appreciate the above code example extended such that it can detect the Desfire card type.