Java
Chilkat2 Java
PC/SC Get Card UID
See more SCard Examples
Sends the APDU command to get a card's UID.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.SCard;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
SCard scard = new SCard();
// First establish a context to the PC/SC Resource Manager
try {
scard.establishContext("user");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Use your own smart card reader name here.
success = scard.connect("ACS ACR122 0", "shared", "no_preference");
if (!success) {
System.out.println(scard.getLastErrorText());
return;
}
System.out.println("Connected reader: " + scard.getConnectedReader());
System.out.println("Active protocol: " + scard.getActiveProtocol());
System.out.println("ATR: " + scard.getCardAtr());
System.out.println("Reader Status: " + scard.getReaderStatus());
// Send the APDU command 0xFF, 0xCA, 0x00, 0x00, 0x00
BinData bdRecv = new BinData();
try {
scard.transmitHex(scard.getActiveProtocol(), "FFCA000000", bdRecv, 32);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
System.out.println("Received: " + bdRecv.getEncoded("hex"));
// The UID is the returned data without the final 2 bytes.
int numBytes = bdRecv.getNumBytes();
if (numBytes > 2) {
System.out.println("UID: " + bdRecv.getEncodedChunk(0, numBytes - 2, "hex"));
}
} else {
System.out.println(scard.getLastErrorText());
}
// Disconnect from this reader.
try {
scard.disconnect("leave");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
}
// Applications should always release the context when finished.
try {
scard.releaseContext();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
}
}
}