Sample code for 30+ languages & platforms
Rust

PC/SC Get Card UID

See more SCard Examples

Sends the APDU command to get a card's UID.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let scard = chilkat::SCard::new();

// First establish a context to the PC/SC Resource Manager
if scard.establish_context("user").is_err() {
    println!("{}", scard.last_error_text());
    return;
}

// Use your own smart card reader name here.
if scard.connect("ACS ACR122 0", "shared", "no_preference").is_err() {
    println!("{}", scard.last_error_text());
    return;
}

println!("Connected reader: {}", scard.connected_reader());
println!("Active protocol: {}", scard.active_protocol());
println!("ATR: {}", scard.card_atr());
println!("Reader Status: {}", scard.reader_status());

//  Send the APDU command 0xFF, 0xCA, 0x00, 0x00, 0x00
let bd_recv = chilkat::BinData::new();
if scard.transmit_hex(&scard.active_protocol(), "FFCA000000", &bd_recv, 32).is_ok() {

    println!("Received: {}", bd_recv.get_encoded("hex").unwrap_or_default());

    // The UID is the returned data without the final 2 bytes.
    let num_bytes = bd_recv.num_bytes();
    if num_bytes > 2 {
        println!("UID: {}", bd_recv.get_encoded_chunk(0, num_bytes - 2, "hex").unwrap_or_default());
    }

} else {
    println!("{}", scard.last_error_text());
}

// Disconnect from this reader.
if scard.disconnect("leave").is_err() {
    println!("{}", scard.last_error_text());
}

// Applications should always release the context when finished.
if scard.release_context().is_err() {
    println!("{}", scard.last_error_text());
}