Common PC/SC Interface functions

Source: Internet
Author: User

The PC/SC specification is a Windows platform-based standard user interface (API) that provides an integrated environment from personal computers (Personal computer) to smart cards (SmartCard), pc/ The SC specification is based on the industry standard-iso7816 and EMV standards, but it complements the underlying device interface and the device-independent API interface, such as a resource manager that allows multiple applications to share the same smart card with the system. The PC/SC system consists of three main components, each of which specifies the responsibilities of the operating system vendor, the reader/writer (IFD) manufacturer, and the smart Card (ICC) vendor. PC/SC's API functions are provided by the operating system, and the MSDN provided by Microsoft Company has help (path \\MSDN\Platform sdk\security\smart Card), function declarations in Winscard.h.
Because of the frequent use, I will pc/sc a few common functions to encapsulate, convenient to call.

1. Loading the header file

#include <WinSCard.h> #pragma comment (lib, "WinSCard.lib") #define Number_of_readers4#define index_length    2 #define Key_length32#define name_length100#define max_input1024#define max_output4000#define MAX_RESPONSE2000


2 Create a context for the explorer and get a list of readers

/************************************************************************//* connection to the card reader return: Connection failed 0, otherwise the number of Card reader list is returned *//*** /extern "C" __declspec (dllexport) int Cardreaderinit (char* messagebuffer,//_out_ return error message char (*readername) [Name_length],//_out_ return card reader list information SCA rdcontext* contexthandle//_out_ return reader handle) {//extra initialization//charreadername[number_of_readers][name_length]; memset (messagebuffer, 0, name_length); memset (Readername[0], 0, name_length); memset (Readername[1], 0, name_length); memset (Readername[2], 0, Name_length) memset (Readername[3], 0, name_length);  Pbyte Poutbuffer = (pbyte) malloc (max_output); int outbufferline = 0; Pbyte Presponsebuffer = (pbyte) malloc (max_response); memset (Presponsebuffer, 0x00, max_response);////open a context Which communication to the Resource manager//long ret = scardestablishcontext (scard_scope_user, NULL, NULL, Contexthandle ); if (ret! = scard_s_success) {sprintf_s (MEssagebuffer, Name_length, "Function SCardEstablishContext returned 0x%X error code.", ret); return false;} int readercount = 0;unsigned long responselength = Max_response;ret = Scardlistreaders (*contexthandle, 0, (char *) pRespons Ebuffer, &responselength), if (ret! = scard_s_success) {sprintf_s (Messagebuffer, Name_length, "Function Scardlistreaders returned 0x%X error code. ", ret); return false;} else {unsigned intstringlen = 0; Scardhandle Cardhandle = Null;while (ResponseLength > Stringlen + 1) {strcpy (Readername[readercount], (LPCTSTR) Presponsebuffer + stringlen);D Wordactiveprotocol = 0;ret = Scardconnect (*contexthandle, Readername[readercount], SCARD _share_shared, Scard_protocol_t0 | Scard_protocol_t1, &cardhandle, &activeprotocol); if (ret! = Scard_e_unknown_reader) readercount++;if (ret = = scard_s_success) Scarddisconnect (Cardhandle, Scard_eject_card); Stringlen + = strlen ((LPCTSTR) Presponsebuffer + Stringlen + 1); Stringlen + = 2;}} if (Readercount = = 0) {sprintf_s (MessagebuffeR, Name_length, "No driver is available for use with the resource manager!"); return false;} return readercount;}


3 card Reader and smart card connection
/************************************************************************//* connection to the card returned: Connection failed 0, otherwise returned 1*//********** /extern "C" __declspec (dllexport) bool Cardconnect ( Scardcontext Contexthandle,//_in_ incoming reader handle char (*readername) [Name_length],//_in_ incoming reader list information (two-dimensional array) int actname ,//_in_ incoming selected list ordinal scardhandle *cardhandle,//_out_ return card handle long* ProtocolType,//_out_ return card protocol char* MESSAGEB Uffer//_out_ return error message) {//<span style= "font-family: ' Courier New '; font-size:14px;" >scardtransmit  </span><a target=_blank target= "_blank" href= "http://baike.baidu.com/view/ 8257336.htm "style=" font-family: ' Courier New '; font-size:14px; " >http://baike.baidu.com/view/8257336.htm</a>dwordactiveprotocol = 0;*protocoltype = SCARD_PROTOCOL_T0 | Scard_protocol_t1;long ret = Scardconnect (Contexthandle, Readername[actname], scard_share_exclusive, *ProtocolType, Cardhandle, &activeprotocol); Memset (mesSagebuffer, 0x00, sizeof (messagebuffer)/sizeof (char)), if (ret! = scard_s_success) {geterrorcode (ret, messagebuffer); return false;} *protocoltype = Activeprotocol;switch (*protocoltype) {case scard_protocol_t0:sprintf_s (Messagebuffer, NAME_LENGTH, " Function scardconnect ok\nprotocoltype = T0 "); break;case scard_protocol_t1:sprintf_s (Messagebuffer, NAME_LENGTH," function Scardconnect Ok\nprotocoltype = T1 "); break;default:sprintf_s (Messagebuffer, Name_length," function Scardconnect ok\n%.8x ", Activeprotocol); return true;}


4 disconnecting from the card reader
/************************************************************************//* with card disconnected return: Connection succeeded 0. Otherwise error/HTTP// msdn.microsoft.com/en-us/library/windows/desktop/aa374738 (v=vs.85). aspx*//************************************ /extern "C" __declspec (dllexport) long Carddisconnect (Scardhandle cardhandle               //_in_ incoming card handle) {return Scarddisconnect (Cardhandle, Scard_eject_card);}

5 Releasing the resource management context
/************************************************************************//* disconnect from the card reader: Connection succeeded 0. Otherwise error/HTTP// msdn.microsoft.com/en-us/library/windows/desktop/aa374738 (v=vs.85). aspx*//************************************ /extern "C" __declspec (dllexport) long Cardreaderdisconnect (scardcontext Contexthandle           //_in_ incoming reader handle {return Scardreleasecontext (contexthandle);}

6 Sending instructions to a smart card
int transmit (byte* cmd,long protocoltype, scardhandle cardhandle) int transmit (byte* cmd, long protocoltype, SCARDHANDLE C Ardhandle) {CHARMHSTR[MAX_INPUT];CHARBUF[MAX_INPUT/2]; Pbytepinbuffer; Pbyte presponsebuffer;memset (mhstr, 0, Max_input); sprintf_s (Mhstr, Max_input, "%s", cmd); int bufferlen = Atohex ((char *) &AMP;MHSTR, (BYTE *) &buf); if (!bufferlen) {return false;} Scard_io_request Io_request;io_request.dwprotocol = Protocoltype;io_request.cbpcilength = (DWORD) sizeof (SCARD_IO_ REQUEST);p Inbuffer = (pbyte) malloc (max_input), memcpy (Pinbuffer, buf, bufferlen);p Responsebuffer = (pbyte) malloc (max_ INPUT); memset (Presponsebuffer, 0x00, Bufferlen); unsigned long responselength = max_response;long ret = Scardtransmit ( Cardhandle, &io_request, Pinbuffer, Bufferlen, 0, Presponsebuffer, &responselength); if (ret! = SCARD_S_SUCCESS) {GetErrorCode (ret, (char*) cmd); return false;} Datax::asctohex (Presponsebuffer, responselength, cmd); Cmd[responselength * 2] = 0x00;return responselength * 2;}

7 getting error messages

void GetErrorCode (long ret, char* messagebuffer) {switch (ret) {case scard_e_cancelled:sprintf_s (Messagebuffer, name_ LENGTH, "The action was cancelled by an scardcancel request."); Break;case scard_e_cant_dispose:sprintf_s (Messagebuffer, Name_length, "the system could not DISPOSE of the media in the RE quested manner. "); Break;case scard_e_card_unsupported:sprintf_s (Messagebuffer, Name_length, "the smart CARD does not meet minimal Requirements for support. "); Break;case scard_e_duplicate_reader:sprintf_s (Messagebuffer, Name_length, "The READER driver didn ' t produce a unique Reader name. "); Break;case scard_e_insufficient_buffer:sprintf_s (Messagebuffer, Name_length, "the data BUFFER to receive returned data is too small for the returned data. ");  Break;case scard_e_invalid_atr:sprintf_s (Messagebuffer, Name_length, "an ATR obtained from the registry are not a valid ATR String. "); Break;case scard_e_invalid_handle:sprintf_s (Messagebuffer, Name_length, "The supplied HANDLE was INVALID."); Break;casescard_e_invalid_parameter:sprintf_s (Messagebuffer, Name_length, "one or more of the supplied parameters could not being prope Rly interpreted. "); Break;case scard_e_invalid_target:sprintf_s (Messagebuffer, Name_length, "Registry startup information is missing or Invalid. "); Break;case scard_e_invalid_value:sprintf_s (Messagebuffer, Name_length, "one or more of the supplied parameters?values Could not being properly interpreted. "); Break;case scard_e_not_ready:sprintf_s (Messagebuffer, Name_length, "the reader or card is not a ready to accept commands.") ; Break;case scard_e_not_transacted:sprintf_s (Messagebuffer, Name_length, "an attempt is made to end a non-existent trans Action. "); Break;case scard_e_no_memory:sprintf_s (Messagebuffer, Name_length, "Not enough MEMORY available-complete this command ."); Break;case scard_e_no_service:sprintf_s (Messagebuffer, Name_length, "the Smart Card Resource Manager is not running."); Break;case scard_e_no_smartcard:sprintf_s (Messagebuffer, Name_length, "the OperatiOn requires a smart card but no smart card was currently in the device. "); Break;case scard_e_pci_too_small:sprintf_s (Messagebuffer, Name_length, "The PCI Receive buffer was TOO SMALL."); Break;case scard_e_proto_mismatch:sprintf_s (Messagebuffer, Name_length, "the requested protocols is incompatible with The protocol currently in use with the card. "); Break;case scard_e_reader_unavailable:sprintf_s (Messagebuffer, Name_length, "The specified READER is not currently Available for use. "); Break;case scard_e_reader_unsupported:sprintf_s (Messagebuffer, Name_length, "The READER driver does not meet minimal Requirements for support. "); Break;case scard_e_service_stopped:sprintf_s (Messagebuffer, Name_length, "the Smart Card Resource manager has shut down." ); Break;case scard_e_sharing_violation:sprintf_s (Messagebuffer, Name_length, "the card cannot be accessed because of Other connections outstanding. "); Break;case scard_e_system_cancelled:sprintf_s (Messagebuffer, Name_length, "the action was CancellEd by the system presumably-log off or shut down. "); Break;case scard_e_timeout:sprintf_s (Messagebuffer, Name_length, "The user-specified TIMEOUT value has expired."); Break;case scard_e_unknown_card:sprintf_s (Messagebuffer, Name_length, "The specified CARD NAME is not recognized."); Break;case scard_e_unknown_reader:sprintf_s (Messagebuffer, Name_length, "The specified READER NAME is not recognized."); Break;case scard_f_comm_error:sprintf_s (Messagebuffer, Name_length, "an internal communications the ERROR has been detected ."); Break;case scard_f_internal_error:sprintf_s (Messagebuffer, Name_length, "an INTERNAL consistency check failed."); Break;case scard_f_unknown_error:sprintf_s (Messagebuffer, Name_length, "an internal ERROR had been detected but the SOURC E is unknown. "); Break;case scard_f_waited_too_long:sprintf_s (Messagebuffer, Name_length, "an internal consistency timer had expired."); Break;case scard_s_success:sprintf_s (Messagebuffer, name_length, "OK"); Break;case Scard_w_removed_card:sprintf_s (Messagebuffer, Name_length, "The card has been removed so, further communication are not possible."); Break;case scard_w_reset_card:sprintf_s (Messagebuffer, Name_length, "The CARD has been RESET so any gkfx state informati On is invalid. "); Break;case scard_w_unpowered_card:sprintf_s (Messagebuffer, Name_length, "Power has been removed by the CARD so that Furt Her communication was not possible. "); Break;case scard_w_unresponsive_card:sprintf_s (Messagebuffer, Name_length, "The CARD isn't responding to a reset."); Break;case scard_w_unsupported_card:sprintf_s (Messagebuffer, Name_length, "the reader cannot communicate with the CARD Due to ATR configuration conflicts. "); break;default:sprintf_s (Messagebuffer, Name_length, "Function returned unknown error code: #%ld", ret); break;}}

8 Reset Card

BOOL Cpureset (Scardhandle Cardhandle, byte* ATR) {CHAR            szreader[200];D word           CCH = 200; BYTE            battr[32];D word           cbyte = 32;dword           dwstate, Dwprotocol; LONG            lreturn;stringatrvalue;memset (battr, 0, +); memset (Szreader, 0, +);//Determine the status.//Hcardhandle was set by a earlier call to Scardconnect.lreturn = Scardstatus (cardhandle,szreader,&cch,&dwstate,& Dwprotocol, (LPBYTE) &battr,&cbyte); if (scard_s_success! = lreturn) return False;datax::asctohex (BAttr, CByte, ATR); return TRUE;}


text/Shing original Reprint Please specify the source http://blog.csdn.net/yxstars/article/details/41522467


Common PC/SC Interface functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.