Java Card Applet

Applications that run on Java smart cards are called applets. This chapter describes the applet development environment. The chapter consists of seven sections. The first section discusses the general principles of how applets work in the JCRE environment. The remaining sections are devoted to the methods of applet development.
The properties of applets are described in detail throughout the book. For example, Chapters 8 and 9 discuss the processing of APDU commands and the sharing of objects by different applets.

The Java Card applet is an application designed to run on a smartcard, which is written in the Java programming language and conforms to a set of conventions that allow it to work in the Java Card Runtime Environment (JCRE). The applet running in the JCRE environment is an instance of the applet class that inherits from the javacard class.framework. Applet. As in the case of in addition to other permanent objects, the lifetime of the applet on the card coincides with the period of its operation1. The Java Card platform supports many applications. Each instance of the applet has a unique application identifier – AID (detailed information about application identifiers was described in Chapter 3).

Installing and executing applets

The installation of the applets includes the following steps: first, the Java package(s) that make up the applet are written to the smart card. These packets are then linked to other packets on the card. The life cycle of an applet begins at the time of creation and registration of its instance in the JCRE runtime environment. JCRE is a single–threaded environment. This means that only one applet can be executed at a time. After the initial installation of the applet, it is in an inactive state. The applet becomes active only after it is explicitly selected by the host application.
Applets, like all smart card applications, provide only a response to external influences. Usually, after activation, the applet goes into a state of waiting for a command from the host system. The applet then executes the command and sends a response to the host application.

Interaction of the host system and applets

The interaction of the host system and applets is carried out by exchanging commands and APDU responses, as shown in Figure 7.2. The APDU block contains either a command or a response message. The host application sends a command to the applet, it executes it and returns a response. (The APDU protocol was discussed in more detail in Chapter 2.)
When the host application wants to select an applet to execute, it sends an APDU block that contains the SELECT command and the AID of the requested applet. JCRE scans the internal table of installed applets and finds an applet whose AID corresponds to the one specified in the command. If the match is established, JCRE activates the specified applet. All subsequent APDU commands (including SELECT APDU) are redirected to the active applet until another applet is selected.

Each applet is implemented by creating a javacard subclass. framework.Applet. JCRE calls the install, select, process, or deselect methods defined in the Applet base class to install, activate the applet, pass the APDU command to it for processing, or deselect. Methods of the javacard class are given.framework.Applet. They are listed in the order in which JCRE calls them during the creation and execution of the applet. To create an instance of the applet, JCRE calls the install method. Then the applet instance is registered in JCRE. To do this, one of the two register methods is used.

After receiving the SELECT APDU command, JCRE first checks whether any applet has already been selected. If so, JCRE deactivates the currently active applet by calling its deselect method. In the deselect method, the applet performs any actions to clean up resources or save its state before becoming inactive. JCRE then calls the select method to select a new applet. All actions to initialize the applet are performed in the select method.
After the applet is successfully selected, it becomes active, and all APDU commands (including SELECT APDU) are redirected to it. To do this, JCRE calls the process method of the active applet. The process method is an important method of the applet class. It handles APDU commands, providing applet functions.
The install, select, deselect and process methods are the entry points to the applet. JCRE calls these methods at certain stages of applet creation and execution. The Applet base class provides only default actions for these methods. In order for the applet to perform its functions, some or all of these methods must be redefined. Later in this chapter, we will look at each method in detail.

JCRE usually calls the install method at the last stage of the applet installation to create an instance of it – a workable applet. The install method is similar to the main method in a Java application. The arguments of the install method are intended to pass the installation parameters. They are analogs of command-line arguments that are passed to the main method.

An instance of the applet is created in the install method. First, the new operator is executed, then the applet constructor is called. The applet constructor usually performs the following tasks:
· Creates objects needed by the applet during its lifetime.
· Initializes the objects and internal variables of the applet.
· Registers an instance of an applet in JCRE by calling one of the two register methods defined in the Applet base class.

After the applet is registered, the time of its existence begins. In order for the JCRE environment to select an applet and transfer control to it, the applet must register with JCRE.
Below is an example of the code that illustrates the creation
of the “electronic wallet” applet. The default constructor is used.

public class WalletApp extends Applet{

private Log transaction_log; private byte[] wallet_id; private byte wallet_balance;
public static void install
(byte[] bArray, short bOffset, byte bLength) { new WalletApp();
}

private WalletApp() {

// creating an operation log with a certain number
of // operation records
transaction_log = new Log(TRAN_RECORD_NUM);

// creating a byte array to store the wallet ID
wallet_id = new byte[ID_LENGTH];

// initialization of the balance of the “electronic wallet”
wallet_balance = INITIAL_BALANCE;

// registering an applet instance in JCRE register();
}
}

Another option is also possible: in the applet, you can define a constructor to which the installation parameters will be passed.

public walletApp(byte[] bArray, short bOffset, byte bLength) {…}

Installation parameters are additional data for initialization and configuration of the applet.
After successful execution of the install method, the applet can be selected by JCRE to process the APDU commands coming from the host system. Only one instance of the applet can be created and registered in one call of the install method. To create multiple instances of the same applet, JCRE must call the install method several times.

If an error occurred during the execution of the install method (before registering the applet using the register method), JCRE performs the necessary actions to clean up the card resources in order to free them for future use. JCRE deletes the applet instance and other objects that were created when executing the install method, and goes to the previous state. There is no need to specify transactions in the install method, because JCRE uses its own internal transaction in this method. Applet registration means that the transaction was completed successfully. Therefore, it is important to provide that the final step of creating an applet is registration. If an error occurs after executing the register method, the applet remains registered, but may be unusable.
Note that the install method of the Applet base class is just a prototype. The applet should define the install method based on this prototype.

Creating objects in the applet constructor

Despite the fact that objects and arrays can be created at any time of the applet execution, if possible, it is recommended to perform these operations only during the initialization of the applet. All objects that may be required by the applet at runtime must be created in advance in its constructor. This is a guarantee that the execution of the applet will never be interrupted due to lack of memory.
The constructor is called from the install method. Thus, if JCRE detects a lack of resources and cannot allocate memory for the applet during the creation of the object or during the allocation of other resources, JCRE will delete the applet and free up all the memory allocated for it. If you use this method, there will never be a partially initialized inoperable applet in the memory of the card.
However, it is necessary to make sure that the object does not create more objects than is required for its operation, because the memory occupied by them cannot be freed or shared by other applets or JCRE.

Registering an applet instance in JCRE

To register an applet in JCRE, use one of the two register methods defined in the Applet base class.

protected final void register()

or

protected final void register
(byte[] bArray, short bOffset, byte bLength)

Processing installation parameters

Usually, during the installation of an applet, the installation parameters are transferred to the card along with CAP files that define the contents of the applet. JCRE then passes these parameters to the applet via the arguments of the install method. The install method provides three arguments:
· byte[] bArray – an array containing the installation parameters.
· short bOffset – the initial offset in the bArray.
· byte bLength – the length in bytes of the parameters written to the bArray. The content and format of the installation parameters are determined by the developermi applet or card issuers. Often the installation parameters include information for configuration and values for initialization of any applet variables. Configuration parameters, for example, may contain the size of an internal file, an array, as well as other information. This initialization method allows the applet to take up enough memory for its further operation and not waste memory in vain. Installation parameters may also contain values for initializing some applet variables. For example, for the “electronic wallet” applet, this can be the initial balance, the cardholder ID and the account number. The applet’s AID can also be passed through the installation parameters, which is different from the default value from the CAP file. For example, imagine that you need to create two copies of the “electronic wallet” applet: one will be associated with the cardholder’s personal account, and the second with his company account. In this case, JCRE should call the install method twice. Each instance of the applet must be assigned a unique AID.

Let’s assume that the developer of the “electronic wallet” applet has provided the following fields in the array of installation parameters:

  1. A binary field with a length of 1 byte is the number of entries in the transaction log.
  2. Fixed-length array (4 bytes) – wallet ID.
  3. A binary field with a length of 1 byte is the initial balance of the wallet.
  4. A binary field with a length of 1 byte is the length of the next subarray.
  5. Variable–length array – AID of this applet instance. If this array is empty, the default AID value from the CAP file will be used to register an applet instance.
    To create an instance of the “electronic wallet” applet for working with a personal account, for registration of which the default AID value will be used, installation parameters can be transferred to the card, making up the following sequence of bytes: [0x10, 0x1, 0x2, 0x3, 0x4, 0x32, 0]. The applet will interpret them as follows:
    · number of entries in the transaction log = 0x10 = 16
    · wallet ID = [0x1, 0x2, 0x3, 0x4]
    · initial balance = 0x32 = 50
    · AID = default AID from CAP file
    To create an instance of the “electronic wallet” applet for working with a company account, for registration of which an AID other than the default value will be used, installation parameters can be transferred to the card, making up the following sequence of bytes: [0x10, 0x4, 0x3, 0x2, 0x1, 0x64, 0xF, ‘B’, ‘A’, ‘N’, ‘K’, ‘’, ‘w’, ‘a’, ‘l’, ‘l’, ‘e’, ‘t’, ‘’, ‘B’, ‘I’, ‘S’]. The applet will
    interpret them as follows:
    · number of entries in the transaction log = 0x10 = 16
    · wallet ID = [0x4, 0x3, 0x2, 0x1]
    · initial balance = 0x64 = 100
    · AID = [‘B’, ‘A’, ‘N’, ‘K’, ‘’, ‘w’, ‘a’, ‘l’, ‘l’, ‘e’, ‘t’, ‘’, ‘B’, ‘I’, ‘S’]
    Here is an example of code that demonstrates the process of processing installation parameters by the applet constructor:

private WalletApp(byte[] bArray, short bOffset, byte bLength) {

// creating an operation log with a certain number
// of operation records
// max_record_num = bArray[bOffset] transaction_log = new Log(bArray[bOffset++]);
// setting the wallet ID
wallet_id = new byte[ID_LENGTH];
Util.arrayCopy(bArray, bOffset, wallet_id, (byte)0, ID_LENGTH]);
// increasing the value of bOffset by ID_LENGTH bytes
bOffset += ID_LENGTH;

// initializing the balance of the “electronic wallet”
wallet_balance = bArray[bOffset++];

// AID check
byte AID_len = bArray[bOffset++]; if (AID_len == 0) {
// registering an applet instance in JCRE
// using the default AID value
this.register();
} else {
// registering an applet instance in JCRE
// using the AID value specified in the installation parameters.
// The value of AID in the array bArray starts with the offset bOffset
// the length of AID is equal to AID_len bytes
this.register(bArray, bOffset, AID_len);
}
}

The contents of the array bArray are not the property of the applet. For security reasons, JCRE clears this array when returning from the install method. If any of these data needs to be saved in the applet, it is necessary to provide for copying them into its own object. In our example, the wallet ID is copied from the bArray to the wallet_id field.
The maximum length of installation parameters supported by the Java Card platform is 32 bytes. Thus, the maximum value of bLength is 32. In Chapter 8, you will see that JCRE uses a buffer to transmit commands over the APDU protocol. The minimum size of the APDU buffer is 37 bytes, including a 5-byte header and 32 bytes of data. The maximum length of the installation parameters, equal to 32 bytes, was chosen so that they could be transferred to the card with a single APDU command.
Additional initialization of applets

After successful completion of the install method, simple applets can be fully ready to work. But in order to organize the work of more complex applets, additional information may be required to configure them. This information may not be available at the time of applet creation, or its length may exceed the maximum length of installation parameters (32 bytes). In this case, a separate scheme for configuring the applet can be provided in the process method. It is determined by the applet developers or card issuers. The additional initialization scheme provides that the applet assigns the transmitted values to its internal variables, and then monitors changes in its state. To obtain additional information necessary to complete initialization, the applet exchanges APDU blocks with the host system.

The applet remains in an inactive state until it is explicitly selected for operation. Activation of the applet occurs after JCRE receives the SELECT APDU command, which specifies the AID of the selected applet. JCRE informs the applet that it is selected by calling its select method.

In the select method, the applet can check whether all the conditions necessary for its activation are met. If everything is in order, the applet can set the values of its internal variables necessary to process subsequent APDU commands. The select method returns true if the applet is ready to process incoming APDU commands using its process method. The applet can also reject the selection. To do this, the select method can return false or raise an exception.

If the activation of the applet failed, JCRE returns the status word 0x6999 to the host system. If the select method returns true, JCRE calls its process method and redirects the SELECT APDU command to it so that the applet can pass any information necessary to start the interaction to the host application. For example, the e-wallet applet can send the issuer’s identification number, currency conversion information, or other parameters to the host system. This information may be required by the host application to start a debit or credit transaction. The content and format of the response to the SELECT APDU command are determined by the applet developers or card issuers.
The select method of the Applet base class simply returns true. The applet developer can override this method to perform the necessary actions during the applet selection process.

Format and processing of the SELECT APDU command

SELECT APDU is the only standardized APDU command of the Java Card platform. It defines a compatible mechanism for selecting applets for different implementations of the Java Card platform. The format of the SELECT APDU command is shown in Table 7.2. The data field of the SELECT APDU command contains the AID of the applet. Its length can be from 5 to 16 bytes. In order for the applet to be selected, an exact match of the APDU data field with the AID of the applet is required.
After receiving the APDU command, JCRE decodes its header (fields CLA, INS, P1 and P2) to determine the type of command. If this is an applet selection command, the applet whose AID exactly matches the value of the data field is searched on the card. If such an applet is found, JCRE cancels the selection of the current applet, selects a new applet, runs its process method and passes it the SELECT APDU command. If the received command is not an applet selection command, JCRE redirects it to the current applet for processing. In any case, if an error occurs during the applet selection process, JCRE signals this by returning the 0x6999 status word to the host application, and there is not a single active applet on the card. The processing of the SELECT APDU command.

Default Applet

Usually, the applet is activated only as a result of the successful execution of the SELECT APDU command. However, some smart card systems require a default applet, which is selected implicitly after each card reset.
To select the default applet, JCRE calls the select method of the applet defined by default and marks this applet as active. Since the SELECT APDU command was not received, the process method of the applet is not called after the selection. If the select method of the applet provided by default throws an exception or returns false, no selected applet remains on the card until the processing of the next received SELECT APDU command is completed.

The default applet selection is an optional JCRE function. If this feature is supported, the JCRE implementation should provide a mechanism for selecting the default object.
Before activating a new applet, JCRE deactivates the current applet by calling its deselect method. There may be a situation when the newly selected applet turns out to be the same applet. In this case, JCRE will deactivate it first anyway, and then activate it again.

The deselect method allows the applet to perform all the necessary actions to clean up the card resources and prepare for “shutdown” in order to allow the next applet to be launched for execution. The deselect method defined in the default Applet class is empty. The applet developer can override this method in order to perform the necessary actions to clean up resources during the deactivation of the applet. For example, the “electronic wallet” applet can reset the set security level or the status of an operation that is valid only for one period of activity.

During the execution of the deselect method, a failure may occur. But even in this case, the current applet is deactivated and a new applet is activated, regardless of the results of executing the deselect method. JCRE also ignores any exceptions raised in the deselect method.
Moreover, in the event of a reset or power outage, JCRE automatically deactivates the current applet without calling its deselect method. Therefore, the applet developer should not hope that all cleaning operations will be performed by the deselect method.

When JCRE receives the APDU command, the process method of the current applet is called. It is assumed that the process method of the applet contains the functions necessary for processing APDU commands and generating responses to them. The process method of the Applet base class is an abstract method. The applet must directly or indirectly override this method. Usually the process method is implemented as a dispatcher. After receiving the APDU command, this method decodes the APDU header and calls the service method to perform the requested function. JCRE passes the parameters of the APDU command to the applet via the apdu argument of the process method (an instance of the APDU class). The applet calls the methods of the apdu object to exchange data with the APDU block.

The Applet class contains two more methods: selectingApplet and getShareableInterfaceObject.
Traditional smart cards are file system oriented. Application data is stored in files. Before performing any operations with the data from the file, it must be opened. Readers familiar with ISO 7816 commands will understand that the SELECT APDU command, the format of which is given in Table 7.2, is an ISO command to open a directory (DF, dedicated file) by name. JCRE determines whether the received APDU command is an applet activation command by comparing the value of the command data field with the AID of all the applets available on the

Other methods of the javacard class.framework.Applet

Due to the fact that all APDU commands are redirected to the process method of the currently active applet, it must call the selectingApplet method to determine whether this SELECT APDU command is intended to activate this applet, or it is an attempt to open the directory of this applet. The selectingApplet method returns true if the APDU command is going to activate this applet. Otherwise, it returns false.

The getShareableInterfaceObject method is designed for sharing objects by different applets. JCRE calls this method when another applet requests access to the shared interface object of this applet. The getShareableInterfaceObject method will be discussed in detail in Chapter 9, which is devoted to the applet security system and object sharing.