Sample code for 30+ languages & platforms
Lua

PC/SC Get Card UID

See more SCard Examples

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

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local scard = chilkat.SCard.new()

-- First establish a context to the PC/SC Resource Manager
local success = scard:establish_context("user")
if not success then
    print(scard.last_error_text)
    return
end

-- Use your own smart card reader name here.
success = scard:connect("ACS ACR122 0", "shared", "no_preference")
if not success then
    print(scard.last_error_text)
    return
end

print("Connected reader: " .. scard.connected_reader)
print("Active protocol: " .. scard.active_protocol)
print("ATR: " .. scard.card_atr)
print("Reader Status: " .. scard.reader_status)

--  Send the APDU command 0xFF, 0xCA, 0x00, 0x00, 0x00
local bdRecv = chilkat.BinData.new()
success = scard:transmit_hex(scard.active_protocol, "FFCA000000", bdRecv, 32)
if success then
    print("Received: " .. bdRecv:get_encoded("hex"))

    -- The UID is the returned data without the final 2 bytes.
    local numBytes = bdRecv.num_bytes
    if numBytes > 2 then
        print("UID: " .. bdRecv:get_encoded_chunk(0, numBytes - 2, "hex"))
    end
else
    print(scard.last_error_text)
end

-- Disconnect from this reader.
success = scard:disconnect("leave")
if not success then
    print(scard.last_error_text)
end

-- Applications should always release the context when finished.
success = scard:release_context()
if not success then
    print(scard.last_error_text)
end