Understand the internal working principles of Java card architecture APIs and runtime Environments

Source: Internet
Author: User
ArticleDirectory
    • Summary
    • What is Java card?
    • Java card Lifecycle
    • Java card VM Lifecycle
    • Java card Applet and object Lifecycle
    • Ava card 2.0 language subset
    • Java card 2.0 Framework
    • Java card security
    • Java card Internal Working Principle
    • How to compile a Java card application?
    • Conclusion
    • References
Summary

Java card can run JavaProgram. For this new Java platform, sun's supervisor oft Department has developed Java card 2.0 API technical specifications. At present, several grantees have implemented this API on smart cards. To write a 2.0-compatible Java card application, developers need to understand the connotation of Java card from the architecture, the meaning of its kernel class, and how to develop applications for smart card. This article will discuss in detail the Java card technology, providing you with technical guidance on the system architecture, application programming interfaces, and runtime environment of the Java platform in the smart card. (4,000 words)

author: zhiqun Chen, Rinaldo di Giorgio
this article will first briefly introduce the smart card and briefly review the standard ISO 7816. According to a previous article on smart card published by Java developer (developer column), this article will first answer the following question: "What is Java card? ", And briefly introduces the Java card system architecture. Then, we will focus on several issues related to Java card (including Java card lifecycle, Java card 2.0 language subset and api library class, and Java card security ). Then we will discuss the Java card runtime environment and how Java card works. The last example illustrates the Java card application: the E-wallet application for Java card.
when Java card is mentioned in this article, Java card 2.0 is used.
what is a smart card?
the size of a smart card is the same as that of a credit card. You can store and process information by embedding an electronic circuit on a silicon wafer in a plastic substrate. Smart cards are mainly divided into two categories: including smart cards with microprocessor and reading, writing and computing functions (such as small microcomputer ). Another type is a memory card without a microprocessor. It can only store information. The memory card uses the security logic algorithm to control access to the memory.
all smart cards have three types of memory:
persistent non-mutable memory; persistent mutable memory ); non-permanent variable memory (non-persistent mutable memory ). Rom, EEPROM, and RAM are currently the most common types of smart card memory. Permanent memory is also called non-volatile memory. In this article, we will alternate the use of term permanent memory and non-volatile memory.
Part 1-7 of ISO 7816 stipulated by the International Standards Organization includes a set of standards covering all aspects of smart cards. ISO 7816 includes:

    • Physical Features (Part 1)
    • Dimensions and contact positions (Part 1)
    • Electronic Signal and transmission protocols (Part 1)
    • Inter-industry exchange commands (Part 1)
    • Application Identifier (Part 1)
    • Data elements between industries (Part 1)
    • Inter-industry scql commands (Part 1)


Indicates the physical properties of a smart card, which is specified in section 7816 of ISO 1st.
Physical characteristics --- physical characteristics
Magnetic stripe (back of card) --- magnetic stripe (back of card)
Contacts --- contacts
Embossing area --- lettering Area
Front of card --- front of card

For details about ISO 7816 and smart card, see "Smart Card: Getting started ".
Generally, smart cards do not include power supplies, display screens, or keyboards. It interacts with the external world through its eight contacts using a serial communication interface. ISO 7816 Part 1 provides detailed specifications on the size and contact position of the smart card. The contact of the smart card.
 
Eight contact points --- 8 contacts
Power Supplier --- Power Supply
Reset --- Reset
Check --- check
Ground --- ground
Optional contact --- optional contact
Input/Output --- input/output
Optional contacts --- optional contact

Smart Card insertion may be connected to another computer card receiving device (CAD ). Card receiving devices are also called terminals, card readers, and IFD (interface devices ). All have the same basic functions, that is, to provide power to the smart card and establish a data transmission connection.

When two computers communicate with each other, they exchange packets constructed based on a series of protocols. Similarly, smart cards use their own data packets, called APDU, to communicate with the outside world. APDU contains a command or response message. In the world of smart cards, the master-slave model is used, and smart cards always play the role of the slave. In other words, the smart card is always waiting for the command APDU from the terminal. Then, it executes the action specified by APDU and responds to the terminal with a response. The smart card and the terminal exchange commands APDU and respond to APDU.

The following table lists the formats of commands APDU and responses to APDU. The structure of APDU is described in Section 7816 of ISO 4th.

Command APDU
Title header (required) Subject (optional)
CIA INS P1 P2 LC Data Field Le


The title header encodes the selected command. It includes four fields: Class (CIA), command (INS), and parameters 1 and 2 (P1 and P2 ). Each field contains one byte:

    • Class-byte. On many smart cards, this byte is used to represent applications.
    • INS: The Instruction byte. This byte indicates the instructionCode.
    • P1-P2: parameter byte. These bytes further describe the APDU command.


LC indicates the number of bytes in the data field of The APDU command; Le indicates the number of bytes in the following data field that responds to APDU.

Reply to APDU
Subject (optional) Tail (required)
Data Field SW1 Sw2


Status bytes SW1 and sw2 indicate the processing status of the command APDU in the smart card.

What is Java card?

Java card is a smart card that can run Java programs. Java card 2.0 technical specifications are published at http://www.javasoft.com/javacard. It includes detailed information about creating Java card virtual machines and application programming interfaces (APIS) on smart cards. The minimum system requirements are 16 kbps read-only memory (ROM), 8 kbps EEPROM, and 256-byte random access memory (RAM ).

The system architecture on Java card is shown in the following figure. Where:
Applet --- small Application
Industry add on classes --- enterprise add class
Javacard framework --- javacard framework
OS & native functions --- operating system and local functions

As shown in the figure, the Java card virtual machine is built on a specific IC and the execution program of the local operating system. The JVM layer uses general languages and system interfaces to hide the manufacturer's patented technologies. The Java card Framework defines a series of application programming interfaces (APIS) used to develop Java card applications and provide system services for these applications ). An added library can be provided for a specific industry or special business application to provide services or optimize security and system models. The Java card application is called applets. Multiple applets can reside on one card. Each applets is uniquely identified by its aid (application identifier), as specified in section 7816 of ISO 5th.

It is important to note that smart cardsNoPC. They only have limited storage resources and computing functions. Users should not simply consider Java card 2.0 as a simplified JDK version.

Java card Lifecycle

The life cycle of Java card starts when the local operating system, Java card virtual machine, API class library, and optional applets are written into the Rom. Writes a permanent component that can process incoming commands into the chip's non-variable memory. This process is also called a mask ).
Java card needs to be initialized and customized before it is installed into your wallet. Initialization refers to loading general data into the non-variable memory of the card. This type of data is the same for many smart cards, not specific to a specific card; for example, the name of a publisher or manufacturer.
The next step, personalization, refers to assigning cards to someone. This process can be done through physical or electronic personalization. Physical personalization refers to the stamping of your name and card number on the surface of the plastic card or laser. Electronic personalization refers to the loading of personal data, such as your personal key, name, and personal identity code, in the non-variable memory of the card.
Manufacturers and publishers use different initialization and personalization methods. For these two processes, data is usually stored using EEPROM (a class of non-variable memory.
Now, Java card can be used. You can buy a Java card from a publisher or from a retailer. The cards sold by retailers are generic and generally not personal.
Now, you can insert your Java card into the card reader, send the command APDU to the applet residing on the card, or download other applets or data to the card.
Unless the Java card fails or is locked due to an irreparable error, the Java card will continue to be used.

Java card VM Lifecycle

Unlike the Java Virtual Machine (JVM) on a PC or workstation, the Java card virtual machine can always work.

Even if the power supply is disconnected (that is, the card is removed from the card reader), most information stored on the card must be saved. The Java card virtual machine can create objects on the eeprom that can save permanent information. The life of a Java card VM is the life of a card. In the absence of power, virtual machines work in an infinite clock cycle.

Java card Applet and object Lifecycle

The lifecycle of an applet starts when it is correctly installed and registered to the registry of the system. When it is deleted from the Registry, its lifecycle ends. The deleted applet space may be used again or no longer, depending on whether the spam function is enabled on the card. The applet on the card is activated only when it is explicitly selected by the terminal.

Objects are created in permanent memory (such as EEPROM. If the object is not referenced by other permanent objects, it may be lost or used as garbage collection. However, the write speed to EEPROM is 1000 times slower than that to ram.

Some objects are often used, so the content of their fields does not have to be permanent. Java card supports transient (temporary) objects in Ram. If an object is declared as transient, its content cannot be written to permanent storage.

Ava card 2.0 language subset

Of course, the Java card program is written in Java. They can be compiled using a general Java compiler. Due to limited storage resources and computing capabilities, Java card does not support all the language functions specified in the Java language technical specifications. In particular, Java card does not support:

    • Dynamic class loading
    • Security Manager
    • Thread and Synchronization
    • Object Replication
    • Finalization)
    • Long Basic Data Types (float, double, long, and char)

Therefore, it is not surprising that the keywords that support these functions are omitted. On a more advanced smart card with larger memory, the real-time users of the Virtual Machine decide whether to support the 32-bit integer type and the native method of the Post-issuance applet. Post-issuance applet is the applet installed on Java card after the card is issued to the cardholder.

Java card 2.0 Framework

Smart cards have been on the market for more than 20 years. Most smart cards are generally compatible with Parts 1-7 and/or EMV of ISO 7816. We have discussed ISO 7816 before. What is EMV? EMV is a standard based on the ISO 7816 series set by companies such as Europay, MasterCard, and visa. It has additional patent functions that meet specific requirements of the financial industry. The Java card framework is designed to easily support smart card systems and applications. It hides the details of the smart card architecture and provides relatively simple and direct programming interfaces for Java card application developers.

The Java card framework includes four packages:

Package name Description
Javacard. Framework This is the javacard kernel package. It defines classes such as Applet and personal identity code (PIN, these classes are basic components of the Java card program and APDU, system and util (providing runtime services and system services for Java card programs and APDU, such as APDU processing and object sharing.
Javacardx. Framework This package provides an object-oriented design for file systems compatible with ISO 7816-4. It supports basic files (EF), specialized files (DF), and file-oriented APDU specified by ISO 7816.
Javacardx. crypto and javacardx. cryptoenc The two packages support the password function required by the smart card.


The Java cardx package conforms to the Java Naming principles and is an extension of the Java card framework. You do not have to support these packages on a smart card.

Java card security

Java applets is restricted by Java security, but the Java card system's security mode is different from standard Java in many aspects.

Java card does not support the security manager class. The language security policy is implemented by virtual machines.

Java applets creates objects that can store and process data. The object is owned by the applet that created the object. Even if the applet references an object, it cannot call the method of the object unless it owns the object or the object has been shared. An applet can share its objects with another applet or all applets.

Applet is an independent entity in Java card. Its selection, execution, and function are not affected by other applets residing on the same card.

Java card Internal Working Principle

Inside Java card, JRE (Java card Runtime Environment) References classes in the Java card Virtual Machine and Java card framework. Each Applet in Java card is associated with a specific aid granted by JRE.

When an applet is correctly loaded into the permanent memory of the card and associated with the Java card framework and other libraries on the card, it serves as the last step of the applet installation process, JRE calls the installation method of the applet. Install is a public static method, which is implemented by the Applet Class to create an applet instance and register it in JRE. Because memory is limited, a better programming method is to create and initialize the objects required by the applet during its life cycle.

The applet residing on the card is activated only after it is explicitly selected. The terminal sends a "select APDU" command to JRE. JRE pause the selected Applet and call the deselect method of the applet to clear the selected applet. Then, JRE marks the applet specified by aid in "select APDU" as the selected Applet and calls the select method of the newly selected applet. The select method prepares the applet to accept the APDU command. JRE sends the subsequent APDU command to the selected applet until it receives the next "select APDU" command.

How to compile a Java card application?

The best way to create a Java card 2.0 applet is through the example. The following example shows an e-wallet application that can store e-cash. This wallet can process APDU commands such as read_balance, deposit, and debit. Only the personal identity code (PIN) of the wallet owner can access the wallet.

This example is formatted as two columns: the left column contains Java code and Java-style annotations, And the right column provides a detailed explanation of the Code on the left column.

Package bank. Purse Similar to standard Java, Java card also supports the conventions of packages and identifiers.
Import javacard. Framework .*;
Import javacardx. Framework .*;
 
Public class wallet extends applet {
/* Constants Declaration */
An applet is an example of the successor class of javacard. Framework. applet.
// Code of linoleic byte in the command APDU header final static byte wallet_linoleic = (byte) 0xb0; The content of the application
// Code of INS byte in the command APDU Header
Final Static byte deposit = (byte) 0x10;
Final Static byte debit = (byte) 0x20;
Final Static byte balance = (byte) 0x30;
Final Static byte validate = (byte) 0x40;
INS identifies application commands
// Maximum number of incorrect tries before the PIN is blocked
Final Static byte pintrylimit = (byte) 0x03;
// Maximum size pin
Final Static byte maxpinsize = (byte) 0x04;
Pin object parameters
// Status word (SW1-SW2) to signal that the balance become neagtive;
Final Static short sw_negative_balance = (short) 0x6910;
Applet-specific static words
/* Instance variables Declaration */
Ownerpin;
Byte balance;
Byte buffer []; // APDU Buffer
 
Private wallet (){
// It is good programming practice to allocate
// All the memory that an applet need during its
// Lifetime inside the constructor
Pin = new ownerpin (pintrylimit, maxpinsize );
Balance = 0;
Register ();
} // End of the constructor
Private constructor --- the wallet-like instance is instantiated by its install method
The applet registers to JRE by calling the register method defined in the Applet Class. Currently, the applet is visible externally.
Public static void install (APDU ){
// Create a wallet applet instance
New wallet ();
} // End of install method
In the last step of the applet installation process, the Method Install is called by JRE.
Public Boolean select (){  

 

// Returns true to JRE to indicate that the Applet
// Is ready to accept incoming apdus.
Return true;
} // End of select Method
This method is called by JRE, indicating that the applet has been selected. It performs the necessary initialization required to process the following APDU Information
Public void process (APDU ){
// APDU object carries a byte array (buffer)
// Transfer incoming and outgoing APDU Header
// And data bytes between card and CAD
Buffer = APDU. getbuffer ();
After the applet is successfully selected, JRE sends the access APDU to this method.
The APDU object is owned and maintained by JRE. It encapsulates the details of underlying basic transfer protocols (such as t0 or t1 defined by the ISO7816-3) and provides a general interface.
// Verify that if the applet can accept this
// APDU message
If (buffer [ISO. offset_linoleic]! = Wallet_cia)
Isoexception. throwit
(ISO. sw_cla_not_supported );
When an error occurs, the applet may decide to abort the process and throw an exception containing the status word (SW1 sw2). The status word is used to indicate the processing status of the card.
switch (buffer [ISO. offset_ins]) {
case balance: getbalance (APDU); return;
case debit: debit (APDU); return;
case deposit: deposit (APDU); return;
case validate: Validate (APDU); return;
default: isoexception. throwit
(ISO. sw_ins_not_supported);

}

}// end of Process Method

the main function of the process method is to execute the action specified by APDU and return the correct response to the terminal.
ins bytes specify the type of the action to be executed
private void deposit (APDU) {
// access authentication
If (! Pin. isvalidated ()
isoexception. throwit (ISO. sw_pin_required);
// LC byte denotes the number of bytes in the Data
// field of the command APDU
byte numbytes = (byte) (buffer [ISO. offset_lc]);
// indicate that this APDU has incoming data and
// receive data sharing from the offset
// ISO. offset_cdata
byte byteread = (byte) (APDU. setincomingandreceive ();
// It is Error if the number of data bytes read does // not match the number in LC byte
If (byteread! = 1)
isoexception. throwit (ISO. sw_wrong_length);
// increase the balance by amount specified in the
/data field of the command APDU
balance = (byte)
(balance + buffer [ISO. offset_cdata]);
// return successfully
return;
}// end of deposit method
The APDU object contains a data field that specifies the deposit amount.
after the APDU object is received from JRE, the first five bytes of the APDU buffer are available (linoleic, INS, P1, P2, LC/Le. Its offset in the APDU buffer is specified in the ISO class. Because the data field is optional, the applet needs to explicitly notify JRE to obtain additional data bytes.
the communication between the card and CAD is exchanged between the command APDU and the response APDU pair. In the deposit example, the response APDU does not contain data fields. JRE uses the status word 0 × 9000 (normal processing) to form a correct response to APDU. Applet developers do not have to worry about the details of constructing a correct response to APDU.
when JRE captures an exception (indicating an error occurred while processing the command), JRE constructs a response to APDU using the status word contained in the exception.
private void debit (APDU) {
// access authentication
If (! Pin. isvalidated ()
isoexception. throwit (ISO. sw_pin_required);
byte numbytes = (byte) (buffer [ISO. offset_lc]);
byte byteread = (byte) (APDU. setincomingandreceive ();
If (byteread! = 1)
isoexception. throwit (ISO. sw_wrong_length);
// balance can not be negative
If (balance-buffer [ISO. offset_cdata]) <0)
isoexception. throwit (sw_negative_balance);
balance = (byte)
(balance-buffer [ISO. offset_cdata]);
}// end of debit method
In the debit method, The APDU object contains a data field that specifies the withdrawal amount.
private void getbalance (APDU) {
// access authentication
If (! Pin. isvalidated ()
isoexception. throwit (ISO. sw_pin_required );
// inform system that the applet has finished processing
// The command and the system shoshould now prepare to
// construct a response APDU which contains data field
APDU. setoutgoing ();
// indicate the number of bytes in the data field
APDU. setoutgoinglength (byte) 1);
// move the data into the APDU buffer starting at offset 0
buffer [0] = balance;
// send 1 byte of data at offset 0 in the APDU buffer
}// end of getbalance method
getbalance returns the wallet balance in the data field in the response to APDU.
because the data field in the response to APDU is optional, the applet needs to explicitly tell JRE the data to be returned. JRE uses an array in the APDU Object Buffer and the correct status word to construct a complete response to APDU.
Private void validate (APDU ){
// Retrieve the pin data which requires to be validated
// The User Interface data is stored in the data field of
APDU
Byte byteread = (byte) (APDU. setincomingand receive ());
// Validate user interface and set the validation falg in
User Interface
// Object to be true if the validation succeeds.
// If user interface validation fails, pinexception wocould be
// Thrown from pin. Check () method
Pin. Check (buffer, ISO. offset_cdata, byteread );
} // End of validate Method
} // End of class wallet
Pin is a common method used by smart cards to protect data from unauthorized use.
Pin records the number of failed attempts since the last Correct PIN was confirmed. If the number of failed attempts exceeds the maximum number of attempts allowed by the pin, the card will be locked.
After successfully selecting the applet, the pin must take effect before other commands can be executed on the applet.

 

Conclusion

This article first introduces some basic concepts of smart card, and then describes the Java card 2.0 technology and the method for developing Java card applications. Java card applet is compiled by a general Java compiler. The output result (class file) of the compiler is input to the Java card converter, which enhances the compatibility of the Java card 2.0 language subset. You can execute name resolution and the initial address link, and optimized the java byte code to make it more suitable for running on the Java card virtual machine. The output result of the converter is downloaded to Java card. This article does not detail the converter and Applet installation protocols because these protocols have not been standardized. We hope to address this issue in future articles.

Java card adds a new platform for the Java World. The widespread adoption and deployment of Java card requires market promotion and development and time of more applications and tools. At the same time, in the next few years, the number of Java cards will increase to millions. That is to say, you will soon use small cards in your wallet to store your personal information and download applications.

References
      • the first article on the smart card Java developer series is "smart card entry"
        http://www.javaworld.com/jw-12-1997/jw-12-javadev.html
      • for Java card-related business opportunities, see "give currency to Java card API"
        http://www.javaworld.com/javaworld/jw-02-1998/jw-02-javacard.html
      • for methods for developing applications on Java card 1.0 API, see "Java card quick start"
        http: // www.javaworld.com/javaworld/2-02-1998/2-02-javadev.html
      • JAVA card site sans oft
        http://www.sun.com/products/javacard/
      • JAVA commercial site
        http://java.sun.com/products/commerce/
      • Joshua susser, Technical Director of Java card, oft, reviewed this article and provided technical guidance. I would like to express my sincere thanks to him.

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.