Technical Articles

Smart Card Crash Course




      A credit card sized plastic card with an embedded computer chip. The chip can either be a microprocessor with internal memory or a memory chip with non-programmable logic. The chip connection is either via direct physical contact or remotely via a contact-less electromagnetic interface.


      Invented in 1974, by independent inventor Roland Moreno. More technologies originated in seventies in Germany, Japan and France. Was in R&D stage in eighties. Widely used now in Europe and US by telephone and banking sector.


    • An advanced security system is worthless if it is so inconvenient for the users that they always find a way around it. For example, many users have so many passwords to remember today that they often write them down in easily accessible places or choose simple easily guessed passwords. Smart cards can easily store large passwords.
    • Being a computer in itself, smart cards can also perform advanced security functions like storage of cryptographic keys and ability to perform cryptographic algorithms.
    • Smart cards provide tamper-resistant storage for protecting sensitive information like private keys, account numbers, passwords, and other forms of personal information.
    • They can isolate security-critical computations that involve authentication, key exchange and digital signatures from other parts of the system that do not have a "need to know". Since computations can be done in the card itself, the keys need not exist anywhere other than the card itself. This prevents malicious sniffing programs from getting hold of the key.
    • They provide a level of portability to securely move information from one system to another.
    • They can run custom code and thus are programmable.


    • Over 300,000,000 GSM mobile telephones with smart cards which contain the mobile phone security and subscription information. The handset is personalized to the individual by inserting the card that contains its phone number on the network, billing information, and frequently call numbers.
    • Almost every small dish TV satellite receiver (millions of them in use in Europe and US) uses a smart card as its removable security element and subscription information.
    • Every French Visa Debit card (over 25,000,000) has a chip in it. In Germany, about 40,000,000 banking cards have been issued. EuroPay, MasterCard, and Visa all have smart card programs for their bank members. In the Portugal and Singapore, the national banking networks have launched electronic purse projects. Proton has worked with its banking partners to issue over 25,000,000 electronic purse cards in several countries.
    • Every person in Germany and Austria is issued a smart card under national health care program.
    • Pay phone systems in Germany, France, UK, Brazil, Mexico, and China.
    • Microsoft Windows 2000 has smart card and certificate based logon built in.
    • Computer/internet user authentication and non-repudiation, retailer loyalty programs, physical access, resort cards, mass transit, electronic toll, product tracking, national ID, drivers license, pass ports, and the list goes on.




      Two general categories: Contact and Contact-less smart cards.

      Contact smart card requires direct connection to the chip on the card surface by inserting into a smart card reader.
      Contact-less card requires only close proximity to a reader. They derive power from electromagnetic signals from the card reader and communicate through antennae. Ideal for applications like mass transit that require very fast card interface.

      Two additional derived categories are Combi cards and Hybrid cards.

      Hybrid card has two separate chips (not connected), each with its respective contact and contact-less interface.
      Combi card is a single chip card with a contact and contact-less interface, thus offering fast card interface with a very high level of security for mass transportation and banking sectors.

      The chips used in these cards fall into two categories: Microprocessor chips and Memory chips.

      A memory chip can be viewed as small floppy disks with optional security.

      Capacity: 103 bits to 16,000 bits.
      Pros: Less expensive. High-security alternative to magnetic stripe cards.
      Cons: Can only undertake a pre-defined operation. Lower data management security.
      Cost: $1 card, $500 reader

      Microprocessor chip is a miniature computer with an input/output port, operating system and hard disk.

      Capacity: 300 bytes to 32,000 bytes.
      Pros: Can add, delete and otherwise manipulate information in its memory. Available in 8, 16, and 32 bit architectures. Can download not just data but also applications.
      Cons: Expensive, slow.
      Cost: $10 card, $500 reader.

      Upcoming Technology:

      Optical Memory Cards.
      Optical memory cards look like a card with a piece of a CD glued on top - which is basically what they are. This type of card is ideal for record keeping - for example medical files, driving records, or travel histories.

      Capacity: 4MB
      Cons: Read only data. No processor in the card. Card readers are expensive.
      Pros: Card prices comparable to chip cards.
      Cost: $10 card, $4000 reader



      Smart cards are embedded with a micro-module containing a single silicon integrated circuit chip with memory and microprocessor. The micro-module has eight metallic pads on its surface, each designed to international standards for VCC (power supply voltage), RST (used to reset the microprocessor of the smart card), CLK (clock signal), GND (ground), VPP (programming or write voltage), and I/O (serial input/output line). Two pads are reserved for future use (RFU). Only the I/O and GND contacts are mandatory on a card to meet international standards; the others are optional.

      When a smart card is inserted into a Card Acceptance Device or CAD (such as a point-of-sale terminal), the metallic pads come into contact with the CAD’s corresponding metallic pins, thereby allowing the card and CAD to communicate. Smart cards are always reset when they are inserted into a CAD. This action causes the smart card to respond by sending an "Answer-to-Reset" message, which informs the CAD, what rules govern communication with the card and the processing of a transaction.

      The micro-module on board the smart card is made up of the following key components:

      The Microprocessor Unit (MPU)
      It executes programmed instructions. Older version smart cards are based on relatively slow 8-bit embedded micro-controllers. The trend during the 1990s has been toward using customized controllers with a 32-bit Reduced Instruction Set Computing (RISC) processor running at 25 to 32 MHz.

      The I/O Controller
      Manages the flow of data between the Card Acceptance Device (CAD) and the microprocessor.

      Read Only Memory (ROM) or Program Memory
      ROM has instructions permanently burned into it by the silicon manufacturer. These instructions (such as the program that manages the password) are the fundamentals of the Chip Operating System (COS) or, as often called, the "Mask."

      Random Access Memory (RAM) or Working Memory
      This serves as a temporary storage of results from calculations or input/output communications. RAM is a volatile memory and loses information immediately when the power supply is switched off.

      Application Memory, or EEPROM.
      EEPROM or double E-PROM stands for Electrically Erasable Programmable Read Only Memory. It can be erased electronically and rewritten. By international standards, this memory should retain data for up to 10 years without electrical power and should support at least 10,000 read-write actions during the life of the card. Application memory is used by an executing application to store information on the card.

      The Chip Operating System (COS)
      The smart card's COS (sometimes referred to as the Mask) is a sequence of instructions, permanently embedded in the ROM of the smart card. COS instructions are not dependent on any particular application, but are frequently used by most applications.

      Chip Operating Systems are divided into two families:

      1. The general purpose COS which features a generic command set in which the various sequences cover most applications, and
      2. The dedicated COS with commands designed for specific applications and which can even contain the application itself. An example of a dedicated COS would be a card designed to specifically support an electronic purse application.

      The baseline functions of the COS which are common across all smart card products include:

      1. Management of interchanges between the card and the outside world, primarily in terms of the interchange protocol.
      2. Management of the files and data held in memory.
      3. Access control to information and functions (for example, select file, read, write, and update data).
      4. Management of card security and the cryptographic algorithm procedures.
      5. Maintaining reliability, particularly in terms of data consistency, sequence interrupts, and recovering from an error.
      6. Management of various phases of the card's life cycle (that is, microchip fabrication, personalization, active life, and end of life).


    There are several standards and specifications. No single specification encompasses all aspects of the smart card industry. As you will discover in the following sections, there are separate specifications for communication between cards and card terminals (ISO 7816), interface between the card aware applications and cards (PC/SC, OpenCard), card-resident applications (Java Card), and then there are standards pertaining to particular industries.


      Basic smart card standard is the ISO 7816 series, part 1-11.

      1. Part 1: Physical characteristics. Defines dimensions of contact smart cards and their resistance to static electricity, electromagnetic radiation and mechanical stress. It also prescribes the physical location of a IC card's magnetic stripe and embossing area.
      2. Part 2: Dimensions and locations of contacts and their purpose and electrical characteristics.
      3. Part 3: Electronic signals and transmission protocols, voltage and current requirements for the electrical contacts defined in Part 2 and asynchronous half-duplex character transmission protocol (T=0). Smart cards that use a proprietary transmission protocol carry the designation, T=14. In practical terms, that means the card is not compatible with ISO 7816. Protocol type T=1, asynchronous half duplex block transmission protocol (Amendment 1, 1992).
      4. Part 4: Inter-industry commands for interchange. A set of commands across all industries to provide access, security and transmission of card data.
      5. Part 5: Application identifiers. An AID has two parts. The first is a Registered Application Provider Identifier (RID) of five bytes that is unique to the vendor. The second part is a variable length field of up to 11 bytes called the Proprietary Application Identifier Extension (PIX) that a vendor can use to identify specific applications. Every smart card application builder can get a RID. RIDs are assigned by the Dutch Telephone Company, KTAS, which is also the ISO/IEC 7816-5 Registration Authority, but the application has to be approved by your national ISO body. Forms for applying for an RID can be found at SCDK website. If you want to issue a single application smart card then you need an Issuer Identification Number (IIN) which is specified in ISO 7812.
      6. Part 6: Inter-industry data elements. Encoding rules for data needed in many applications e.g. name and photograph of owner, his preference of languages etc.
      7. Part 7: Inter-industry commands for SCQL (Structured Card Query Language). Defines how to treat the data in a card as a SQL database.
      8. Part 8: DRAFT Security related inter-industry commands. Adds symmetric and asymmetric key capabilities to Part 4.
      9. Part 9: DRAFT Additional inter-industry commands and security attributes. Adds commands needed for personalization such as Create File and Delete File as well as search commands to Part 4.
      10. Part 10: DRAFT Electronic signals and answer to reset for synchronous cards. Defines basic communication protocols for synchronous (T=14) smart cards.
      11. 11. Part 11: WITHDRAWN Card structure and enhanced functions for multi-application use. First attempt to standardize a multi-application card. Now abandoned.
      More... (SCIA Standards page)

      The Communication Protocol

        Smart cards speak to the outside world using data packages called APDU (Application Protocol Data Units). APDU contains either a command or a response message. A master-slave model is used whereby a smart card always plays the passive role. In other words, a smart card always waits for a command APDU from a terminal. It then executes the action specified in the APDU and replies to the terminal with a response APDU. Command APDUs and response APDUs are exchanged alternatively between a card and a terminal. The following tables illustrate command and response APDU formats, respectively. APDU structure is described in ISO 7816, part 4.

        Command APDU

        Command APDU
        Mandatory Header Conditional Body
        CLA INS P1 P2 Lc Data Field Le

        The header codes the selected command. It consists of four fields, each of 1 byte length. The body consists of three fields.

        1. CLA: Class byte. In many smart cards, this byte is used to identify an application.
        2. INS: Instruction byte. This byte indicates the instruction code.
        3. P1-P2: Parameter bytes. These provide further qualification to the APDU command.
        4. Lc: Denotes the number of bytes in the data field of the command APDU.
        5. Le: Denotes the maximum number of bytes expected in the data field of the following response APDU.

        Response APDU

        Response APDU
        Conditional Body Mandatory Trailer
        Data Field SW1 SW2

        Status bytes SW1 and SW2 denote the processing status of the command APDU in a card.



      The EMV standard, defined by Europay, MasterCard, and Visa, is based on the ISO 7816 series of standards with additional proprietary features to meet the specific needs of the financial industry.


      Although smart cards confirm to a set of international standards, there is currently no standard chip operating system, or anything as common and widespread as Windows and Unix. Each smart card vendor provides a distinct product. The key discriminator between different smart card products is the proprietary operating system that each vendor provides.


      The PC/SC Specifications 1.0 are completely platform independent, and can be implemented on any operating system.
      PC/SC work builds upon existing industry smart card standards - ISO7816 and EMV - and complements them by defining low-level device interfaces and device-independent application APIs as well as resource management, to allow multiple applications to share smart card devices attached to a system.

      The PC/SC Specifications 1.0 are divided into eight parts.

      1. Part 1: Provides an overview of the system architecture and components defined by the Workgroup.
      2. Part 2: Details compliant ICC-IFD (smart card - Interface Device) characteristics and interoperability requirements.
      3. Part 3: Describes the interface to, and required functionality for, compliant IFD devices.
      4. Part 4: Discusses design considerations for IFD devices. In particular, it provides a recommended implementation for PS/2 keyboard integrated IFDs.
      5. Part 5: Describes the interfaces and functionality supported by the ICC Resource Manager, a required system level component.
      6. Part 6: Describes the ICC Service Provider model, identifies required interfaces, and indicates how this may be extended to meet application domain-specific requirements.
      7. Part 7: Describes design considerations for application developers, and how to make use of the other components.
      8. Part 8: Describes recommended functionality for ICCs intended to support general purpose cryptographic and storage requirements. This is oriented toward support of Internet and PC standards for security and privacy.


      The OpenCard Standard is an attempt to standardize the interface between the Card Terminal, Card Operating System and the Card Application. OCF helps developers in developing card-external applications. It will not provide support in developing the card-resident application.

      The core architecture of the OpenCard Framework features two main parts: the CardTerminal layer and the CardService layer. The problem of card issuer independence is addressed separately by OCF's ApplicationManagement component.

      The CardTerminal layer provides access to physical card terminals and inserted smart cards for which manufacturers make appropriate OCF-compliant drivers available. Also included are Java APIs for accessing PC/SC-supported card terminals.

      The CardService layer makes it possible for the OpenCard Framework to deal with the wide variety of card operating systems in existence and the various different functions they may offer. Among OCF's many CardServices are the FileAccessCardService and the SignatureCardService. The FileAccessCardService provides a fairly complete set of interfaces and (abstract) classes making the ISO file system's functions available to the programmer. These classes and interfaces have been designed to fit seamlessly into the existing Java programming model. The SignatureCardService offers you methods to create and verify digital signatures based on such public key algorithms as RSA and DSA. Additional services allow private and public keys to be imported to the smart card or key pairs to be generated directly on the smart card.

      With the introduction of multiple applications which can be loaded onto a single smart card, new dependencies - such as which applications are available on the card or where an application and its data are physically located on the card - are created. This is where the ApplicationManagement component comes in. The ApplicationManagement component is capable of locating and selecting card-resident applications on any given smart card, listing the applications which a particular smart card supports, installing and uninstalling applications on smart cards, and blocking and unblocking applications on smart cards, and thus solves the problem of card issuer dependency.

      OpenCard framework supports JavaCards and other Multi-Application Cards through a package called opencard.opt.applet that supports implementation of card services in form of proxy classes for applets on JavaCards, applications on EMV/ISO cards etc.



        The Java Card specifications enable Java technology to run on Smart Cards and other devices with limited memory. The Java Card API allows applications written for one smart card platform that is enabled with Java Card technology to run on any other such platform.

        The Java Card Application Environment (JCAE) is licensed on an OEM-basis to smart card manufacturers, representing more than 90 percent of the worldwide smart card manufacturing capacity.

        The minimum card requirements are 16KB or ROM, 8KB of EEPROM, and 256 bytes of RAM. Java Card specifications can be accessed from JavaSoft Website.

      Java Card Applications:

        Java card applications are called applets. Multiple applets can reside on one card, each of which is identified by its unique AID (Application Identifier) as defined, in ISO7816, part 5. An AID is a sequence of 5 to 16 bytes, the first 5 bytes of which is a National registered application provider ID (RID), and the next 11 bytes specify the proprietary application identifier extension (PIX). ISO controls assignment of RID and companies manage assignment of PIX.

        Unlike the Java virtual machine (JVM) in a PC or workstation, the Java Card virtual machine runs forever.

        Most of the information stored on the card must be preserved even when the power is removed - that is, when the card is removed from the reader. The Java Card VM creates objects in EEPROM to hold the persistent information. The execution lifetime of the Java Card VM is the lifetime of the card. When the power is not provided, the VM runs in an infinite clock cycle.

        An applet's life starts when it is properly installed and registered with the system's registry table and ends when it is removed from the table. The space of a removed applet may or may not be reused, however, depending on whether garbage collection is implemented on the card. An applet on a card is in an inactive stage until the terminal explicitly selects it.

        Objects are created in the persistent memory (for example, EEPROM). They could be lost or garbage-collected if other persistent objects do not reference them. However, it's a thousand times slower to write to EEPROM than to RAM.

        Some objects are accessed frequently, and the contents of their fields need not be persistent. The Java Card supports transient (temporary) objects in RAM. Once an object has been declared as transient, its contents can not be moved back to the persistent memory.

      The Restricted JVM:

        Java Card programs are, of course, written in Java. They are compiled using common Java compilers. Due to limited memory resources and computing power, not all the language features defined in the Java Language Specification are supported on the Java Card. Specifically, the Java Card does not support:

        1. Dynamic class loading
        2. Security manager
        3. Threads and synchronization
        4. Object cloning
        5. Finalization
        6. Large primitive data types (float, double, long, and char)

        It's no surprise that keywords that support those features are also omitted from the language. VM implementers may decide to support 32-bit integer type or native methods for post-issuance applets if they are working on a more advanced smart card with more memory. Post-issuance applets are those applets that are installed on a Java Card after the card is issued to a cardholder.

      Benefits of Java Card technology:

      • Platform Independent - Java Card technology applets that comply with the Java Card API specification will run on cards developed using the JCAE - allowing developers to use the same Java Card technology applet to run on different vendors' cards.
      • Multi-Application Capable - Multiple applications can run on a single card. In the Java programming language, the inherent design around small, downloadable code elements makes it easy to securely run multiple applications on a single card.
      • Post-Issuance of Applications - The installation of applications, after the card has been issued, provides card issuers with the ability to dynamically respond to their customer's changing needs. For example, if a customer decides to change the frequent flyer program associated with the card, the card issuer can make this change, without having to issue a new card.
      • Flexible - The Object-Oriented methodology of the Java Card technology provides flexibility in programming smart cards.
      • Compatible with Existing Smart Card Standards - The Java Card API is compatible with formal international standards, such as, ISO7816, and industry-specific standards, such as, Europay/Master Card/Visa (EMV).


      The physical and mechanical standards are observed more uniformly than the software standards. The ISO 7816 series of standards and the ETSI SMG9 standards are the most important and relevant for smart card application programmers.

      • ISO 7810 - Identification cards -- Physical characteristics.
      • ISO/IEC 7812 - Identification of issuers.
      • ISO/IEC 7816 - Identification cards -- Integrated circuit(s) with electrical contacts.
      • ISO/IEC 10536 - Identification cards – Contact-less integrated circuit(s) cards. The standard specifies close coupling (slot and surface) cards communication (parts 1-3)
      • ISO/IEC 10373 - Identification cards -- Test methods.
      • ISO/IEC 14443 - Remote-coupling communication cards. (Contact-less cards)
      • ISO TC 68 - Banking and related financial services
      • EN 742 - Identification cards
      • EN 726 Terminal Equipment (TE) - Requirements for IC cards and terminals for telecommunication use. The standard is the technical basis for smartcards in Europe.
      • FIPS 140-1 – Published in the U.S., the National Institute of Standards and Technology (NIST). Concerns physical security of smart card IC-s, as they are one kind of cryptographic module.
        ( "Security Requirements for Cryptographic Modules"
      • SEIS - Secure Electronic Information in Society - Used by the Swedish government to standardize a smart card for use by its citizens.


      All ISO 7816-3 compliant card readers can communicate with all ISO 7816-3 compliant cards at this level.

      NO! This is a common misconception.

      The ISO 7816-3 standard defines a common vocabulary to describe options and parameters, and a method for the card to tell some options it can use, so that IF the card and reader support a common set of options (and are standard-compliant), they can function together.

      The standard does not even try to insure that any compliant card can work in any compliant reader. A striking (and frequent) example is that there is no requirement for either the reader or the card to support both the T=0 and T=1 protocol, which are entirely different.

      The standard does insure that one COULD build a reader that could read any compliant card not using RFU values. But no reader that I know does that; in particular, most readers support a narrow subset of the 8 possible Di parameter (fortunately, all readers and most cards support Di = 1).

      Fortunately, the standard also defines a "default" value for all parameters and options. These are supported by most readers and used by most cards, with the notable the exception of T (the parameter defining the protocol in use) which defaults to 0 but is 1 in a significant proportion of cards.

      Another example (no longer frequent) of incompatible parameter set between card and reader occurs with the support of Vpp, which few recent readers support, but some old Smart Cards require for common operations (including reading some areas protected by PIN code).

      So you think, let us prescribe Smart Card readers that support both T=0 and T=1, and at least they should support all cards that use either protocol with default options and do not require Vpp, right? In theory, yes. But in practice no. Among the pitfalls encountered in my practice:

      • On the ISO 7816-2 mechanical layer, most readers that implement dual-position contacts do so by wiring together the contacts with the same name in the two positions. But quite a few cards using one position have grounded metal (partly) in the area of the Vcc contact on the other position, which (sometimes) creates a power short circuit.
      • On the ISO 7816-3 physical layer, many readers do not match the requirement on Vcc stability and precision set by the standard, so cards must be very tolerant on that parameter; same thing for the rise/fall time and symmetry of clock.
      • On the ISO 7816-3 logical layer, many cards and many readers require an extra delay (beside the one defined by the standard at 6.5.3) between a byte they send and the next byte they can receive. Some application standards (like EMV) do attempt to fix this by specifying an extra delay on the transmitting side before sending the first byte following a direction change.
      • There are two incompatible methods around to compute the 16 bit CRC specified for the T=1 protocol.
      • Quite a few cards do produce (for complex commands) inter-character delay beyond the one implied by conformant analysis of their ATR, so readers must be prepared to extend this delay; the card should not ask an extended delay, because many readers will not accept/perform it.
      • Cards that send an ATR specifying multiple set of options will put many readers in trouble, and some readers will work well only with the default options.

      Among more theoretical problems, if you really try, you will find quite a few readers do not implement the error correction protocol mandated for T=0, although they do support T=0. And, both for T=0 and T=1, if you induce a single bit error, you'll often find the error-recovery does not work at all, often because one side was not conformant, sometime because the standard itself does not insure successful recovery (especially true for T=0). But fortunately communication errors are about as unlikely as floppy disk errors, and the user in practice performs recovery.

      - Francois Grieu on




    • A resource manager that uses a Win32 API.
    • A user interface that works with the resource manager.
    • Specific services provided by service providers. This is a layer over the Win32 APIs.


    PCSC SmartCard Subsystem


      Windows provides a Resource Manager - a component of the smart card subsystem that manages access to multiple readers and smart cards. The resource manager identifies and tracks resources, allocates readers and resources across multiple applications, and supports transaction primitives for accessing services available on a given card. The following is a list of Win32 Smart Card API along with a brief description. The order of listing is approximately the order to follow while operating on a card.

      Establishing Context:

      Function Name: SCardEstablishContext

      Returns a context handle that is to be used in further queries and operations on the card. The context defines the scope of the operations (USER or SYSTEM level) you need to perform.


      Function Name: SCardConnect

      Establishes a connection between the calling application and the smart card reader. Connections can be SHARED, EXCLUSIVE, or DIRECT. You can also specify a preferred protocol to use (T0 or T1). The function returns a handle that identifies this specific connection.

      Getting Card Status:

      Function Name: SCardStatus

      Gets current status of the card in the card reader. Status can be PRESENT, ABSENT, SWALLOWED, etc. Also returns the current protocol on use (T0 or T1). This card does not affect the state of the reader or the reader driver.

      Starting a Transaction:

      Function Name: SCardBeginTransaction

      Starts a transaction on the card. During a transaction access to the card is blocked for all other applications. If some other application has started a transaction, the API waits till the transaction gets over.

      Executing Single Commands:

      Function Name: SCardTransmit

      Sends a request to the card and expects the result back.

      Ending a Transaction:

      Function Name: ScardEndTransaction

      Ends a previously started transaction. Other applications can start using the card after this call.


      Function Name: SCardReconnect

      Used to move a card from direct access mode to general access mode, to reset an error condition that is preventing further access to the card, or to change the protocol.


      Function Name: SCardDisconnect

      Terminates the connection between the calling application and the smart card reader.

      Releasing Context:

      Function Name: SCardReleaseContext

      Releases the context handle that was obtained from a previous call to SCardEstablishContext.


Java Card Technology


      When a Java Card is inserted into a card acceptance device (CAD), the CAD selects an applet on the card and sends it a series of commands to execute. Each applet is identified and selected by its application identifier (AID). Commands such as the selection command are formatted and transmitted in the form of application protocol data units (APDUs). Applets reply to each APDU command with a status word (SW) that indicates the result of the operation. An applet can optionally reply to an APDU command with other data.


      Class Structure of The Server Applet:

        The class javacard.framework.Applet provides a framework for applet execution. The Java Card Runtime Environment (JCRE) calls methods defined in this class when it receives APDU commands from the CAD.


        Method Name: install

        After the applet code has been properly loaded on a Java Card and linked with other packages on the card, an applet's life starts when an applet instance is created and registered with the JCRE's registry table. An applet must implement the static method install( ) to create an applet instance and register the instance with the JCRE by invoking one of the two register( ) methods. The install( )method takes a byte array as a parameter. This array contains the installation parameters for initializing or personalizing the applet instance.


        Method Name: register

        This method is used by the applet to register this applet instance with the JCRE and assign either the default AID in the CAD file or a specified AID in the function parameters to the applet instance.


        Method Name: select

        An applet on a Java Card is in an inactive stage until it is explicitly selected. When the JCRE receives a SELECT APDU command, it searches its internal table for the applet whose AID matches the one specified in the command. If a match is found, the JCRE prepares the new applet to be selected. This preparation process consists of two steps: First, if a currently-selected applet is present, the JCRE deselects it by invoking the deselect( ) method. The applet performs any clean-up or bookkeeping work in the deselect( ) method before it goes into the inactive stage. Then the JCRE invokes the select( ) method to inform the new applet that it has been selected. The new applet performs any initialization necessary before it actually becomes selected. The applet returns true to the select( ) method if it is now ready to become active and to process subsequent APDU commands. Otherwise, the applet returns false to decline its participation, and if so, no applet will be selected. The javacard.framework.Applet class provides a default implementation for both the select( ) and deselect( ) methods. A subclass of the Applet class may override these two methods to define the applet's behavior during selection and deselection.


        Method Name: process

        Once an applet is selected, the JCRE forwards all subsequent APDU commands (including the SELECT command) to the applet's process( ) method. In the process( ) method, the applet interprets each APDU command and performs the task specified by the command. For each command APDU, the applet responds to the CAD by sending back a response APDU, which informs the CAD of the result of processing the command APDU. The process( ) method in class javacard.framework.Applet is an abstract method: a subclass of the Applet class must override this method to implement an applet's functions.

        This command-and-response dialogue continues until a new applet is selected or the card is removed from the CAD. When deselected, an applet becomes inactive until the next time it is select.

        Distinguishing Select from Process:

        Method Name: selectingApplet

        Since the SELECT APDU command is also forwarded to the process( ) method, the selectingApplet( ) method is used by the applet's process() method to distinguish the SELECT APDU command selecting this applet from all other SELECT APDU commands that may relate to file or internal applet state selection.

        Providing a Shareable Object:

        Method Name: getShareableInterfaceObject

        Called by the JCRE to obtain a sharable interface object from this server applet on behalf of a request from a client applet.


        Method Name: deselect

        Called by the JCRE to inform the currently selected applet that another (or the same) applet will be selected.

      Interaction between the Terminal and The Server Applet:

        An applet running in a smart card communicates with the terminal application at the CAD using application protocol data units. In essence, the interface between an applet and its terminal application is a set of APDU commands that are agreed upon and supported by both the applet and the terminal application.

        A Java Card applet should support a set of APDU commands, comprising a SELECT APDU command and one or more process APDU commands. The SELECT command instructs the JCRE to select the applet on the card. The set of process commands defines the commands the applet supports. These are defined in accordance with the functions of the applet.

        Java Card technology specifies the encoding of the SELECT APDU command. Applet developers are free to define the encoding of their process commands. However, process commands must comply with the structure outlined above.

        For each command APDU, the applet should first decode the value of each field in the command. If the optional data fields are included, the applet should also determine their format and the structure. Using these definitions, the applet knows how to interpret each command and read the data. It then can execute the task specified by the command.

        For each response APDU, the applet should define a set of status words to indicate the result of processing the paired-command APDU. During normal processing, the applet returns the success status word (0x9000, as specified in ISO 7816). If an error occurs, the applet must return a status word other than 0x9000 to denote its internal state. If the optional data field is included in the response APDU, the applet should define what to return.

        The class javacard.framework.APDU encapsulates APDU commands. When the JCRE receives an APDU command, it encapsulates the command as an APDU object and passes the APDU object to the process() method of the currently selected applet. The APDU object carries a byte array, which contains the APDU message content. Processing the command involves the following steps:

        Retrieving the APDU buffer

        Function Name: getBuffer

        Obtains a reference to the APDU buffer, which contains the message. Only the first five APDU header bytes (CLA, INS, P1, P2, and Lc) are available in the APDU buffer. If the command has optional data it is denoted by Lc.

        Receiving data

        Function Names: setIncomingAndReceive, receiveBytes

        Directs the APDU object to receive incoming data. The data is read into the APDU buffer following the five header bytes. The last byte in the header (Lc) shows the length of the incoming data. If the APDU buffer can't hold all the data, the applet can process the data piecemeal, or it can copy it to an internal buffer. In either case, it would then repeatedly call the receiveBytes( ) method to read additional data into the APDU buffer.

        Returning data

        Function Names: setOutgoing, setOutgoingLength, sendBytes, sendByteLong, setOutgoingAndSend

        After processing the command APDU, the applet can also return data to the CAD in the response APDU. The applet should first call the setOutgoing( ) method to set the data transfer direction to outbound, and to obtain the expected length of response (Le). Le is specified in the command APDU paired with this response APDU.
        Next, the applet calls the setOutgoingLength( ) method to inform the CAD of the actual length of the response data. The applet can move the data to the APDU buffer and call the sendBytes( ) method to send out data. The sendBytes( ) method can be invoked repeatedly if the APDU buffer cannot hold the entire response data.
        If the data is stored in an internal buffer, the applet invokes the sendByteLong( ) method to send data from the buffer. If the response data is short enough to fit into the APDU buffer, the APDU class provides a convenient method for doing so: setOutgoingAndSend( ). This method is a combination of setOutgoing,setOutgoingLength, and sendBytes. However, this method can only be invoked once, and no other send methods can be invoked afterwards.

        Returning a status word

        Function Name: ISOException.throwIt

        Upon a successful return from the process( ) method, the JCRE automatically sends 0x9000 to indicate normal processing. At any point, if the applet detects any error, the applet can throw an ISOException by invoking the static method ISOException.throwIt(short reason). The status word is specified in the parameter reason. If the ISOException isn't handled by the applet, it will be caught by the JCRE. The JCRE retrieves the reason code and sends it as the status word.





      Before a smart card can be accessed, OCF must be initialized. This gets the necessary CardTerminal components loaded for the installed hardware and begins the processing necessary to determine when a card has been inserted. An application can declare itself to be a listener for OpenCard events so that it will automatically be informed when a card is inserted or removed. To do this, an application class must implement the CTListener interface and register itself as a listener with the CardTerminalRegistry.

              SmartCard.start ( ); // Initialize the framework
              // register as a Card Terminal Event Listener
              CardTerminalRegistry.getRegistry( ).addCTListener(this);

      As soon as the initialization has been carried out, the application class implementing the CTListener interface will be informed whenever a smart card is inserted or removed from the terminal. The CardTerminalRegistry informs the application class of these events by calling the cardInserted() and cardRemoved() methods. The application can react appropriately to the event, displaying necessary messages, etc.

      Obtaining Card Services

      In the implementation of cardInserted(), the SmartCard object representing the inserted card can be retrieved from the event. The SmartCard object is capable of providing all available card services to the application. For example, FileAccessCardService and the SignatureCardService are needed in order to read data from files on the card and to digitally sign data.

      Some types of smart card access require the card holder to enter a password or to undergo some other form of card holder verification (CHV). If the application requires this type of access, it must provide a function that will allow the card service to obtain the password to the user. This is done by implementing the CHVDialog interface and passing a corresponding instantiated object to the card service using thesetCHVDialog() method.

              public void cardInserted(CardTerminalEvent ctEvent)
                try {
                  fileService = (FileAccessCardService)
                    card.getCardService(FileAccessCardService.class, true);
                  signatureService = (SignatureCardService)
                    card.getCardService(SignatureCardService.class, true);
                  SBCHVDialog dialog = new SBCHVDialog();
                catch(Exception e) 

      Reading a File

      After a card has been inserted and the necessary card services have been obtained, data can be read from the card using the FileAccessCardService.

              // mount file system to get access to the root directory
              CardFile root = new CardFile(fileService);
              // This is the file holding card holder data
              CardFile file = new CardFile(root, ":C009");
              // Create a CardFileInputStream for file
              DataInputStream dis = 
              	new DataInputStream(new CardFileInputStream(file));
              // Read in the holder's name
              byte[] cardHolderData = new byte[file.getLength()];  
              // Explicitly close the InputStream 
              // to yield the smart card to other applications
              dis.close( );

      Generating a digital signature

      First the private key to be used in the signing process must be selected. The private key stored on the card is represented by a PrivateKeyFile object, which is created through specification of the appropriate file ID. The signatureService.signData() method is used to pass the data to be signed to the card. Along with the data, the key file, algorithm name, and padding type to be used must be provided to the function. After successful execution, the digital signature corresponding to the data is returned to the application.

              // specify the key used for signing
              PrivateKeyFile kf = 
              	new PrivateKeyFile (new CardFilePath(":C110"), keyNumber);
              // Let the card generate a signature
              signature = 
              	signatureService.signData(kf, JCAStandardNames.SHA1_RSA,
              		JCAStandardNames.ZERO_PADDING, data);

      Listing Applications

      Card-resident applications are described by meta-information encapsulated in AppletInfo objects, which includes the user-friendly label and the AppletID. A card applet refers to either a program that can be executed on the card itself (like a Java Card applet), or it can be an application specific set of files and directory structures (on ISO complaint file-system oriented cards). Use the AppletAccessService to list the available AppletInfo’s and select the appropriate one.

              AppletInfo [] templates = null;
              	AppletAccessCardService aacs = null;
              	aacs = (AppletAccessCardService) 
              		card.getCardService(AppletAccessCardService, true);
              	templates = aacs.list();
              	// evaluate templates, and select one
              	// use the selected applet
              		AppletID aid = templates[0].getAid( );	
              		// 0th index selected
              		CardFilePath  filepath = 
              			new CardFilePath(aid.toString( ));
              	catch Opencard Exceptions
              		// handle exceptions
              catch  Opencard Exceptions
              	// handle exception


      Finally, when the application is finished accessing the smart card, the framework should be terminated to allow OCF to shutdown in an orderly fashion and to avoid wasting resources.

              SmartCard.shutdown ();


      Writing a Card Terminal is not particularly difficult provided you know everything about your card reader. A CardService generates APDU’s to implement high level API functions, thus hiding smart card specifics. Further information regarding this is available at OpenCard website.