Home
Application Programming Notes, Java Card 3 Platform
Contents
1. Chapter 3 describes how to develop applications that use the optional RMI APIs on the Java Card platform Chapter 4 describes how to handle extended APDU functionality on the Java Card platform viii Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Glossary defines terms used in the Java Card 3 Platform Classic Edition Typographic Conventions Typeface Meaning Examples AaBbCc123 The names of commands files Edit your login file and directories on screen Use ls a to list all files computer output You have mail AaBbCc123 What you type when contrasted su with on screen computer output password AaBbCc123 Book titles new words or terms Read Chapter 6 in the User s Guide words to be emphasized These are called class options Replace command line variables You must be superuser to do this with real names or values To delete a file type rm filename Note Characters display differently depending on browser settings If characters do not display correctly change the character encoding in your browser to Unicode UTF 8 Related Documentation References to various documents or products are made in this manual Have the following documents available m Development Kit User s Guide for the Java Card Platform Version 3 0 1 Classic Edition m Application Programming Interface for the Java Card Platform Version 3 0 1 Classic Edition m Virtual Machin
2. if amount lt 0 balance lt amount UserException throwIt REQUEST_FAILED balance amount return balance An operation is only allowed if the value of its parameter is compatible with the current state of the purse object In this particular case the application only checks that the amounts handled are positive and that the balance of the purse always remains positive In Java Card RMI the arguments to and return values from remote methods are restricted The main reason for this limitation is that the Java Card 3 platform Classic Edition does not support object serialization Following are the rules for the Java Card 3 platform Classic Edition 3 6 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 O22 m The arguments to remote methods can be of any supported integral type such as boolean byte short and int or any single dimensional arrays of these integral types Note The int type is optionally supported on the Java Card platform so applications that use this type might not run on all platforms m The return value from a remote method can be any type supported as arguments as well as any remote interface type The method can also return void On the other hand object passing in Java Card RMI follows the normal RMI rules m By default non remote objects are passed by copy which means that all data members of an object are copied except those marke
3. 2 8 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 0 last or only command 1 command chaining y Secure Messaging indicator see 1507816 4 2003 section 6 for further information z Logical channel indicator Type 4 supports logical channels 0 3 Type 16 supports logical channels 0 15 which are mapped to logical channels 4 19 Proprietary Java Card Technology Space CLA Remarks Ox8X Type 4 last or only command in chain Ox9X Type 4 not last command in chain paired with 0x8X OxAX Type 4 last or only command in chain OxBX Type 4 not last command in chain paired with 0xAX OxCX Type 16 no SM last or only command in chain 0xDX Type 16 no SM not last command in chain paired with 0xCX OxEX Type 16 SM last or only command in chain OxFX Type 16 SM not last command in chain paired with OxEX The encoding details are as follows Type 4 b8 b7 b6 b5 b4 b3 b2 b1 1 0 N A x y y Z Z Type 16 b8 b7 b6 b5 b4 b3 b2 b1 1 1 y x z z z z All applets willing to use the logical channel capabilities must comply with the ISO 7816 4 2005 CLA byte encoding specification and choose APDU commands as defined in the proprietary space Chapter 2 Working with Logical Channels 2 9 The X nibble is responsible for logical channels and secure message encoding Only the two least significant bits of the nibble are used for channel encoding which ranges from 0 to 3 When an API DU com
4. if security isCommandSecure SecurityService PROPERTY_INPUT_INTEGRITY security isAuthenticated SecurityService ID_CARDHOLDER UserException throwIt REQUEST_FAILED If one of the two conditions is not satisfied the remote object throws an exception This exception is caught by the dispatcher and forwarded to the client Chapter 3 Developing RMI Applications for the Java Card Platform 3 17 33 1 Implementing a Security Service The following example shows how to implement a security service package com sun javacard samples SecureRMIDemo import javacard framework import javacard framework service public class MySecurityServic tends BasicService implements SecurityService list IDs of known parties private static final byte PRINCIPAL APP PROVIDER ID 0x12 0x34 private static final byte PRINCIPAL CARDHOLDER ID 0x43 0x21 private OwnerPIN provider_pin cardholder_pin null and the security related session flags public MySecurityService initialize the PINs public boolean processDataIn APDU apdu if selectingApplet reset all flags else return preprocessCommandAPDU apdu public boolean isCommandSecure byte properties throws ServiceException return the value of appropriate flag public boolean isAuthenticated short principal throws ServiceException return the value of appropriate flag private byte authentica
5. then we have applet activation Otherwise no applet activation occurs if appInstAlreadySelected false Initialize applet private data upon activation initData privateData DATA_PRIVATE return true In the case of deselection the applet data must be cleared The method MultiSelectable deselect boolean can be implemented so that it clears applet data only if the applet is no longer active For example public void deselect boolean appInstStillSelected If boolean parameter is false then applet is no longer active It is O K to clear applet private data if appInstStillSelected false clearData privateData If this applet is the last one to be deactivated from the package it also must clear package data This situation results in a call to Applet deselect This method can be implemented like this public void deselect This call means that the applet is no longer active and that no other applet in the package is Data for both applet and package must be cleared clearData packageData clearData privateData Handling Channel Information on APDU Commands APDU commands follow the ISO 7816 4 2005 specifications to encode logical channel information The CLA byte encodes logical channel information The CLA byte encoding is divided into two spaces interindustry used by all ISO 7816 4 2005 defined commands and the proprietary space used by Java Card te
6. access to remote databases at the time of a transaction Application Programming Notes Java Card 3 Platform Classic Edition July 2009 terminal thread transaction transient object verification word a Card Acceptance Device that is typically a computer in its own right and can integrate a card reader as one of its components In addition to being a smart card reader a terminal can process data exchanged between itself and the smart card the basic unit of program execution A process can have several threads running concurrently each performing a different job such as waiting for events or performing a time consuming job that the program doesn t need to complete before going on When a thread has finished its job it is suspended or destroyed The Java Card virtual machine can support only a single thread of execution Java Card technology programs cannot use class Thread or any of the thread related keywords in the Java programming language an atomic operation in which the developer defines the extent of the operation by indicating in the program code the beginning and end of the transaction the state of transient objects do not persist from one CAD session to the next and are reset to a default state at specified intervals Updates to the values of transient objects are not atomic and are not affected by transactions a process performed on a CAP file that ensures that the binary representation of the package is
7. and interpreted as 32 767 if the applet implements ExtendedLength or 256 if it does not The Java Card RE analyzes the APDU type coming into the card and determines Chapter 4 Using Extended APDU 4 3 4 3 2 its type based on the rules defined in the ISO 7816 3 specification Because case 2E commands look like case 25 commands in T 0 the Java Card RE is not able to distinguish this particular case Extensions To javacard framework APDU Class Because LC in cases 3E and 4E can take a large value the parameter is sent to the card as a three byte quantity in the format of 00 LCh LCI starting at 1S07816 0FFSET_LC Two new API calls have been added to javacard framework APDU so that the applet developer will not be required to parse the APDU The API calls allow the applet developer to get the value of LC and the data offset inside the APDU buffer without having to get them directly from that buffer as was necessary before These two APIs allow applet developers to write applets without having to worry about parsing extended length in T 0 and T 1 implementations m public short getIncomingLength This API call returns the value of LC as expressed in the APDU whether it is extended or not m public short getOffsetCdata This API call returns the offset where the first byte of the APDU data segment is found 4 4 4 4 Sending and Receiving Extended APDU Commands To write an applet that takes advantage of exten
8. 7816 4 an acronym for Application Programming Interface The API defines calling conventions by which an application program accesses the operating system and other services within the context of this document a Java Card applet which is the basic unit of selection context functionality and security in Java Card technology a person creating an applet using Java Card technology context of a package that contains currently active applet the mechanism that prevents unauthorized accesses to objects in contexts other than currently active context see library package the logical channel on which the applet instance is either the active applet instance or will become the active applet instance Glossary 1 atomic operation atomicity ATR basic logical channel big endian binary compatibility bytecode CAD CAP file CAP file component Glossary 2 card session cast an operation that either completes in its entirety or no part of the operation completes at all state in which a particular operation is atomic Atomicity of data updates guarantee that data are not corrupted in case of power loss or card removal an acronym for Answer to Reset An ATR is a string of bytes sent by the Java Card platform after a reset condition logical channel 0 the only channel that is active at card reset This channel is permanent and can never be closed a technique of storing multibyte data where the high or
9. Card platform supports extended APDUs with some limitations Because the platform defines all of its mandatory API in terms of short data length the values of LC and LE are limited to short positive values That is LC and LE have a range of 0 32 767 Lengths of 32 768 and beyond are not supported by the Java Card platform at this time jJavacardx framework ExtendedLength Interface Not all Java Card applets can handle extended APDUs Legacy applets should never encounter an extended APDU in the APDU buffer Because of this the Java Card API has added a tagging interface javacardx apdu ExtendedLength to signal that the applet implementing this interface is capable of processing receiving and replying to extended APDU commands The Java Card RE will not deliver extended APDU commands to applets not implementing this interface it would throw an ISOException with reason code IS07816 SW_WRONG_LENGTH in that case nor would it allow applets to send reply data lengths greater than 256 if such an interface is not implemented by the applet The APDU buffer in Java Card technology applications will reflect the structure of the extended APDU as defined in ISO In T 1 this representation is straightforward and precise whereas in T 0 there need to be some adaptations for some cases Specifically a case 2E APDU sent over T 0 transport will not show its extended LE value in the APDU buffer Instead a P3 value of 00 will always be transmitted
10. Clear the applet private data when the applet instance is deselected Assume that the following methods are responsible for clearing and setting the data dataType parameter as above final static byte DATA_PRIVATE byte 01 final static byte DATA_PACKAGE byte 02 public void initData byte dataArray byte dataType public void clearData byte dataArray To achieve the behavior specified above you must modify the selection and deselection methods in your sample applet The code for Applet select which is invoked when this applet is the first to become active in the package can be implemented like this public boolean select First applet to be selected in package so initialize package data and applet data initData packageData DATA_PACKAGE initData privateData DATA_PRIVATE return true Likewise the implementation of the method MultiSelectable select boolean must determine whether the applet is already active According to its definition this method is called when another applet within this package is active MultiSelectable select boolean can be implemented such that if appInstAlreadySelected is false then the applet private data can be initialized For example 2 6 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 2 3 1 1 public boolean select boolean appInstAlreadySelected If boolean parameter is false
11. CustomCardAccessor new ApdulOCardAccessor create an RMI connector instance for the Java Card platform JCRMIConnect jCRMI new JCRMIConnect cca byte appAID new byte 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 select the Java Card applet jcRMI selectApplet RMI_DEMO_AID JCRMIConnect REF_WITH_CLASS NAMI GW or jcRMI selectApplet RMI_DEMO_AID JCRMIConnect REF_WITH_INTERFACE NAMES Chapter 3 Developing RMI Applications for the Java Card Platform 3 21 give your PIN if cca authenticateUser PRINCIPAL CARDHOLDER ID throw new RemoteException msg getString msg04 obtain the initial reference to the Purse interface Purse myPurse Purse jcRMI getInitialReference debit the requested amount try short balance myPurse debit debitAmount catch UserException jce short reasonCode jce getReason process UserException reason information display the balance to user catch Exception e e printStackTrace finally try if cca null1 cca closeCard catch Exception e e printStackTrace Note that the CustomCardAccessor instance is now obtained instead of ApdulOCardAccessor cca new CustomCardAccessor new ApdulOCardAccessor An extra step to authenticate with the SecurePurseApplet after selectApplet is added This invokes a new method in CustomCardAccessor to interact with the card using the us
12. machine for the Java Card virtual machine Java Card VM regarding security checks on method invocations Applets that implement MultiSelectable are designed to handle calls to Shareable objects across packages when several applets are active on different logical channels In contrast an applet written for version 2 1 of the Java Card platform or an applet written for the Java Card 3 platform that does not implement MultiSelectable has exclusive control over any changes to its internal objects or data when it is selected Only when the non multiselectable applet is in a deselected state can other applets modify its internal data structures Therefore if an applet is non multiselectable no calls to its Shareable objects can be made when it is selected Working with Non MultiSelectable Applets Applets written for the Java Card 3 platform do not have to implement the MultiSelectable interface In this case the applet assumes that it is uniquely selected and its owned objects will not be modified via Shareable interface objects while it is selected The limitations are imposed when you interact with applets that do not implement MultiSelectable m It is not possible to select more than one applet simultaneously from a package if any of the applets you want to select does not implement the MultiSelectable interface m It is not possible to invoke methods of a Shareable object belonging to a non multiselectable applet when an applet belonging t
13. object 5 7 Index 2 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 PIX 5 7 W Proximity Coupling Device 5 7 word 5 9 R RAM 5 7 random access memory 5 7 read only memory 5 8 reference implementation 5 7 remote interface 5 8 Remote Method Invocation 5 5 remote methods 5 8 remote object 5 8 removable applets 1 4 removable packages 1 3 Reserved for Future Use 5 8 REU 5 8 RI 5 7 RID 5 8 RMI 3 1 5 5 5 8 ROM 5 8 runtime environment 5 8 S security service for Java Card RMI 3 18 security for Java Card RMI 3 14 SELECT FILE 2 16 selection 2 3 shareable interface 5 8 shareable interface object 5 8 SIO 5 8 smart card 5 8 stubs 3 2 generating 3 13 T terminal 5 9 thread 5 9 transaction 5 9 transient object 5 9 V verification 5 9 Index 3 Index 4 Application Programming Notes Java Card 3 Platform Classic Edition July 2009
14. resulting stubs class_name is the name of the remote class The v1 2 flag is required by the RMI client framework for the Java Card platform The rmic must be called for each remote class in your applet Note You need to generate stubs only for remote classes that list a remote interface in their implements clause The file tools jar is provided in version 3 0 1 of the Java Card development kit This Java Archive JAR file contains compiled implementations of packages javacard framework javacard security javacardx biometry javacardx external and javacardx tlv Classes in these packages might be referenced by Java Card RMI applets and thus might be needed by the rmic to generate stubs Running a Java Card RMI Applet The server part the Java Card RMI enabled applet can be run on the C language Java Card RE for which the standard procedures apply the applet must be installed first using the installer applet After the applet is installed the EEPROM state can be saved and used to run the Java Card RE against the Java Card RMI client Application Programming Notes Java Card 3 Platform Classic Edition July 2009 3 1 3 Running the Java Card RMI Client Program The client program can be developed and compiled using javac or your favorite IDE To compile the client the remote interfaces for your applet must be present in your classpath Running the client program has the following requirements m The clien
15. the same package remains active on another channel so CLEAR_ON_DESELECT transients are not cleared Only when the last applet instance from the entire package is deselected does a call to Applet deselect result resulting in the erasure of CLEAR_ON_DESELECT transients 2 3 2 4 Writing Applets For Concurrent Logical Channels This section describes how to write a multiselectable applet that will perform various tasks based on whether it is selected The code samples in this section show how to extend the applet to implement the MultiSelectable interface and how to implement the MultiSelectable select boolean and deselect boolean methods The code samples also show how to use the Applet select and deselect methods to work with multiselectable applets To take advantage of multiple channel operation an applet must implement the javacard framework MultiSelectable interface For example Application Programming Notes Java Card 3 Platform Classic Edition July 2009 public class SampleApplet extends Applet implements MultiSelectable The new applet needs to provide implementation for the MultiSelectable select boolean and MultiSelectable deselect boolean methods These methods are responsible for encoding the behavior that the applet needs during a selection event if either of the following situations occurs m The applet is already selected on a different channel m One or more applets from
16. this procedure 1 If the specified channel is closed open the channel 2 Deselect currently selected applet in channel if needed 3 Select specified applet in the channel This SELECT FILE command selects an applet on channel R CLA INS P1 P2 Le Data Le sw1 sw2 xOR xA4 x04 x00 AID len AID x90 0 This command produces the following results m Channel encoded in R can be any channel opened or unopened including the basic channel m The applet identified in the Data section becomes the selected applet on channel R m If channel encoded in R is not open this command opens channel R m If channel encoded in R is open this command changes the selected applet in the channel to the one specified Application Programming Notes Java Card 3 Platform Classic Edition July 2009 This command returns an error in the following circumstances m The applet cannot be found or is not available The current applet is left selected and an error is returned m An active applet belonging to the same package does not implement the javacard framework MultiSelectable interface or if the applet to be selected does not implement this interface m Channel encoded in R is not available Chapter 2 Working with Logical Channels 2 17 2 18 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 CHAPTER O Developing RMI Applications for the Java Card Platform This chapter describes ho
17. 9 m Use the object deletion mechanism when a large object such as a certificate or key must be replaced with a new one In this case instead of updating the old object in a transaction create a new object and update its pointer within the transaction Then use the object deletion mechanism to remove the old object m Use the object deletion mechanism when object resizing is required as shown in the example in Requesting the Object Deletion Mechanism on page 2 122 12 1 Package and Applet Deletion The Java Card 3 platform provides the ability to delete package and applet instances from the card s memory Requests for deletion are sent in the form of an APDU from the terminal to the smart card Requests to delete an applet or package cannot be sent from an applet on the card In the Java Card 3 platform the installer deletes packages and applets Once the installer is selected it can receive requests from the terminal to delete packages and applets The following sections describe programming guidelines that will help your packages and applets to be more easily removed Developing Removable Packages Package deletion refers to removing all of a package s code from the card s memory To be eligible for deletion nothing on the card can have dependencies on the package to be deleted including the following m Packages that are dependent on the package to be deleted m Applet instances or objects that either belong
18. RE dispatcher which performs the functions specified by the commands including the following m Managing logical channels m Deselecting applets m Selecting applets 2 3 4 1 MANAGE CHANNEL OPEN In response to the MANAGE CHANNEL OPEN command the dispatcher follows this procedure 1 If the origin channel is not open an error is returned 2 Determines whether the channel is open or closed If the channel is open an error is returned 3 Opens the channel 4 If the origin channel is 0 the default applet if there is one is selected in the new channel 5 If the origin channel is not 0 the selected applet on the origin channel becomes the selected applet in new channel 2 14 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 2 3 4 2 This MANAGE CHANNEL OPEN command opens a new channel from channel encoded in Q CLA INS P1 P2 Le Data Le Data sw1 sw2 xQ x70 0 0 iL xOR x90 0 CLA INS P1 P2 Le Data Le sw1 sw2 bxa 0x70 00 OxR 0 0 0x90 00 This command produces the following results m If channel encoded in Q is the basic channel channel 0 the card s default applet is selected on channel encoded in R No applet is selected if no default applet is defined m If channel encoded in Q is other than the basic channel channels 1 2 19 the selected applet on channel encoded in Q becomes the current applet selected on channel R
19. al URI and segments from the path a software tool that allows Java applications programmed for the Java Card Platform Version 2 2 2 to be deployed on both the Java Card 3 Platform Connected Edition and on the Java Card 3 Platform Classic Edition It also allows Java applications packaged for Version 2 2 2 to be transformed through the normalization process and then repackaged for deployment on both the Connected and Classic Editions a programming methodology based on the concept of an object which is a data structure encapsulated with a set of routines called methods which operate on the data the applet instance within the currently active context when the object is instantiated An object can be owned by an applet instance or by the Java Card RE in object oriented programming unique instances of a data structure defined according to the template provided by its class Each object has its own values for the variables belonging to its class and can respond to the messages methods defined by its class the logical channel on which an APDU command is issued the context in which an object is instantiated or created a namespace within the Java programming language that can have classes and interfaces an acronym for Proximity Coupling Device The PCD is a contactless card reader device persistent objects and their values persist from one CAD session to the next indefinitely Objects are persistent by default Persi
20. al an applet activation event If the applet is subsequently selected on another channel Chapter 2 Working with Logical Channels 2 3 2 252 MultiSelectable select boolean is called again but this time the appInstAlreadySelected parameter is passed as true to indicate that the applet is already active Deselection for MultiSelectable Applets The MultiSelectable interface defines one method to be invoked instead of Applet select when the applet being deselected or any other applet in its package is already selected on another logical channel public void MultiSelectable deselect boolean appInstStillSelected The MultiSelectable deselect boolean method informs the applet instance if it is being deselected on the logical channel while the same applet instance or another applet in the same package is still active on another channel on any interface The parameter appInstStillSelected is true if the applet remains active on a different channel It is false if it is not active on another channel A value of false indicates that this is the last remaining active instance of the applet This method can be called as the result of a MANAGE CHANNEL CLOSE or SELECT FILE APDU command If the applet still remains active on a different channel the appInstStillSelected parameter is passed as true Note that if the MultiSelectable deselect boolean method is called it means that either an instance of this applet or another applet from
21. as the Java Card client side framework rely on the APDU I O library for managing and communicating with the card reader and the card on which the Java Card applet PurseApplet resides This makes the client application very portable on Java SE platforms See the Development Kit User s Guide Java Card Platform Version 3 0 1 Classic Edition for information on the APDU I O library The following example shows a very simple PurseClient application that is the client application of the Java Card technology based program PurseApplet import examples purse import javacard framework UserException public class PurseClient extends java lang Object public static void main java lang String argv arg 0 contains the debit amount short debitAmount short Integer parseInt argv 0 CardAccessor ca null try open and powerup the card ca new ApdulOCardAccessor create an RMI connector instance for the Java Card platform JCRMIConnect jcRMI new JCRMIConnect ca byte appAID new byte 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 select the Java Card applet jcRMI selectApplet RMI_DEMO_AID JCRMIConnect REF_WITH_CLASS NAM jcRMI selectApplet RMI_DEMO_AID JCRMIConnect REF_WITH_INTERFACE NAMES obtain the initial reference to the Purse interface Purse myPurse Purse jcRMI getInitialReference debit the requested amount try short balance myPurse debit deb
22. ation Code MAC is an encryption of data for security purposes refers to embedding the Java Card virtual machine runtime environment and applets in the read only memory of a smart card during manufacture a procedure or routine associated with one or more classes in object oriented languages implements the javacard framework MultiSelectable interface Multiselectable applets can be selected on multiple logical channels at the same time They can also accept other applets belonging to the same package being selected simultaneously an applet instance that is selected and therefore active on more than one logical channel simultaneously a set of names in which all names are unique a method that is not implemented in the Java programming language but in another language The CAP file format does not support native methods four bits the process of transforming and repackaging a Java application packaged for the Java Card Platform Version 2 2 2 for deployment on both the Java Card 3 Platform Connected Edition and the Java Card 3 Platform Classic Edition Application Programming Notes Java Card 3 Platform Classic Edition July 2009 normalization URI Normalizer object oriented object owner objects origin logical channel owning context package PCD persistent object PIX RAM random access memory reference implementation the process of removing unnecessary component of a hierarchic
23. ation on logical channels their implementation and logical channel terminology see the Runtime Environment Specification for the Java Card Platform Version 3 0 1 Classic Edition 2 1 ZA 2 1 1 Z2 2 2 Applets and Logical Channels In the Java Card 3 platform Classic Edition you can work with applets that are aware of multiple channels and applets that are not aware of multiple channels The logical channel implementation in the Java Card 3 platform preserves backward compatibility with applets written for the Java Card platform version 2 1 It also allows you the option of writing your applets to use the logical channel feature or of writing the applets to work independently on any channel without using the logical channels at all Non MultiSelectable Applets In the Java Card 3 platform you have the option of writing applets that can operate in a multiple channel environment or you can write applets that do not take advantage of this feature Applets written for the Java Card platform that do not take advantage of the multiple channel environment are similar to applets written for the version 2 1 Java Card specification An applet written for the Java Card platform that is not designed to be aware of multiple channels cannot be selected more than once nor can any other applet inside the package be selected concurrently on a different channel You can have several non multiselectable applets operating simultaneously on di
24. be done in an applet s install method m The remote objects must communicate with the outside world which can be done in an applet s process method Chapter 3 Developing RMI Applications for the Java Card Platform 3 7 3 8 For conversion an applet should be assigned with an AID known on the client side 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 since this AID is used in the client program Following is the basic code for such an applet package examples purse import javacard framework import javacard framework service import java rmi public class PurseApplet extends Applet private Dispatcher dispatcher private PurseApplet Allocates an RMI service and sets for the Java Card platform the initial reference RemoteService rmi new RMIService new PurseImpl Allocates a dispatcher for the remote service dispatcher new Dispatcher short 1 dispatcher addService rmi Dispatcher PROCESS COMMAND public static void install byte buffer short offset byte length Allocates and registers the applet new PurseApplet register public void process APDU apdu dispatcher process apdu Preparing and Registering the Remote Object The PurseApplet constructor contains the initialization code for the remote object First a javacard framework service RMIService object must be allocated This service is an object that knows how to handle all the inc
25. c Edition July 2009 Third Party Web Sites Sun is not responsible for the availability of third party web sites mentioned in this document Sun does not endorse and is not responsible or liable for any content advertising products or other materials that are available on or through such sites or resources Sun will not be responsible or liable for any actual or alleged damage or loss caused by or in connection with the use of or reliance on any such content goods or services that are available on or through such sites or resources Sun Welcomes Your Comments Sun Microsystems is interested in improving its documentation and welcomes your comments and suggestions You can submit your comments to http java sun com docs forms sendusmail html Please include the title of your document with your feedback Application Programming Notes Java Card 3 Platform Classic Edition Preface xi xii Application Programming Notes Java Card 3 Platform Classic Edition July 2009 CHAPTER 1 Using Object Package and Applet Deletion This chapter describes how to use the object deletion mechanism and the package and applet deletion features of the Java Card 3 Platform Classic Edition 1 1 Object Deletion Mechanism The object deletion mechanism on the Java Card 3 platform Connected Edition reclaims memory that is being used by unreachable objects For an object to be unreachable neither a static nor an object fie
26. chnology to encode application specific commands Chapter 2 Working with Logical Channels 2 7 The CLA byte encoding is divided into two classes Type 4 commands which encode legacy ISO 7816 4 logical channel information and Type 16 commands which are defined by the ISO 7816 4 2005 specification to encode information for additional 16 logical channels in the card Type 4 logical channels occupy the range of 0 3 while Type 16 logical channels go in the range of 4 19 that is the value encoded in the CLA byte plus four as it is used in SELECT MANAGE CHANNEL and other proprietary or ISO commands However a note of caution while MANAGE CHANNEL command CLA byte follows the encoding as described below its P2 parameter does not The logical channel numbers in its P2 parameter are correctly encoded in the range of 0 19 The CLA byte encoding follows the following rules Interindustry Space CLA Remarks Ox0X Type 4 last or only command in chain 0x1X Type 4 not last command in chain paired with 0x0X Ox2X RFU Ox3X RFU 0x4X Type 16 no SM last or only command in chain Ox5X Type 16 no SM not last command in chain paired with 0x4X 0x6X Type 16 SM last or only command in chain Ox7X Type 16 SM not last command in chain paired with 0x07X The encoding details are as follows Type 4 b8 b7 b6 b5 b4 b3 b2 bl O 0 110 ER ye y ZZ Type 16 b8 b7 b6 b5 b4 b3 b2 bl yh Re 2 Notation x Command Chaining bit
27. curePurseApplet extends Applet Dispatcher dispatcher private SecurePurseApplet SecurityService sec First get a security service sec new MySecurityService Allocates an RMI service for the Java Card platform and sets the initial reference RemoteService rmi new RMIService new SecurePurselmpl sec Allocates and initializes a dispatcher for the remote object dispatcher new Dispatcher short 2 dispatcher addService rmi Dispatcher PROCESS COMMAND dispatcher addService sec Dispatcher PROCESS_INPUT_DATA public static void install byte buffer short offset byte length Allocates and registers the applet new SecurePurseApplet register public void process APDU apdu dispatcher process apdu The security service that is used by the remote object must be initialized at some point Here this is done in the constructor for the SecurePurseApplet sec new MySecurityService The initialization then goes on with the initialization of the Java Card RMI service The only new thing here is that the remote object being allocated and set as the initial reference is now a SecurePurselmpl RemoteService rmi new RMIService new SecurePurselImpl sec Next the dispatcher must be initialized Here it must dispatch simple Java Card RMI requests and security related requests such as EXTERNAL AUTHENTICATE In fact the security service handles these requests direc
28. curity services principal identification and authentication secure communication channel are provided by an object that implements the SecurityService interface Because a generic remote object must not be dependent on a particular kind of security service it must take a reference to this object as a parameter to its constructor This is exactly what happens here where the reference to the object is stored in a dedicated private field private SecurityService security The SecurityService interface is part of the extended application development framework and offers an API that can then be used to check on the current security status Use the Service to Check the Current Security Status In the example this following required security behaviors for the applet are assumed m The debit method is authorized only if it is sent through a secure channel that ensures at least the integrity of input data and if the cardholder is successfully authenticated m The credit method is authorized only if it is sent through a secure channel that ensures at least the integrity of input data and if the application issuer is successfully authenticated m The getBalance method is authorized only if the cardholder or the application issuer is successfully authenticated The SecurityService provides methods and constants that allow the implementation to perform such checks For instance following is the code for the checks on the debit method
29. d static or transient In the case of the Java Card platform this rule is trivial to apply because the only objects concerned are arrays of integral types m Remote objects are passed by reference In the case of the Java Card platform remote objects can only be passed as return values A reference to a remote object is actually a reference to a stub which is a client side proxy for the remote objects Stubs are needed only when the format remote_ref_with_class is used for passing remote references When another format such as remote_ref_with_interfaces is used stubs are not necessary Stubs are described in Generate the Stubs on page 13 Note Even though the semantics of the Java Card platform transient arrays are somewhat similar to transient fields in the Java programming language different rules apply Java Card platform contents are copied in Java Card RMI and passed by value when they are returned from a remote method A class can define methods not specified in a remote interface but they can only be invoked on card within the Java Card VM and cannot be invoked remotely Building an Applet In the Java Card 3 platform all applications must include a class that inherits from javacard framework Applet which will provide an interface with the outside world This also applies to applications that are based on remote objects for two main reasons m The remote objects must be instantiated and initialized which can
30. ded length follow these steps 1 Implement the javacardx apdu ExtendedLength interface in your applet Application Programming Notes Java Card 3 Platform Classic Edition July 2009 import javacard framework import javacardx apdu ExtendedLength public MyApplet extends Applet implements ExtendedLength method as you would with any 2 Write your applet and Applet process code other applets For consistency it is advisable that your process begin like the one below public void process APDU apdu byte buffer apdu getBuffer if apdu isISOInterindustryCLA if this selectingApplet return else ISOException throwIt ISO7816 SW_CLA_NOT_SUPPORTED switch buffer ISO7816 OFFSET_INS case CHOICE_1 return case CHOICE_2 default ISOException throwIt ISO7816 SW_INS_NOT_SUPPORTED 3 For cases 3S 4S 3E and 4E write the method to handle incoming data Do it relying on API extensions so that your applet properly handles extended as well as non extended cases Chapter 4 Using Extended APDU 4 5 void receiveData APDU apdu byte buffer apdu getBuffer short LC apdu getIncomingLength short recvLen apdu setIncomingAndreceive short dataOffset apdu getOffsetCdata while recvLen gt 0 process data in buffer dataOffset recvLen apdu receiveBytes dataOffset Done 4 For case 2S 2E write the
31. der bytes come first For example given an 8 bit data item stored in big endian order the first bit read is considered the high bit in a Java Card system a change in a Java programming language package results in a new CAP file A new CAP file is binary compatible with equivalently does not break compatibility with a preexisting CAP file if another CAP file converted using the export file of the preexisting CAP file can link with the new CAP file without errors machine independent code generated by the compiler and executed by the Java virtual machine an acronym for Card Acceptance Device The CAD is the device in which the card is inserted the CAP file is produced by the Converter and is the standard file format for the binary compatibility of the Java Card platform A CAP file contains an executable binary representation of the classes of a Java programming language package The CAP file also contains the CAP file components see also CAP file component The CAP files produced by the converter are contained in Java Archive JAR files a Java Card platform CAP file consists of a set of components which represent a Java programming language package Each component describes a set of elements in the Java programming language package or an aspect of the CAP file A complete CAP file must contain all of the required components Header Directory Import Constant Pool Method Static Field and Reference Location The following com
32. e Specification for the Java Card Platform Version 3 0 1 Classic Edition m Runtime Environment Specification for the Java Card Platform Version 3 0 1 Classic Edition m Java Card Technology for Smart Cards by Zhiqun Chen Addison Wesley 2000 m Off Card Verifier for the Java Card Platform Version 2 2 1 White Paper Sun Microsystems Inc 2003 Sun Microsystems Inc Preface ix m The Java Programming Language Java Series Second Edition by Ken Arnold and James Gosling Addison Wesley 1998 m The Java Virtual Machine Specification Java Series Second Edition by Tim Lindholm and Frank Yellin Addison Wesley 1999 m The Java Class Libraries An Annotated Reference Second Edition Java Series by Patrick Chan Rosanna Lee and Doug Kramer Addison Wesley 1999 m ISO 7816 Specification Parts 1 6 You can download the Java Card specifications bundle separately from the Sun Microsystems web site at http java sun com products javacard Accessing Sun Documentation Online The Java Developer Connection program web site enables you to access Java platform technical documentation on the web at http developer java sun com developer infodocs Documentation Support and Training Sun Function URL Documentation Support Training http www sun com documentation http www sun com support http www sun com training x Application Programming Notes Java Card 3 Platform Classi
33. e objects are Java Card RE owned AID instances Glossary 5 JDK software library package local variable logical channel MAC mask production masking method multiselectable applets multiselected applet namespace native method nibble normalization classic applet Glossary 6 an acronym for Java Development Kit The JDK software is a Sun Microsystems Inc product that provides the environment required for software development in the Java programming language The JDK software is available for a variety of operating systems for example Sun Microsystems Solaris OS and Microsoft Windows a Java programming language package that does not contain any non abstract classes that extend the class javacard framework Applet An applet package contains one or more non abstract classes that extend the javacard framework Applet class a data item known within a block but inaccessible to code outside the block For example any variable defined within a method is a local variable and cannot be used outside the method as seen at the card edge works as a logical link to an application on the card A logical channel establishes a communications session between a card applet and the terminal Commands issued on a specific logical channel are forwarded to the active applet on that logical channel For more information see the ISO IEC 7816 Specification Part 4 http www iso org an acronym for Message Authentic
34. e than once on different channels or selected concurrently with applets in the same package an error is returned to the terminal Note If an applet in any package implements the MultiSelectable interface then all applets in the package must also implement the MultiSelectable interface It is not possible to have multiselectable and non multiselectable applets in the same package The MultiSelectable interface contains a select and a deselect method to manage multiselectable applets Selection for MultiSelectable Applets The MultiSelectable interface defines one method to be invoked instead of Applet select when the applet being selected or any other applet in its package is already selected on another logical channel public boolean MultiSelectable select boolean appInstAlreadySelected The MultiSelectable select boolean method informs the applet instance if it is selected more than once on different channels or if another applet in the same package is selected on another channel on any interface The parameter appInstAlreadySelected is true if the applet is selected on a different channel It is false if it is not selected The method can return either true or false to accept or reject applet selection This method can be called as a result of issuing a SELECT FILE or MANAGE CHANNEL OPEN APDU command to select an applet If the applet is not selected then the appInstAlreadySelected parameter is passed as false to sign
35. ection 2 4 E EEPROM 5 3 Electrically Erasable Programmable Read Only Memory 5 3 entry point objects 5 3 entry point objects Java Card RE 5 5 Export file 5 4 extended APDU 4 1 externally visible 5 4 F finalization 5 4 firewall 2 13 5 4 flash memory 5 4 framework 5 4 G garbage collection 5 4 H heap 5 4 l installation program 5 4 installer 5 4 instance variables 5 5 instantiation 5 5 instruction 5 5 interface multiselectable 2 3 internally visible 5 5 J JAR file 5 5 Java Archive file 5 5 Java Card RE entry point objects 5 5 Java Card RE entry point objects 5 5 Java Card RMI 3 1 CardAccessor objects 3 12 client program 3 3 running applets 3 2 security service 3 18 shutting down 3 11 Java Development Kit 5 6 JDK 5 6 L library package 5 6 local variable 5 6 logical channel 5 6 logical channels 2 1 management 2 13 M MAC 5 6 MANAGE CHANNEL CLOSE 2 15 MANAGE CHANNEL OPEN 2 14 mask production 5 6 masking 5 6 Message Authentication Code 5 6 method 5 6 multiselectable applets 5 6 multiselectable interface 2 3 multiselected applet 5 6 N namespace 5 6 native method 5 6 nibble 5 6 non multiselectable applets 2 2 Normalizer 5 7 O object deletion 1 1 object owner 5 7 object oriented 5 7 objects 5 7 origin logical channel 5 7 owning context 5 7 P package 5 7 package deletion 1 3 PCD 5 7 persistent
36. er s credentials if cca authenticateUser PRINCIPAL CARDHOLDER_ID handle error The rest of SecurePurseClient is the same as PurseClient 3 22 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Writing a CustomCardAccessor Class The SecurePurseClient application uses a subclass of CardAccessor called CustomCardAccessor to perform user authentication functions and to sign every message sent thereafter for integrity purposes package examples securepurseclient public class CustomCardAccessor extends ApdulOCardAccessor Creates new CustomCardAccessor public CustomCardAccessor public byte exchangeAPDU byte sendData throws java io IOException byte macSignature null byte dataWithMAC new byte sendData length 4 sign the sendData data using session key sign the data in commandBuffer using the user s session key add generated MAC signature to data in buffer before sending return super exchangeAPDU dataWithMAC boolean authenticateUser short userKey byte externalAuthCommand null build and send the appropriate commands to the applet to authenticate the user using the user Key and additional info provided try byte response super exchangeAPDU externalAuthCommand catch Exception e analyze return false Then compute the session key for later use return true successful aut
37. erface Purse extends Remote public static final short MAX_AMOUNT 400 public static final short REQUEST_FAILED 0x0102 public short debit short amount throws RemoteException UserException public short credit short amount throws RemoteException UserException public short getBalance throws RemoteException UserException This is a typical Java Card RMI interface in the following ways m The interface type extends the java rmi Remote interface This interface is a tagging interface that identifies the interface as defining a remotely accessible object m Every method in the interface must be declared as throwing a RemoteException or one of its superclasses IOException or Exception This exception is required to encapsulate all the communication problems that might occur during a remote invocation of the method In addition the credit debit and getBalance methods also throw the UserException to indicate application specific errors m The interface can also define values for constants that might be used in the communication between the client and the server The Purse interface defines a constant MAX_AMOUNT that represents the maximum allowed value for the transaction amount parameter It also defines a reason code REQUEST_FAILED for the UserException qualifier Implement a Remote Interface The next step provides an implementation for this interface This implementation runs on a Java Card platform and it therefo
38. es a new buffer and removes the old one by requesting the object deletion mechanism The following method updates the buffer size by removing the old buffer object from the memory by requesting object deletion and creates a new one with the required size Kj void updateBuffer byte requiredSize try if buffer null amp amp buffer length requiredSize we already have a buffer of required size return JCSystem beginTransaction byte oldBuffer buffer buffer new byte requiredSize if oldBuffer null JCSystem requestObjectDeletion JCSystem commitTransaction catch Exception e JCSystem abortTransaction Object Deletion Mechanism Usage Guidelines Do not confuse the object deletion mechanism on the Java Card platform with garbage collection in the standard Java programming language The following guidelines describe the possible scenarios when the object deletion mechanism might or might not be used m When throwing exceptions avoid creating new exception objects and relying on the object deletion mechanism to perform cleanup Try to use existing exception objects m Similarly try not to create objects in method or block scope This is acceptable in standard Java technology applications but is an incorrect use of the object deletion mechanism in Java Card technology based applications Application Programming Notes Java Card 3 Platform Classic Edition July 200
39. export file the process by which a Java virtual machine VM allows an unreferenced object instance to release non memory resources for example close and open files prior to reclaiming the object s memory Finalization is only performed on an object when that object is ready to be garbage collected meaning there are no references to the object Finalization is not supported by the Java Card virtual machine The method finalize is not called automatically by the Java Card virtual machine see applet firewall a type of persistent mutable memory It is more efficient in space and power than EPROM Flash memory can be read bit by bit but can be updated only as a block Thus flash memory is typically used for storing additional programs or large chunks of data that are updated as a whole the set of classes that implement the API This includes core and extension packages Responsibilities include applet selection sending APDU bytes and managing atomicity the process by which dynamically allocated storage is automatically reclaimed during the execution of a program a common pool of free memory usable by a program A part of the computer s memory used for dynamic memory allocation in which blocks of memory are used in an arbitrary order The Java Card virtual machine s heap is not required to be garbage collected Objects allocated from the heap are not necessarily reclaimed the on card mechanism to download and install CAP fi
40. fferent channels as long as they do not interfere with each other s data while they are active For example you can open up to 4 channels and run a distinct applet on each as long as they do not inter operate You can control their operation by multiplexing commands into the APDU communications channel If the applets are independent of each other then the results will be the same as if each of these applets were running one at a time each in a separate session Interoperability If you design your applets to take advantage of multi session functionality they can inter operate from different channels and can be selected multiple times in different channels For example the card might handle security information on one channel while data is accessed on a second channel while the third channel takes care of data encoding operations Application Programming Notes Java Card 3 Platform Classic Edition July 2009 22 224 Understanding the MultiSelectable Interface For an applet to be selectable on multiple channels at the same time or to have another applet belonging to the same package selected simultaneously it must implement the javacard framework MultiSelectable interface Implementing this interface allows the applet to be informed when it has been selected more than once or when applets in the same package are already selected during applet activation If an applet that does not implement MultiSelectable is selected mor
41. he Applet select MultiSelectable select boolean Applet deselect or MultiSelectable deselect boolean method it returns the APDU command logical channel as specified in the CLA byte m JCSystem class public static byte getAssignedChannel This method returns the channel of the currently selected applet In case of a MANAGE CHANNEL command if this method is invoked inside the Applet select MultiSelectable select boolean Applet deselect or MultiSelectable deselect boolean method it returns the channel where the applet to be selected or deselected is assigned to run ISO 7816 4 2005 Compliant Applet Example In case of a MANAGE CHANNEL command from a non zero channel to another non zero channel the ISO 7816 4 specification requires that the security state from the applet selected in the origin channel be copied into the new channel In the example presented in this section assume that the state information is stored in the array appState inside the applet StateObj appState MAX CHANNELS Holds the security state for each logical channel You can use the APDU getCLAChannel and JCSystem getAssignedChannel methods to identify if the applet selection case corresponds to an ISO 7816 4 case where the security state needs to be copied Note that if such an event occurs it will also be a multiselection situation where the applet is also selected on the newly opened channel Chapte
42. he Java platform constant pool there is one constant type for method references while in the Java Card constant pool there are three constant types for method references The additional information provided by a constant type in Java Card technologies simplifies resolution of references protected object space associated with each applet package and Java Card RE All objects owned by an applet belong to context of the applet s package a change from one currently active context to another For example a context switch is caused by an attempt to access an object that belongs to an applet instance that resides in a different package The result of a context switch is a new currently active context a piece of software that preprocesses all of the Java programming language class files that make up a package and converts the package to a CAP file The Converter also produces an export file when an object instance method is invoked an owning context of this object becomes the currently active context the Java Card RE keeps track of the currently selected Java Card applet Upon receiving a SELECT FILE command with this applet s AID the Java Card RE makes this applet the currently selected applet The Java Card RE sends all APDU commands to the currently selected applet a new component added to the CAP file The new component must conform to the general component format It is silently ignored by a Java Card virtual machine that does not
43. he ability to export or unexport an object Chapter 3 Developing RMI Applications for the Java Card Platform 3 5 Define the Constructor for the Remote Object The constructor for a remote class provides the same functionality as the constructor of a non remote class it initializes the variables of each newly created instance of the class In addition the remote object instance will need to be exported Exporting a remote object makes it available to accept incoming remote method requests By extending CardRemoteObject a class guarantees that its instances are exported automatically upon creation on the card If a remote object does not extend CardRemoteObject directly or indirectly you must explicitly export the remote object by calling the CardRemoteObject export method in the constructor of your class or in any appropriate initialization method Of course this class must still implement a remote interface To review The implementation class for a remote object needs to do the following Implement a remote interface m Export the object so that it can accept incoming remote method calls Provide an Implementation for Each Remote Method The implementation class for a remote object contains the code that implements each of the remote methods specified in the remote interface For example here is the implementation of the method that debits the purse public short debit short amount throws RemoteException UserException
44. hentication Chapter 3 Developing RMI Applications for the Java Card Platform 3 23 The CustomCardAccessor class introduces the authenticateUser method to send APDU commands to the SecurePurseApplet on the card to authenticate the user described by the userKey parameter and other parameters and to compute a transport key It invokes super sendCommandAPDU method to send the command without modification This CustomCardAccessor class also reimplements the exchangeAPDU method declared in a superclass CardAccessor to sign each message before it is sent out by super exchangeAPDU 3 24 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 CHAPTER 4 Using Extended APDU The extended APDU feature in the Java Card 3 Platform Classic Edition allows applet developers to take advantage of extended APDU functionality as defined in the ISO 7816 specification Extended APDU allows large amounts of data to be sent to the card processed appropriately and sent back to the terminal in a more efficient way Instead of having to re issue multiple APDU messages to complete an operation requiring large volumes of data and requiring the developer to code the application to keep a state across such multiple APDU commands extended APDU allows applets to perform this function more efficiently with one large APDU exchange Extended APDU can be beneficial when dealing with large amounts of information For example applicati
45. hods These constraints are as a result of the Java Card platform language subset and other feature limitations the methods of a remote interface an object whose remote methods can be invoked remotely from the CAD client A remote object is described by one or more remote interfaces acronym for Reserved for Future Use see AID application identifier an acronym for Remote Method Invocation RMI is a mechanism for invoking instance methods on objects located on remote virtual machines meaning a virtual machine other than that of the invoker memory used for storing the fixed program of the card A smart card s ROM contains operating system routines as well as permanent data and user applications No power is needed to hold data in this kind of memory ROM cannot be written to after the card is manufactured Writing a binary image to the ROM is called masking and occurs during the chip manufacturing process see Java Card Runtime Environment Java Card RE an interface that defines a set of shared methods These interface methods can be invoked from an applet in one context when the object implementing them is owned by an applet in another context an object that implements the shareable interface a card that stores and processes information through the electronic circuits embedded in silicon in the substrate of its body Unlike magnetic stripe cards smart cards carry both processing power and information They do not require
46. itAmount catch UserException jce short reasonCode jce getReason 3 10 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 process UserException reason information display the balance to user catch Exception e e printStackTrace finally try if ca null ca closeCard catch Exception e e printStackTrace Initializing and Shutting Down the Card Connection The client application must open the connection to the card and close it at the end Note ApdulOCardAccessor takes its settings from the file jcclient properties For example when the RMIPurse sample demo client application runs the JC_CLASSIC_HOME samples classic_applets RMIPurse client directory containing the properties file is included in the CLASSPATH The directory in which you installed the developer s kit is indicated as JC_CLASSIC_HOME The following code shows opening and closing the connection using the RMI client framework CardAccessor ca null The following line initializes card connection according to parameters listed in the jcclient properties file ca new ApdulOCardAccessor The following line powers down the card and closes the connection ca closeCard Chapter 3 Developing RMI Applications for the Java Card Platform 3 11 3 12 Creating and Using a CardAccessor Object To access the Java Card applet using remote
47. ld can point to an object An applet object is reachable until successfully deleted The object deletion mechanism on the Java Card 3 platform is not like garbage collection in standard Java technology applications due to space and time constraints The amount of available RAM on the card is limited In addition because object deletion mechanism is applied to objects stored in persistent memory it must be used sparingly EEPROM writes are very time consuming operations and only a limited number of writes can be performed on a card Due to these limitations the object deletion mechanism in Java Card technology is not automatic It is performed only when an applet requests it Use the object deletion mechanism sparingly and only when other Java Card technology based facilities are cumbersome or inadequate The object deletion mechanism on the Java Card platform is not meant to change the programming style in which programs for the Java Card platform are written 1 1 1 1 1 2 1 2 Requesting the Object Deletion Mechanism Only the runtime environment for the Java Card platform Java Card Runtime Environment or Java Card RE can start the object deletion mechanism although any applet on the card can request it The applet requests the object deletion mechanism with a call to the JCSystem requestObjectDeletion method For example the following method updates the buffer capacity to the given value If it is not empty the method creat
48. les The installer receives executable binary from the off card installation program writes the binary into the smart card memory links it with the other classes on the card and creates and initializes any data structures used internally by the Java Card Runtime Environment the off card mechanism that employs a card acceptance device CAD to transmit the executable binary in a CAP file to the installer running on the card Glossary 4 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 instance variables instantiation instruction internally visible JAR file Java Card Platform Remote Method Invocation Java Card Runtime Environment Java Card RE Java Card Virtual Machine Java Card VM Java Card RE entry point objects also known as non static fields in object oriented programming to produce a particular object from its class template This involves allocation of a data structure with the types specified by the template and initialization of instance variables with either default values or those provided by the class s constructor function a statement that indicates an operation for the computer to perform and any data to be used in performing the operation An instruction can be in machine language or a programming language items that are not externally visible These items are not described in a package s export file but some such items use private tokens to represent in
49. m The applet on channel encoded in R can either accept or reject selection This command returns an error under the following circumstances m The applet does not implement the javacard framework MultiSelectable interface when an attempt to select the applet in more than one channel takes place m The applet rejects selection or throws exception No channel is available m Channel encoded in Q is not open MANAGE CHANNEL CLOSE 7 In response to the MANAGE CHANNEL CLOSE command the dispatcher follows this procedure 1 If the origin channel is not open an error is returned 2 If the channel to be closed is 0 an error is returned 3 If the channel to be closed is not open or not available a warning is thrown Chapter 2 Working with Logical Channels 2 15 2 3 4 3 2 16 4 Deselects the applet in the channel to be closed 5 Closes the logical channel This MANAGE CHANNEL CLOSE command closes channel R from channel Q CLA INS P1 P2 Le Data Le sw1 sw2 0x90 00 bxQ 0x70 0x80 OxR b This command closes channel R Channel R must not be the basic channel it can be channel 1 2 19 only This command returns an error in the following circumstances m Channel encoded in R is the basic channel m Channel encoded in Q is not open It returns a warning if channel R is not open SELECT FILE In response to the SELECT FILE command the dispatcher follows
50. mand is received the card processes it and determines whether the command has logical channel information encoding If logical channel information is encoded then the card sends the API the respective channel All other DU command to APDU commands are forwarded to the card s basic channel 0 For example the command 0x21 forwards the command to the card s basic channel 0 because the CLA byte with the nibble 0x2X does not contain logical channel information This also means that all applets willing to use the logical channel capabilities must comply with the ISO 7816 4 CLA byte encoding specification and choose APDU commands accordingly Just as the deselection and selection mechanisms must be written to take into consideration a multiple channel environment it is important to write the Applet process method so the fact that some AP that it handles channel information correctly Due to DUs can be digitally signed the APDU command is passed to the applet s process method as it is sent by the terminal That means any logical channel information is not cleare deal with this situation d and is passed intact to the applet The applet must To assist applet developers in correctly identifying proprietary and interindustry commands the following API call can be used This call returns true if the CLA byte encoding corresponds to the interindustry space or false if it corresponds to the proprietary
51. method handling data output A method could look something like this void sendData APDU apdu byte buffer apdu getBuffer short LE apdu setOutgoing short toSend if LE toSend apdu setOutgoingLength toSend while toSend gt 0 prepare data to send in APDU buffer apdu sendBytes dataOffset sentLen toSend sentLen Done 4 6 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Glossary active applet instance AID application identifier APDU API applet applet developer applet execution context applet firewall applet package assigned logical channel an applet instance that is selected on at least one of the logical channels defined by ISO 7816 a string used to uniquely identify card applications and certain types of files in card file systems An AID consists of two distinct pieces a 5 byte RID resource identifier and a 0 to 11 byte PIX proprietary identifier extension The RID is a resource identifier assigned to companies by ISO The PIX identifiers are assigned by companies A unique AID is assigned for each package In addition a unique AID is assigned for each applet in the package The package AID and the default AID for each applet defined in the package are specified in the CAP file They are supplied to the converter when the CAP file is generated an acronym for Application Protocol Data Unit as defined in ISO
52. methods the client application must obtain an instance of the CardAccessor interface The ApduI0 class implements the CardAccessor interface and is included in the framework The CardAccessor interface is a platform independent and framework independent interface that is used by the RMI framework for the Java Card platform to communicate with the card The CardAccessor object is then provided as a parameter during construction of the JavaCardRMIConnect class to initiate an RMI dialogue for the Java Card platform as the following code shows create an RMI connection object for the Java Card platform JavaCardRMIConnect jcRMI new JavaCardRMIConnect myCS Selecting the Java Card Applet and Obtaining the Initial Reference To invoke methods on the remote objects of the Java Card applet PurseApplet on the card it must first be selected using the AID select the Java Card applet byte appAID new byte 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 jcRMI selectApplet appAID Then the client must obtain the initial reference remote object for PurseApplet JavaCardRMIConnect returns an instance of a stub class corresponding to the Purselmpl class on the card which implements the Purse interface The client application knows beforehand that the PurseApplet s initial remote reference implements the Purse interface and therefore casts it appropriately obtain the initial reference to the Purse interface Purse myPurse Pu
53. national standards such as ISO7816 and industry specific standards such as Europay Master Card Visa EMV vii Who Should Use This Book This book is for applet developers using the Application Programming Interface for the Java Card Platform Version 3 0 1 Classic Edition to implement applet management multiselectable applets logical channels Remote Method Invocation RMI and extended APDUs for the Java Card platform This book is also for developers who are considering creating a vendor specific framework based on version 3 0 1 of the Java Card technology specifications Classic Edition Before You Read This Book Before reading this guide become familiar with the Java programming language object oriented design the Java Card technology specifications and smart card technology A good resource for becoming familiar with Java and Java Card technology is the Sun Microsystems Inc web site located at http java sun com You must also be familiar with the development tools released with version 3 0 1 of the Java Card platform For information on these tools see the Development Kit User s Guide Java Card Platform Version 3 0 1 Classic Edition How This Document Is Organized Chapter 1 describes how to perform object deletion applet deletion and package deletion on the Java Card platform Chapter 2 describes how to create and use applets that can be selected for use on multiple channels on the Java Card platform
54. ndor specific frameworks This book covers several topics that are substantially different from programming models found in earlier versions of the Java Card platform and is not meant to comprehensively introduce or cover general programming topics The Java Card 3 Platform currently includes releases 3 0 and 3 0 1 The Java Card 3 Platform consists of two editions both of which are backward compatible with previous versions and share key security features This book is strictly for use with the Classic APIs which appear in both editions m Classic Edition Targets more resource constrained devices that support applet based applications and contains only Classic APIs The Classic Edition is based on an evolution of the Java Card Platform Version 2 2 2 Connected Edition Features a significantly enhanced runtime environment and a new virtual machine It includes new network oriented features such as support for web applications including the Java Servlet APIs The Connected Edition supports the Classic APIs but also supports applets with extended and advanced capabilities Java Card technology combines a subset of the Java programming language with a runtime environment optimized for smart cards and similar small memory embedded devices The goal of Java Card technology is to bring many of the benefits of the Java programming language to the resource constrained world of smart cards The Java Card API is compatible with inter
55. nt Applet Example 2 11 2 3 3 Applet Firewall Operation Requirements 2 13 2 3 3 1 Working with Non MultiSelectable Applets 2 13 2 3 4 ISO 7816 4 2005 Specific APDU Commands for Logical Channel Management 2 13 2 3 4 1 MANAGE CHANNEL OPEN 2 14 2 3 4 2 MANAGE CHANNEL CLOSE 2 15 2 3 4 3 SELECT FILE 2 16 3 Developing RMI Applications for the Java Card Platform 3 1 3 1 Developing an RMI Applet for the Java Card 3 Platform 3 1 3 1 1 Generating Stubs 3 2 3 12 Running a Java Card RMI Applet 3 2 3 13 Running the Java Card RMI Client Program 3 3 3 2 Basic Example 3 3 3 2 1 Main Program 3 3 3 22 Building an Applet 3 7 323 Writing a Client 3 9 3 2 4 Card Terminal Interaction 3 13 3 3 Adding Security 3 14 3 3 1 Implementing a Security Service 3 18 3 3 2 Building an Applet 3 19 3 3 3 Writing a Client 3 21 4 Using Extended APDU 4 1 4 1 Extended APDU Nominal Cases 4 1 4 2 Extended APDU Format 4 2 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 4 3 Extended APDU Limits 4 3 4 3 1 javacardx framework ExtendedLength Interface 4 3 4 3 2 Extensions To javacard framework APDU Class 4 4 4 4 Sending and Receiving Extended APDU Commands 4 4 Glossary Glossary 1 Index Index 1 Contents v vi Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Preface This book contains tips and guidelines for developers of Classic Java Card applets and for developers of ve
56. o the same group context is active ISO 7816 4 2005 Specific APDU Commands for Logical Channel Management There are two ISO specific APDU commands that you can use to work with logical channels in a smart card m SELECT FILE This command selects the specified applet on the specified channel number The channel number can be from 0 to 3 and is specified in the lower two bits of the CLA byte If the channel is closed it is opened and the specified applet is selected on the channel SELECT FILE commands are forwarded to the newly selected applet Chapter 2 Working with Logical Channels 2 13 MANAGE CHANNEL This command can be used to open a new channel from another channel or close it It allows you to specify the channel to be used or to allow the smart card to select the channel Like SELECT FILE this command uses the lower two bits of the CLA byte to specify the channel number MANAGE CHANNEL commands are not forwarded to the applet When you work with these commands keep the following guidelines in mind Origin logical channel values are encoded in the two least significant bits of the CLA byte Logical channel values have a valid range of 0 19 only Logical channel 0 is known as the basic channel and it cannot be closed At card reset the basic channel channel 0 is open All other channels 1 2 19 are closed The MANAGE CHANNEL and SELECT FILE commands are read by the Java Card
57. oming APDU commands related to the Java Card RMI protocol The service must be initialized to allow remote methods on an instance of the PurseImp1 class A new instance of Purselmpl is created and is specified as the initial reference parameter to the RMIService constructor as shown in the following code snippet The initial reference is the reference that is made public by an applet to all its clients It is used as a bootstrap for a client session and is similar to that registered by a Java RMI server to the Java Card RMI registry RemoteService rmi new RMIService new PurseImpl Application Programming Notes Java Card 3 Platform Classic Edition July 2009 ea Then a dispatcher is created and initialized A dispatcher is the glue among several services In this example the initialization is quite simple because there is a single service to initialize dispatcher new Dispatcher short 1 dispatcher addService rmi Dispatcher PROCESS COMMAND Finally the applet must register itself to the Java Card RE to be made selectable This is done in the install method where the applet constructor is invoked and immediately registered new PurseApplet register Processing the Incoming Commands The processing of the incoming commands is entirely delegated to the Java Card RMI service which knows how to handle all the incoming requests The service also implements a default behavior for the handling of any request
58. ons such as signature verification biometrics verification and image storage and retrieval could greatly benefit from this feature Extended APDU implementations can easily be implemented if the underlying transport protocol is T 1 while applets developed for T 0 cards would need special logic and care to work correctly 4 1 Extended APDU Nominal Cases The ISO 7816 4 2005 specification defines an extended APDU as any APDU whose payload data response data or expected data length exceeds the 256 byte limit Therefore the four traditional cases are redefined as follows m Case 1 As in short length this case is not affected m Case 25 The legacy case 2 from previous Java Card technology releases LE has a value of 1 to 255 m Case 2E The extended version of case 25 where LE is greater than 255 m Case 3S The legacy case 3 case LC is less than 256 bytes of data and LE is zero m Case 3E The extended version of Case 3 where LC is greater than 255 and LE is Zero 4 1 m Case 4S The legacy case 4 LC and LE are less than 256 bytes of data m Case 4E The extended version of Case 4 LC or LE are greater than 256 bytes of data 4 2 Extended APDU Format To express extended length the APDU format has changed The table below summarizes the format defined by ISO 7816 4 2005 for extended length APDU Any APDU classified as extended must follow this format TABLE 4 1 Extended APDU Format Field Description N
59. ont soumis aux termes de la licence standard Sun Microsystems et aux conditions appliqu es de la FAR et de ces compl ments Cette distribution peut inclure des l ments d velopp s par des tiers Sun Sun Microsystems le logo Sun Java Solaris Java Card Mozilla Netscape Javadoc JDK JVM NetBeans et Servlet sont des marques de fabrique ou des marques d pos es enregistr es de Sun Microsystems Inc ou ses filiales aux Etats Unis et dans d autres pays UNIX est une marque d pos e aux Etats Unis et dans d autres pays et licenci e exlusivement par X Open Company Ltd Le logo Adobe est une marque d pos e de Adobe Systems Incorporated Les produits qui font l objet de ce manuel d entretien et les informations qu il contient sont regis par la legislation americaine en mati re de contr le des exportations et peuvent tre soumis au droit d autres pays dans le domaine des exportations et importations Les utilisations finales ou utilisateurs finaux pour des armes nucleaires des missiles des armes biologiques et chimiques ou du nucleaire maritime directement ou indirectement sont strictement interdites Les exportations ou reexportations vers des pays sous embargo des Etats Unis ou vers des entites figurant sur les listes d exclusion d exportation americaines y compris mais de maniere non exclusive la liste de personnes qui font objet d un ordre de ne pas participer d une fa on directe ou indirecte aux exportations de des produit
60. ow the concurrent execution of multiple applications on the card allowing a terminal to handle different tasks at the same time Applets written for version 2 1 of the Java Card platform still work correctly but they are unaware of logical channel support In contrast classic applets written for version 2 2 2 or later can take advantage of this feature For example you can write an applet for the Java Card 3 platform that is capable of handling security on one channel while another applet attempts to access user personal information on another channel using security information on the first By following this design it is possible to access information owned by a different applet without having to deselect the currently selected applet that is handling session information Thus you avoid losing your session specific security data which is usually stored in CLEAR_ON_DESELECT RAM memory On dual interface cards each interface itself can handle up to twenty independent logical channels Each interface has its separate pool of logical channels channels sharing the same number on two distinct interfaces will be treated as two independent separate logical channels Therefore a dual concurrent interface card could in theory support up to forty concurrent logical channels twenty per each interface Channel management commands can only affect the operation logical channels in the interface where these commands were issued For more inform
61. ples purse Purse lmpl_Stub Thus for PurseClient to run correctly on the terminal the following files must be present in the examples purse directory and accessible via its classpath or from class loaders m Purselmpl_ Stub class m Purse class Card Terminal Interaction When a Java Card technology enabled smart card is powered up the card sends an ATR Answer to Reset to the terminal The Card Accessor returns the value of the ATR to the client program FIGURE 3 1 Smart Card Sends an ATR to the Terminal Chapter 3 Developing RMI Applications for the Java Card Platform 3 13 When the PurseClient application calls the selectApplet method of JavaCardRMIConnect it sends a SELECT APDU command to the card via the CardAccessor object This results in a File Control Information FCI APDU response from the RMIService instance of PurseApplet on the card in a TLV Tag Length Value format that includes the initial reference remote object information which FIGURE 3 2 illustrates FIGURE 3 2 Terminal Sends a SELECT Command to the Smart Card which Returns FCI Later when the PurseClient application calls the debit method of the remote interface Purse the PurseImp1_Stub object sends an invoke command to the card via the CardAccessor object identifying the remote object reference interface method and parameter data for method invocation The RMIService instance of PurseApplet unmarshalls this information and invokes the debit me
62. ponents are optional the Applet Export and Debug The Applet component is included only if one or more Applets are defined in the package The Export component is included only if classes in other packages may import elements in the package defined The Debug component is optional It contains all of the data necessary for debugging a package a card session begins with the insertion of the card into the CAD The card is then able to exchange streams of APDUs with the CAD The card session ends when the card is removed from the CAD the explicit conversion from one data type to another Application Programming Notes Java Card 3 Platform Classic Edition July 2009 constant pool context context switch Converter currently active context currently selected applet custom CAP file component default applet EEPROM entry point objects the constant pool contains variable length structures representing various string constants class names field names and other constants referred to within the CAP file and the Export File structure Each of the constant pool entries including entry zero is a variable length structure whose format is indicated by its first tag byte There are no ordering constraints on entries in the constant pool entries One constant pool is associated with each package There are differences between the Java platform constant pool and the Java Card technology based constant pool For example in t
63. pplication Programming Notes Java Card 3 Platform Classic Edition July 2009 To ensure that the applets are deleted implement the uninstall method defensively Write your applet with these guidelines in mind m The applet continues to function consistently and securely if deletion fails m The applet can withstand a possible tear during the execution m The uninstall method can be called again if deletion is reattempted The following example shows such an implementation public class TestAppl extends Applet implements AppletEvent field set to true after uninstall private boolean disableApp false public void uninstall if disableApp JCSystem beginTransaction to protect against tear disableApp true mark as uninstalled TestApp2SIO removeDependency JcSystem commitTransaction public boolean select boolean appInstAlreadyActive refuse selection if in uninstalled state if disableApp return false return true Chapter 1 Using Object Package and Applet Deletion 1 5 1 6 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 CHAPTER 2 Working with Logical Channels The Java Card 3 Platform Classic Edition has the ability to support up to twenty logical channels per active interface This gives an ISO 7816 4 2005 compliant terminal the ability to open as many as twenty sessions into the smart card one session per logical channel Logical channels all
64. public class SecurePurseImpl implements Purse private short balance private SecurityService security SecurePurselmpl SecurityService security this security security public short debit short amount throws RemoteException UserException if security isCommandSecure SecurityService PROPERTY_INPUT_INTEGRITY I security isAuthenticated SecurityService PRINCIPAL_ CARDHOLDER UserException throwIt REQUEST_FAILED i if amount lt 0 balance lt amount UserException throwIt REQUEST_FAILED balance amount return balance public short credit short amount throws RemoteException UserException if security isCommandSecure SecurityService PROPERTY_INPUT_INTEGRITY security isAuthenticated SecurityService PRINCIPAL APP PROVIDER UserException throwIt REQUEST_FAILED if amount lt 0 amount gt MAX AMOUNT UserException throwIt REQUEST_FAILED balance amount return balance i public short getBalance throws RemoteException UserException if security isAuthenticated SecurityService PRINCIPAL CARDHOLDER amp amp security isAuthenticated SecurityService PRINCIPAL_APP_PROVIDER UserException throwlt REQUEST_FAILED return balance i 3 16 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Initialize a Security Service In this example basic se
65. r 2 Working with Logical Channels 2 11 In this example the code to identify the applet selection case is included in the implementation of the MultiSelectable select boolean method public boolean select boolean appInstAlreadySelected Obtain logical channels information This call returns the channel where the command was issued byte origChannel APDU getCLAChannel This call returns the channel where the applet is being selected byte targetChannel JCSystem getAssignedChannel if origChannel targetChannel This is a SELECT FILE command Do processing here if origChannel 0 This is a MANAGE CHANNEL command from channel 0 ISO 7816 4 state sharing case does not apply here Do processing here else Since origChannel 0 the special ISO 7816 4 case applies Copy security state from origin channel to assigned logical channel appState targetChannel appState origChannel Do further processing here Please refer to the Application Programming Interface for the Java Card Platform Version 3 0 1 Classic Edition for more information about the API methods described above 2 12 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 2 3 3 2 3 3 1 2 3 4 Applet Firewall Operation Requirements To ensure proper operation and protection a number of applet firewall checks have been added to the virtual
66. re needs to use only features that are supported by a Java Card platform Application Programming Notes Java Card 3 Platform Classic Edition July 2009 packag xamples purse import javacard framework import javacard framework service import java rmi public class PurseImpl extends CardRemoteObject implements Purse private short balance Purselmpl super balance 0 public short debit short amount throws RemoteException UserException if amount lt 0 amount gt MAX AMOUNT UserException throwIt REQUEST_FAILED balance amount return balance public short credit short amount throws RemoteException UserException if amount lt 0 balance lt amount UserException throwIt REQUEST_FAILED balance amount return balance public short getBalance throws RemoteException UserException return balance Here the remote interface is the Purse interface which declares the remotely accessible methods By implementing this interface the class establishes a contract between itself and the compiler by which the class promises that it will provide method bodies for all the methods declared in the interface public class PurseImpl extends CardRemoteObject implements Purse The class also extends the javacard framework service CardRemoteObject class This class provides our class with basic support for remote objects and in particular t
67. recognize the component The identifiers associated with the new component are recorded in the custom_component item of the CAP file s Directory component an applet that is selected by default on a logical channel when it is opened If an applet is designated the default applet on a particular logical channel on the Java Card platform it becomes the active applet by default when that logical channel is opened using the basic channel an acronym for Electrically Erasable Programmable Read Only Memory see Java Card RE entry point objects Glossary 3 Export file externally visible finalization firewall flash memory framework garbage collection heap installer installation program a file produced by the Converter that represents the fields and methods of a package that can be imported by classes in other packages in the Java Card platform any classes interfaces their constructors methods and fields that can be accessed from another package according to the Java programming language semantics as defined by the Java Language Specification and Java Card API package access control restrictions see Java Language Specification section 2 2 1 1 Externally visible items may be represented in an export file For a library package all externally visible items are represented in an export file For an applet package only those externally visible items that are part of a shareable interface are represented in an
68. rse jcRMI getInitialReference Using Remote Objects in Remote Method Invocations The client can now invoke remote methods on the initial reference object The remote methods are declared in the Purse interface The following code shows the client invoking the debit method Note how an UserException exception thrown by the remote method is caught by the client code in a normal Java programming language style Application Programming Notes Java Card 3 Platform Classic Edition July 2009 3 2 4 debit the requested amount try short balance myPurse debit debitAmount catch UserException jce short reasonCode jce getReason process on card exception reason information Generate the Stubs The client side scenario uses RMIC generated stubs for the remote classes RMIC is the Java RMI stub compiler For the client application PurseClient to execute correctly on the terminal it needs these remote stub classes and the remote interface class files it uses to be accessible in its classpath The stub class Purselmpl_Stub class for the PurseImp1 class is produced by running the standard JDK 1 6 compiler Note the directory where you installed the developer s kit is indicated by JC_CLASSIC_HOME For example when in the examples purse directory enter the following command rmic classpath JC_CLASSIC_HOME lib tools jar d v1 2 examples purse Purselmpl This produces a stub class called exam
69. s ou des services qui sont repi par la legislation americaine sur contr le des exportations et la liste de ressortissants specifiquement designes sont rigoureusement interdites LA DOCUMENTATION EST FOURNIE EN L TAT ET TOUTES AUTRES CONDITIONS DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE A L APTITUDE A UNE UTILISATION PARTICULIERE OU A L ABSENCE DE CONTREFA ON Si Ca Adobe PostScript Contents Preface vii Using Object Package and Applet Deletion 1 1 1 1 Object Deletion Mechanism 1 1 11 1 Requesting the Object Deletion Mechanism 1 2 1 1 2 Object Deletion Mechanism Usage Guidelines 1 2 1 2 Package and Applet Deletion 1 3 12 1 Developing Removable Packages 1 3 1 2 2 Writing Removable Applets 1 4 1 2 2 1 Using the AppletEvent uninstall Method 1 4 Working with Logical Channels 2 1 2 1 Applets and Logical Channels 2 2 2 1 1 Non MultiSelectable Applets 2 2 2 12 Interoperability 2 2 22 Understanding the MultiSelectable Interface 2 3 2 2 1 Selection for MultiSelectable Applets 2 3 2 2 2 Deselection for MultiSelectable Applets 2 4 2 3 Writing Applets For Concurrent Logical Channels 2 4 2 3 1 MultiSelectable Applet Example 2 5 iv 2 3 1 1 Handling Channel Information on APDU Commands 2 7 2 3 2 Writing ISO 7816 4 2005 Compliant Applets 2 11 2 3 2 1 ISO 7816 4 2005 Complia
70. sS amp o SUN microsystems Application Programming Notes Java Card 3 Platform Classic Edition Sun Microsystems Inc www sun com July 2009 Copyright 2009 Sun Microsystems Inc 4150 Network Circle Santa Clara California 95054 U S A All rights reserved Sun Microsystems Inc has intellectual property rights relating to technology embodied in the product that is described in this document In partic ar and without limitation these intellectual property rights may include one or more of the U S patents listed at ttp www sun com patents and one or more additional patents or pending patent applications in the U S and in other countries U S Government Rights Commercial software Government users are subject to the Sun Microsystems Inc standard license agreement and applicable provisions of the FAR and its supplements This distribution may include materials developed by third parties Sun Sun Microsystems the Sun logo Java Solaris Java Card Mozilla Netscape Javadoc JDK JVM NetBeans and Servlet are trademarks or registered trademarks of Sun Microsystems Inc or its subsidiaries in the U S and other countries UNIX is a registered trademark in the U S and other countries exclusively licensed through X Open Company Ltd The Adobe logo is a trademark or registered trademark of Adobe Systems Incorporated Products covered by and information contained in this service manual are controlled by U S E
71. space Applet s process method public void process APDU apdu byte buffer apdu getBuffer check SELECT APDU command if apdu isISOInterindu if Applet sele return else ISO Exception throwIt stryCLA ctingApplet ISO7816 SW_CLA_NOT_SUPPORTED 2 10 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 2 3 2 2 3 2 1 Writing ISO 7816 4 2005 Compliant Applets If your applets must be compliant with the ISO 7816 4 2005 specification then you must track the applet security state on each channel where it is active Additionally in the case of multiselectable applets you must copy the state including its security configuration when you perform MANAGE CHANNEL commands from a channel other than the basic channel For example applets might need to perform some sort of initialization upon activation as well as cleanup procedures during deactivation To do these tasks a multiselectable applet might need to keep track of the channels on which it is being selected during a card session To track this information you need to know the channel on which the task is being performed Tracking is done by two methods in the Java Card API m APDU class public static byte getCLAChannel This method returns the origin channel where the command was issued In case of MANAGE CHANNEL or SELECT FILE commands if this method is called within t
72. stent object values are updated atomically using transactions The term persistent does not mean there is an object oriented database on the card or that objects are serialized and deserialized just that the objects are not lost when the card loses power see AID application identifier temporary working space for storing and modifying data RAM is non persistent memory that is the information content is not preserved when power is removed from the memory cell RAM can be accessed an unlimited number of times and none of the restrictions of EEPROM apply a fully functional and compatible implementation of a given technology It enables developers to build prototypes of applications based on the technology Glossary 7 remote interface remote methods remote object RFU RID RMI ROM read only memory runtime environment shareable interface shareable interface Glossary 8 object SIO smart card an interface which extends directly or indirectly the interface java rmi Remote Each method declaration in the remote interface or its super interfaces includes the exception java rmi RemoteException or one of its superclasses in its throws clause In a remote method declaration if a remote object is declared as a return type it is declared as the remote interface not the implementation class of that interface In addition Java Card RMI imposes additional constraints on the definition of remote met
73. structurally correct an abstract storage unit A word is large enough to hold a value of type byte short reference or returnAddress Two words are large enough to hold a value of integer type Glossary 9 Glossary 10 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 Index A AID 5 1 Answer to Reset 5 2 APDU 5 1 APDU commands 2 7 ISO 7816 4 specific 2 13 API 5 1 applet 5 1 default 5 3 deletion 1 4 developer 5 1 execution context 5 1 firewall 5 1 multiselectable 5 6 multiselected 5 6 package 5 1 applet instance active 5 1 applets 2 2 3 7 3 19 deletion 1 3 firewall 2 13 ISO 7816 4 compliant 2 11 Java Card RMI 3 1 selection 2 3 application identifier 5 1 Application Programming Interface 5 1 Application Protocol Data Unit 5 1 assigned logical channel 5 1 atomic operation 5 2 atomicity 5 2 ATR 5 2 B basic logical channel 5 2 big endian 5 2 binary compatibility 5 2 bytecode 5 2 C CAD 5 2 CAP file 5 2 component 5 2 Card Acceptance Device 5 2 card session 5 2 card terminal interaction 3 13 CardAccessor objects 3 12 cast 5 2 client 3 9 3 21 commands MANAGE CHANNEL CLOSE 2 15 MANAGE CHANNEL OPEN 2 14 SELECT FILE 2 16 constant pool 5 3 context 5 3 switch 5 3 Converter 5 3 currently active context 5 3 currently selected applet 5 3 custom CAP file component 5 3 D default applet 5 3 Index 1 deletion 1 1 1 3 desel
74. t framework file jcrmiclientframework jar is present in the classpath This file contains all the client framework and necessary classes from the card framework m The file jccclient properties is present in one of the directories specified in the classpath m The remote interfaces and stubs for your applet are present in the classpath For a sample command line to run a client program refer to the file rmidemo or rmidemo bat in this directory m The jccclient properties file supplied in the samples src demo directory This file specifies parameters for com sun javacard clientlib APDUIOCardAccessor To be accessible at runtime this file must be located in one of the directories listed in the classpath This parameter connection specified in the file must be configured to be TCP The protocol being used can be TO or T1 9 2 a2 Basic Example The basic example is the Java Card platform equivalent of Hello World which is a program that manages a counter remotely and is able to decrement increment and return the value of the counter Main Program As for any Java Card RMI program the first step is to define the interface to be used as contract between the server the Java Card technology based application and its clients the terminal applications Chapter 3 Developing RMI Applications for the Java Card Platform 3 3 3 4 packag xamples purse import java rmi import javacard framework public int
75. ted private boolean preprocessCommandAPDU APDU apdu receivelnData apdu if checkAndRemoveChecksum apdu 3 18 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 7 set DATA_INTEGRITY flag else reset DATA_INTEGRITY flag return false other services may also preprocess the data private boolean checkAndRemoveChecksum APDU apdu remove the checksum return true if checksum OK false otherwise public boolean processCommand APDU apdu if isAuthenticate apdu receivelnData apdu check PIN set AUTHENTICATED flags return true processing of the command is finished else return false this command was addressed to another service no processing is done public boolean processDataOut APDU apdu add checksum to outgoing data return false other services may also postprocess outgoing data private boolean isAuthenticate APDU command check values of CLA and INS bytes 3 3 2 Building an Applet The supporting applet also must undergo some significant changes in particular regarding the initialization of the remote object Chapter 3 Developing RMI Applications for the Java Card Platform 3 19 package examples securepurse import javacard framework import javacard framework service import java rmi import com sun javacard samples SecureRMIDemo MySecurityService public class Se
76. ternal references See also externally visible an acronym for Java Archive file which is a file format used for aggregating many files into one a subset of the Java Platform Remote Method Invocation RMI system It provides a mechanism for a client application running on the CAD platform to invoke a method on a remote object on the card consists of the Java Card virtual machine the framework and the associated native methods a subset of the Java virtual machine which is designed to be run on smart cards and other resource constrained devices The Java Card VM acts an engine that loads Java class files and executes them with a particular set of semantics objects owned by the Java Card RE context that contain entry point methods These methods can be invoked from any context and allow non privileged users applets to request privileged Java Card RE system services Java Card RE entry point objects can be either temporary or permanent temporary references to temporary Java Card RE entry point objects cannot be stored in class variables instance variables or array components The Java Card RE detects and restricts attempts to store references to these objects as part of the firewall functionality to prevent unauthorized reuse Examples of these objects are APDU objects and all Java Card RE owned exception objects permanent references to permanent Java Card RE entry point objects can be stored and freely reused Examples of thes
77. that it does not recognize In Java Card RMI the following kinds of requests that can be handled m Selection request to which the service responds by sending its initial remote reference m Method invocation request to which the service responds by performing the actual method invocation and returning the result To perform these actions the service needs privileged access to some resources that are owned by the Java Card RE in particular privileged access is needed to perform the method invocation The applet delegates processing to the Java Card RMI service from its process method as follows dispatcher process apdu Writing a Client The client application runs on a terminal supporting a Java Virtual Machine environment such as Java 2 Platform Standard Edition J2SE platform or Java 2 Platform Micro Edition Java Platform Micro Edition Java ME platform The PurseClient application interacts with the remote stub classes generated by a stub generation tool and the Java Card platform specific information managed by the Java Card platform client side framework located in packages com sun javacard clientlib and com sun javacard rmiclientlib 1 The terms Java Virtual Machine and JVM mean a Virtual Machine for the Java platform Chapter 3 Developing RMI Applications for the Java Card Platform 3 9 The following example uses standard Java RMIC compiler generated client side stubs The client application as well
78. the same package are also selected on different channels The behavior to be encoded might include initializing applet state accepting or rejecting the selection request or clearing data structures in case of deselection boolean select boolean appInstAlreadySelected Implement the logic to control applet selection during a multiselection situation void deselect boolean appInstStillSelected Implement the logic to control applet deselection during a multiselection situation Note that the applet is still required to implement the Applet select and Applet deselect methods in addition to the MultiSelectable interface These methods handle applet selection and deselection behavior when a multiselection situation does not happen 254 MultiSelectable Applet Example In this example assume that the multiselectable applet SampleApplet must initialize the following two arrays of data when it is selected m An array of package data to be initialized when the first applet in the package becomes active m An array of private applet data to be initialized upon applet instance activation Chapter 2 Working with Logical Channels 2 5 You can make these distinctions in your code because the MultiSelectable interface allows the applet to recognize the circumstances under which it is selected Also assume that the applet has the following requirements m Clear the package data once no applet in the package is active m
79. thod of the Purselmpl instance and returns the return value in the response APDU which FIGURE 3 3 illustrates FIGURE 3 3 Terminal Sends an INVOKE Command to the Smart Card Which Returns a Value 3 3 3 14 Adding Security This first example is extremely simple and is not realistic In particular it does not include any kind of security Users are not authenticated and no transport security is provided Of course every smart card that implements the Java Card platform includes such security mechanisms because they are central to Java Card technology The following section describes how to add security support to the Purse example Application Programming Notes Java Card 3 Platform Classic Edition July 2009 The Purse interface in the package examples securepurse is similar to the Purse interface in the previous code sample In addition it might include reason codes for exceptions to report security violations to the terminal Replace it with examples securepurse The interface does not include any implementation which means that in particular it does not include any support for security The applet keeps its original organization but it also includes additional code that is dedicated to the management of security Chapter 3 Developing RMI Applications for the Java Card Platform 3 15 package examples securepurse import javacard framework import javacard framework service import java rmi i
80. tly First allocate a dispatcher and inform it that it will delegate commands to two different services 3 20 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 3 3 3 dispatcher new Dispatcher short 2 Then register services with the dispatcher The security service is registered as a service that performs preprocessing operations on incoming commands and the Java Card RMI service is registered as a service that processes the command requested dispatcher addService rmi Dispatcher PROCESS COMMAND dispatcher addService sec Dispatcher PROCESS_INPUT_DATA The rest of the class install and process methods remain unchanged Writing a Client The driver client application itself only changes minimally to account for the authentication and integrity needs of SecurePurseApplet It must also interact with the user for identification Hence a subclass of ApbduIO_Card_Accessor must be developed to provide these additional interactions and the transport filtering required Following is the new SecurePurseClient application import examples purse import javacard framework UserException public class PurseClient extends java lang Object public static void main java lang String argv arg 0 contains the debit amount short debitAmount short Integer parseInt argv 0 CustomCardAccessor cca null try open and powerup the card using CustomCardAccessor cca new
81. to the package or that belong to a package that depends on the package to be deleted Package deletion will not succeed if any of the following conditions exist m A reachable instance of a class belonging to the package exists on the card m Another package on the card depends on the package m A reset or power failure occurs after the deletion process begins but before it completes To ensure that a package can be removed from the card easily avoid writing and downloading other packages that might be dependent on the package If there are other packages on the card that depend on this package then you must remove all of the dependent packages before you can remove this package from the card memory Chapter 1 Using Object Package and Applet Deletion 1 3 1 2 2 1 2 2 1 1 4 Writing Removable Applets Deleting an applet means that the applet and all of its child objects are deleted Applet deletion fails if any of the following conditions exist m Any object owned by the applet instance is referenced by an object owned by another applet instance on the card m Any object owned by the applet instance is referenced from a static field in any package on the card m The applet is active on the card If you are writing an applet that is deemed to be short lived and is to be removed from the card after performing some operations follow these guidelines to ensure that the applet can be removed easily m Write cooperating apple
82. ts if shareable objects are required To reduce coupling between applets try to obtain shareable objects on a per use basis m If interdependent applets are required make sure that these applets can be deleted simultaneously m Follow one of these guidelines when static reference type fields exist a Ensure there is a mechanism available in the applet to disassociate itself from these fields before applet deletion is attempted a Ensure that the applet instance and code can be removed from the card simultaneously that is by using applet and package deletion Using the AppletEvent uninstall Method When an applet needs to perform some important actions prior to deletion it might implement the uninstall method of the AppletEvent interface An applet might find it useful to implement this method for the following types of functions m Release resources such as shared keys and static objects m Backup data into another applet s space m Notify other dependent applets Calling uninstall does not guarantee that the applet will be deleted The applet might not be deleted after the completion of the uninstall method in some of these cases m Other applets or packages are still dependent on this applet m Another applet that needs to be deleted simultaneously cannot currently be deleted m The package that needs to be deleted simultaneously cannot currently be deleted m A tear occurs before the deletion elements are processed A
83. umber of Bytes Command Header Command Header Command Header LC Field Data Field LE Field Response Data Response Status Class byte CLA Instruction byte INS Parameter bytes P1 P2 Absent for Nc 0 Present for Nc gt 0 Absent if Nc 0 present if Nc gt 0 Absent for Ne 0 present for Ne gt 0 Absent if Nr 0 present if Nr gt 0 Status bytes SW1 SW2 NOTATION Nc command data length Ne expected response data length Nr actual response data length 1 1 2 0 1 or 3 Ne 0 1 20r3 Nr max Ne 2 The encoding rules are defined as For LC m If LC field is absent Nc 0 m If LC is present as one byte with values between 01 and FF then Nc 1 255 accordingly and it will be a short field m If LC is present as an extended field then it will be three bytes in length byte one will be 00 bytes two and three will contain a 16 bit value representing the length of the data Nc with values between 1 and 65535 For LE 4 2 Application Programming Notes Java Card 3 Platform Classic Edition July 2009 m If LE is absent Ne 0 m If LE is one byte m A value between 01 and FF will indicate Ne 1 255 m A value of 00 will indicate Ne 256 If LE is an extended field LC and LE must be in the same format m An LE field value between 0001 and FFFF will indicate Ne 1 65535 m An LE field value of 0000 will indicate Ne 65536 4 3 4 3 1 Extended APDU Limits The Java
84. w to write RMI applications for the Java Card 3 Platform Classic Edition In this release you can run and debug Java Card remote method invocation Java Card RMI applications in the Java Card RE Note that the Java Card specifications state that Java Card RMI is optional therefore before using the Java Card RMI APIs ensure that your targeted card supports Java Card RMI 3 1 Developing an RMI Applet for the Java Card 3 Platform Following are the main steps for developing an RMI applet for the Java Card 3 platform 1 Define remote interfaces 2 Develop classes implementing the remote interfaces 3 Develop the main class for the applet For a simple applet the main class of the applet can also be the class implementing the remote interface 3 1 Jll 3 1 2 3 2 Generating Stubs The Java Card RMI Client framework requires stubs only when the remote_ref_with_class format is used for passing remote references These stubs of remote classes of applets must be pr generated and available on the client When the remote_ref_with_interfaces format is used stubs are not necessary In this example Sun Microsystems standard RMI Compiler rmic is used to generate these stubs Following is the command to run the rmic rmic v1 2 classpath path d output_dir class_name where path includes the path to the remote class of your sample applet and to the file tools jar output_dir is the directory in which to place the
85. xport Control laws and may be subject to the export or import laws in other countries Nuclear missile chemical biological weap ns or nuclear maritime end uses or end users whether direct or indirect are strictly prohibited Export or reexport to countries subject to U S embargo or to entities identified on U S export exclusion lists including but not limited to the denied persons and specially designated nationals lists is strictly prohibited DOCUMENTATION IS PROVIDED AS IS AND ALL EXPRESS OR IMPLIED CONDITIONS REPRESENTATIONS AND WARRANTIES INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE OR NON INFRINGEMENT ARE DISCLAIMED EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID Copyright 2009 Sun Microsystems Inc 4150 Network Circle Santa Clara California 95054 Etats Unis Tous droits r serv s Sun Microsystems Inc d tient les droits de propri t intellectuels relatifs la technologie incorpor e dans le produit qui est d crit dans ce document En particulier et ce sans limitation ces droits de propri t intellectuelle peuvent inclure un ou plus des brevets am ricains list s l adresse http www sun com patents et un ou les brevets suppl mentaires ou les applications de brevet en attente aux Etats Unis et dans les autres pays Droits du gouvernement des Etats Unis Logiciel Commercial Les droits des utilisateur du gouvernement des Etats Unis s
Download Pdf Manuals
Related Search
Related Contents
Samsung 930MP Felhasználói kézikönyv Horno electrico T'nB ADV01 DF 81x - Migros User Manual English - Velopex International Rexel Clip Files A4 PDF形式 466KB 2 - Automatismes Distribution mai 2015 - Mairie de Pommerit Sony VAIO VPCL232FX/B Copyright © All rights reserved.
Failed to retrieve file