SCard Chilkat2 Perl Reference Documentation
Chilkat2::SCard
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.SCard
Enumerate available PC/SC smart card readers and identify the reader the
application should use.
Connect to a reader/card, check card presence and status, and manage the
active PC/SC connection.
Send APDU commands directly to the card and receive the raw response
bytes and status words.
Issue lower-level reader control commands when supported by the reader
driver and PC/SC environment.
Monitor reader or card status changes so applications can detect card
insertion, removal, or state changes.
Use PC/SC transactions for coordinated card access and inspect detailed
error information when reader or card operations fail.
For an extended overview, see
SCard Class Overview.
Communicate directly with smart card readers and cards through PC/SC.
Chilkat.SCard is the low-level PC/SC smart card interface for
applications that need direct reader and card communication. It supports
reader discovery, reader connection, card status checking, APDU transmission,
reader-control commands, status-change monitoring, transactions, and
diagnostic access to underlying PC/SC errors. Use this class when the
application needs APDU-level control rather than a higher-level certificate,
minidriver, or PKCS#11 abstraction.
Reader discovery
Connect to cards
Transmit APDUs
Reader-control commands
Status monitoring
Transactions and diagnostics
Chilkat.SCard for direct PC/SC
reader and APDU-level work; use Chilkat.ScMinidriver for
card-minidriver certificate and key-container operations, and
Chilkat.Pkcs11 for PKCS#11 token or HSM sessions.
Object Creation
use Chilkat2;
my $sCard = Chilkat2::SCard->new;
# or set properties (and RaiseError) at creation:
# my $sCard = Chilkat2::SCard->new(VerboseLogging => 1, RaiseError => 1);Creates the object. The optional pairs set writable properties (and RaiseError) in order, as if set one by one; an unknown or read-only name croaks. use Chilkat2; loads every class; the Chilkat2/SCard.pm file holds only this class's documentation (perldoc Chilkat2::SCard).
Perl frees the object when its last reference goes (undef $sCard, or the variable going out of scope); there is nothing to close. Objects returned by methods are independent and freed the same way. The class may be subclassed (use parent -norequire, 'Chilkat2::SCard';): an object is a blessed hash reference whose hash is free for the subclass's own fields.
When false (the default), a method that fails returns false (or undef), and the reason is in LastErrorText. When true, it dies with a Chilkat2::Error instead, as DBI does with its RaiseError. Objects returned by a method inherit the value of the object that returned them.
Errors
A Chilkat2::Error stringifies to the failed call's full LastErrorText, and has the methods text, class ('Chilkat2::SCard'), method (the method name) and object. Methods that look something up and find nothing return undef without dying (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain boolean, and property reads and writes never fail for Chilkat reasons.
Misuse always croaks, with your file and line, whatever RaiseError is: a wrong number of arguments, a reference or undef where a string or number is expected, an object of the wrong class, an out-of-range integer, a string containing a NUL character, a wide character in a byte string, or a write to a read-only property.
Strings are Perl character strings in both directions (length, regexes and :encoding layers see characters); binary data (BinData) is a byte string. Unlocking: call Chilkat2::Global->new->UnlockBundle('...') once at startup.
Properties
ActiveProtocol
my $strVal = $sCard->ActiveProtocol;
The name of the active protocol if connected smart card reader, or an empty string if not connected. Possible values are T0, T1, raw, undefined, or if not connected to a reader.
CardAtr
my $strVal = $sCard->CardAtr;
This is the Current ATR of a card in the connected reader.
topConnectedReader
my $strVal = $sCard->ConnectedReader;
The name of the currently connected smart card reader, or an empty string if not connected.
topContext
my $strVal = $sCard->Context;
Contains the string user or system if this object has established a context (by calling EstablishContext). Contains the empty string if no context is established.
DebugLogFilePath
my $strVal = $sCard->DebugLogFilePath;
$sCard->DebugLogFilePath($strVal);
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
LastErrorHtml
my $strVal = $sCard->LastErrorHtml;
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
my $strVal = $sCard->LastErrorText;
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
my $strVal = $sCard->LastErrorXml;
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
my $boolVal = $sCard->LastMethodSuccess;
$sCard->LastMethodSuccess($boolVal);
Indicates the success or failure of the most recent method call: 1 means success, 0 means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
PcscLibPath
my $strVal = $sCard->PcscLibPath;
$sCard->PcscLibPath($strVal);
For Linux systems only. Specifies the full path of the libpcsclite.so shared lib. This property should only be used if the libpcsclite.so is in a non-standard location or if Chilkat cannot automatically located it.
topReaderStatus
my $strVal = $sCard->ReaderStatus;
The current status of the connected reader. Possible values are:
absent- There is no card in the reader.present- There is a card in the reader, but it has not been moved into position for use.swallowed- There is a card in the reader in position for use. The card is not powered.powered- Power is being provided to the card, but the reader driver is unaware of the mode of the card.negotiable- The card has been reset and is awaiting PTS negotiation.specific- The card has been reset and specific communication protocols have been established.
ScardError
my $strVal = $sCard->ScardError;
The last error returned by an underlying PC/SC function. Can be one of the following:
SCARD_W_REMOVED_CARD- The smart card has been removed, so that further communication is not possible.SCARD_W_RESET_CARD- The smart card has been reset, so any shared state information is invalid.
...
VerboseLogging
my $boolVal = $sCard->VerboseLogging;
$sCard->VerboseLogging($boolVal);
If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
my $strVal = $sCard->Version;
Methods
BeginTransaction
my $success = $sCard->BeginTransaction();
Establishes a temporary exclusive access mode for doing a series of commands in a transaction.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
CheckStatus
my $flag = $sCard->CheckStatus();
Check the current status of the currently connected reader. Calling this method updates the ReaderStatus, ActiveProtocol, and CardAtr properties. If this method returns 0, none of the properties are updated.
Never dies: false is an answer, not a failure.
Connect
# $shareMode is a string
# $preferredProtocol is a string
# $flag is true or false
my $flag = $sCard->Connect($reader, $shareMode, $preferredProtocol);
Establish a connection to a reader. The $reader is the name of a reader returned from ListReaders. The $shareMode can be shared, exclusive, or direct. The $preferredProtocol can be 0 (valid only if the shareMode = direct), T0, T1, raw, or no_preference. (No preference is effectively T0 or T1.)
If successful, the state of this object instance is that it's connected to the reader.
Never dies: false is an answer, not a failure.
Disconnect
# $success is true or false
my $success = $sCard->Disconnect($disposition);
Terminates a connection with a reader. The $disposition can be one of the following values:
leave: Do nothing.reset: Reset the card (warm reset).unpower: Power down the card (cold reset).eject: Eject the card.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
EndTransaction
# $success is true or false
my $success = $sCard->EndTransaction($disposition);
Ends a previously begun transaction. The $disposition is the action to be taken on the reader, and can be leave which is to do nothing, reset, unpower, or eject.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
EstablishContext
# $success is true or false
my $success = $sCard->EstablishContext($scope);
Creates an Application Context to the PC/SC Resource Manager. This must be the first WinSCard function called in a PC/SC application. The $scope can be user or system. After calling, this object will have context and all other methods will use the established context. The Context property will hold the value user or system if context was established, or will be empty if no context was established.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
FindSmartcards
# $success is true or false
my $success = $sCard->FindSmartcards($json);
Returns JSON containing information about the smartcards currently inserted into readers.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetAttrib
# $bd is a Chilkat2::BinData
# $success is true or false
my $success = $sCard->GetAttrib($attr, $bd);
Get an attribute from the IFD Handler (reader driver).
The $attr can be one of the following:
ASYNC_PROTOCOL_TYPESATR_STRINGCHANNEL_IDCHARACTERISTICSCURRENT_BWTCURRENT_CLKCURRENT_CWTCURRENT_DCURRENT_EBC_ENCODINGCURRENT_FCURRENT_IFSCCURRENT_IFSDCURRENT_IO_STATECURRENT_NCURRENT_PROTOCOL_TYPECURRENT_WDEFAULT_CLKDEFAULT_DATA_RATEDEVICE_FRIENDLY_NAMEDEVICE_IN_USEDEVICE_SYSTEM_NAMEDEVICE_UNITESC_AUTHREQUESTESC_CANCELESC_RESETEXTENDED_BWTICC_INTERFACE_STATUSICC_PRESENCEICC_TYPE_PER_ATRMAX_CLKMAX_DATA_RATEMAX_IFSDMAXINPUTPOWER_MGMT_SUPPORTSUPRESS_T1_IFS_REQUESTSYNC_PROTOCOL_TYPESUSER_AUTH_INPUT_DEVICEUSER_TO_CARD_AUTH_DEVICEVENDOR_IFD_SERIAL_NOVENDOR_IFD_TYPEVENDOR_IFD_VERSIONVENDOR_NAME
The attribute data is returned in $bd.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetAttribStr
# $str is a string or undef
my $str = $sCard->GetAttribStr($attr);
Get a string typed attribute from the IFD Handler (reader driver).
The $attr can be one of the following, but should be limited to the particular attributes that return string values.
ASYNC_PROTOCOL_TYPESATR_STRINGCHANNEL_IDCHARACTERISTICSCURRENT_BWTCURRENT_CLKCURRENT_CWTCURRENT_DCURRENT_EBC_ENCODINGCURRENT_FCURRENT_IFSCCURRENT_IFSDCURRENT_IO_STATECURRENT_NCURRENT_PROTOCOL_TYPECURRENT_WDEFAULT_CLKDEFAULT_DATA_RATEDEVICE_FRIENDLY_NAMEDEVICE_IN_USEDEVICE_SYSTEM_NAMEDEVICE_UNITESC_AUTHREQUESTESC_CANCELESC_RESETEXTENDED_BWTICC_INTERFACE_STATUSICC_PRESENCEICC_TYPE_PER_ATRMAX_CLKMAX_DATA_RATEMAX_IFSDMAXINPUTPOWER_MGMT_SUPPORTSUPRESS_T1_IFS_REQUESTSYNC_PROTOCOL_TYPESUSER_AUTH_INPUT_DEVICEUSER_TO_CARD_AUTH_DEVICEVENDOR_IFD_SERIAL_NOVENDOR_IFD_TYPEVENDOR_IFD_VERSIONVENDOR_NAME
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetAttribUint
# $n is an integer
my $n = $sCard->GetAttribUint($attr);
Get an unsigned integer typed attribute from the IFD Handler (reader driver).
The $attr can be one of the following, but should be limited to the particular attributes that return unsigned integer values.
ASYNC_PROTOCOL_TYPESATR_STRINGCHANNEL_IDCHARACTERISTICSCURRENT_BWTCURRENT_CLKCURRENT_CWTCURRENT_DCURRENT_EBC_ENCODINGCURRENT_FCURRENT_IFSCCURRENT_IFSDCURRENT_IO_STATECURRENT_NCURRENT_PROTOCOL_TYPECURRENT_WDEFAULT_CLKDEFAULT_DATA_RATEDEVICE_FRIENDLY_NAMEDEVICE_IN_USEDEVICE_SYSTEM_NAMEDEVICE_UNITESC_AUTHREQUESTESC_CANCELESC_RESETEXTENDED_BWTICC_INTERFACE_STATUSICC_PRESENCEICC_TYPE_PER_ATRMAX_CLKMAX_DATA_RATEMAX_IFSDMAXINPUTPOWER_MGMT_SUPPORTSUPRESS_T1_IFS_REQUESTSYNC_PROTOCOL_TYPESUSER_AUTH_INPUT_DEVICEUSER_TO_CARD_AUTH_DEVICEVENDOR_IFD_SERIAL_NOVENDOR_IFD_TYPEVENDOR_IFD_VERSIONVENDOR_NAME
Returns 0xFFFFFFFF on failure.
topGetStatusChange
# $stReaderNames is a Chilkat2::StringTable
# $json is a Chilkat2::JsonObject
# $success is true or false
my $success = $sCard->GetStatusChange($maxWaitMs, $stReaderNames, $json);
Blocks execution until the current availability of the cards in a specific set of readers changes.
This function receives a list of reader names in $stReaderNames. It then blocks waiting for a change in state to occur for a maximum blocking time of $maxWaitMs (in milliseconds) or forever if 0 is used.
Information about the current reader states and which reader(s) changed is returned in $json. See the example below for more information.
To wait for a reader event (reader added or removed) you may use the special reader name \\?PnP?\Notification.
To cancel the ongoing call, call Cancel().
The $stReaderNames contains the reader names to check. The $json is empty on input, and if the call returns success contains information about the state (after the event change) of each reader.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetStatusChangeCancel
my $success = $sCard->GetStatusChangeCancel();
Cancels an ongoing GetStatusChange method call. This would be called from a separate thread in your application if GetStatusChange was called synchronously.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
ListReaderGroups
# $success is true or false
my $success = $sCard->ListReaderGroups($readerGroups);
Returns a list of currently available reader groups on the system. The reader groups are returned in $readerGroups.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
ListReaders
# $success is true or false
my $success = $sCard->ListReaders($st);
Returns a list of currently available readers on the system.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Reconnect
# $preferredProtocol is a string
# $action is a string
# $success is true or false
my $success = $sCard->Reconnect($shareMode, $preferredProtocol, $action);
Reestablishes a connection to a reader that was previously connected to using Connect().
In a multi application environment it is possible for an application to reset the card in shared mode. When this occurs any other application trying to access certain commands will be returned the value SCARD_W_RESET_CARD. When this occurs Reconnect() must be called in order to acknowledge that the card was reset and allow it to change its state accordingly.
The $shareMode can be shared, exclusive, or direct. The $preferredProtocol can be 0 (valid only if the shareMode = direct), T0, T1, raw, or no_preference. (No preference is effectively T0 or T1.) The $action is the desired action taken on the card/reader. It can be leave, reset, unpower, or eject.
If successful, the state of this object instance is that it's connected to the reader.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
ReleaseContext
my $success = $sCard->ReleaseContext();
Destroys a communication context to the PC/SC Resource Manager. This must be the last function called in a PC/SC application.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
SendControl
# $bdSend is a Chilkat2::BinData
# $bdRecv is a Chilkat2::BinData
# $success is true or false
my $success = $sCard->SendControl($controlCode, $bdSend, $bdRecv);
Sends a command directly to the IFD Handler (reader driver) to be processed by the reader.
This is useful for creating client side reader drivers for functions like PIN pads, biometrics, or other extensions to the normal smart card reader that are not normally handled by PC/SC.
The command data is sent in $bdSend. The response is written to $bdRecv.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
SendControlHex
# $sendData is a string
# $bdRecv is a Chilkat2::BinData
# $success is true or false
my $success = $sCard->SendControlHex($controlCode, $sendData, $bdRecv);
Sends a command directly to the IFD Handler (reader driver) to be processed by the reader.
This is useful for creating client side reader drivers for functions like PIN pads, biometrics, or other extensions to the normal smart card reader that are not normally handled by PC/SC.
The command data is provided as a hex string in $sendData. The response is written to $bdRecv.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Transmit
# $bdSend is a Chilkat2::BinData
# $bdRecv is a Chilkat2::BinData
# $maxRecvLen is an integer
# $success is true or false
my $success = $sCard->Transmit($protocolName, $bdSend, $bdRecv, $maxRecvLen);
Sends an APDU to the smart card contained in the currently connected reader. The $protocolName can be T0, T1, or raw. The APDU to be sent is contained in $bdSend. The response from the card is contained in $bdRecv. The $maxRecvLen is the maximum response size (in bytes) willing to be accepted.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
TransmitHex
# $apduHex is a string
# $bdRecv is a Chilkat2::BinData
# $maxRecvLen is an integer
# $success is true or false
my $success = $sCard->TransmitHex($protocolName, $apduHex, $bdRecv, $maxRecvLen);
Sends an APDU to the smart card contained in the currently connected reader. The $protocolName can be T0, T1, or raw. The APDU (in hexadecimal) to be sent is passed in $apduHex. The response from the card is contained in $bdRecv. The $maxRecvLen is the maximum response size (in bytes) willing to be accepted.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Chilkat2::SCard reports progress to handlers installed with on, which takes Event => CODE pairs (closures, so a handler can use the variables around it):
$sCard->on(
PercentDone => sub { my ($pctDone) = @_; print "$pctDone%\n"; return 0 }, # a true return aborts
ProgressInfo => sub { my ($name, $value) = @_; print "$name: $value\n" },
);Installs the handlers given, replacing those installed before for the same events; undef instead of a CODE reference removes one, and $sCard->on() with no arguments returns the installed handlers as a list of pairs. The event names are checked: a misspelled one croaks, and nothing is installed.
The AbortCheck handler is called periodically during long operations; PercentDone is called when an operation's completion percentage is known; ProgressInfo delivers named progress values. A true return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (false or undef, or a Chilkat2::Error under RaiseError).
Handlers run during the method call, on the thread that called it. Inside a handler, other objects may be used, but calling a method of the same object (or its on) croaks. A die in a handler aborts the running method and is re-thrown from the method call; the object remains usable. A handler that uses $sCard itself makes a reference cycle: weaken the captured copy (Scalar::Util) or remove the handler when done.
AbortCheck
$sCard->on(AbortCheck => sub { ... });
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
my $deadline = time() + 30; # give up after 30 seconds
$sCard->on(AbortCheck => sub { return time() > $deadline });PercentDone
$sCard->on(PercentDone => sub { ... });
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to 1. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$sCard->on(PercentDone => sub {
my ($pctDone) = @_; # 0 to 100
print "Percent done: $pctDone\n";
return 0; # return a true value to abort the method in progress
});ProgressInfo
$sCard->on(ProgressInfo => sub { ... });
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
$sCard->on(ProgressInfo => sub {
my ($name, $value) = @_;
print "$name: $value\n";
});