Java Card Tutu

Embed Size (px)

Citation preview

  • 8/10/2019 Java Card Tutu

    1/16

    Developing secure Java Card applications

    Jan Vossaert Jorn Lapon Vincent Naessens

    June 9, 2010

    1 Introduction

    This tutorial covers the basic steps towards secure smart card application development withthe Java Card platform . Crucial knowledge of smart cards and the Java Card platform forapplication developers are discussed. Multiple steps during the development of Java Cardapplications are discussed. Each section also contains one or more practical assignments.All les that are required to execute the assignments are compressed in a zip le, namelyjavacardtutorial.zip 1 .

    1.1 Smart card basics

    Java Card technology adapts the Java platform for use on devices with limited memory andprocessing power. A common platform on which the Java Card technology is widely used is

    smart cards. Multiple aspects of smart cards, such as physical characteristics, transmissionprotocols and their security architecture are dened by the international standard ISO/IEC7816 [1]. Smart cards are often used in environments with strong security requirements. Exam-ples are electronic identity cards, credit cards, membership cards . . . The card performs certaincryptographic operations such as encryptions and digital signatures. Many smart cards, there-fore, provide cryptographic coprocessors that accelerate cryptographic operations. However,the Java Card platform is a card-independent high level interface that hides the complex-ity of the underlying coprocessor and the manufacturer-specic implementation details andtechnologies.

    1.2 Smart card communication

    Smart cards communicate with host applications through a request-response protocol in whichapplication protocol data units (APDUs) are exchanged. Two types of APDUs exist, namelyCommand and Response APDUs. The former are sent by the host application to the card. Thelatter are sent by the card, as a response to a C-APDU, to the host application.

    Mandatory header Optional bodyCLA INS P1 P2 Lc Data eld Le

    Table 1: The C-APDU structure.

    1. The le can be downloaded from http://www.msec.be/jan/javacardtutorial.zip

    1

  • 8/10/2019 Java Card Tutu

    2/16

    A C-APDU consists of a required header and an optional body, as illustrated in Table 1. The CLAbyte denes an application-specic class of instructions. According to the ISO7816 standard,

    byte values between 0xB0 and CF can be used. The INS byte denes a specic instructionwithin the class of instructions dened by the CLA byte. For valid CLA values, the applicationdeveloper can dene his own application specic instructions. The P1 and P2 elds can beused to further qualify the instruction and to provide input data respectively. The other eldsare optional: the Lc eld denes the number of data bytes in the data eld; the Data eldcan contain up to 255 bytes of data; and the Le eld denes the maximum number of bytesin the data eld of the R-APDU.

    Optional body Mandatory trailerData eld SW1 SW2

    Table 2: The R-APDU structure.

    An R-APDU consists of an optional body and mandatory trailer. The Data eld containsthe response data, maximum 255 bytes, returned by the applet. The elds SW1 and SW2provide feedback about the execution of the C-APDU. Several status words are predenedin the ISO7816 standard. The status word 0x9000 represents successful execution of thecommand.

    Figure 1: Overview of the possible C/R-APDU combinations.

    1.3 Java Card Virtual Machine

    The Java Card virtual machine (JCVM) is split in two components. One component runsat the machine of the developer. It veries Java classes and converts the Java classes toa CAP (Converted Applet ) le. A CAP le keeps all classes in a loadable, executable binaryrepresentation. The other component runs at the card. Amongst other things, it interpretsthe byte code and manages the objects. This separation results in a smaller memory footprinton the card. It, however, introduces additional overhead to application developers.

    Due to the memory and processing constraints of smart cards, the JCVM only supports a subsetof the Java programming language. For example, the types char , double , float , long arenot supported. Support for int is optional. Moreover, the Java core API classes and interfaces(java.io, java.lang and java.util ) are not supported except for Object and Throwable .Further, threads, the security manager and object cloning are not available. For a full overviewof the restrictions of the JCVM, we refer to the documentation in the JCDK [2].

    1.4 Java Card Runtime Environment

    The Java Card runtime environment (JCRE) is responsible for card resource management,

    applet execution, applet security . . . It separates applets from the proprietary technologies of

    2

  • 8/10/2019 Java Card Tutu

    3/16

  • 8/10/2019 Java Card Tutu

    4/16

    APDUs, or false to decline selection. The deselect() method can, for instance, be used forsession termination code.

    1 package be . demo;

    3 import jav aca rd . framework .APDU;import jav aca rd . framework . Applet ;

    5 import javac ard . f ramework . ISOExcept ion ;

    7 p u b l i c c l a s s Demo e x t e n d s A pp l et {

    9 p r i v a t e Demo ( ) {s u p e r ( ) ;

    11 r e g i s t e r ( ) ;}

    13p u b l i c s t a t i c v o id i n s t a l l ( b y te b Ar ray [ ] , s h o r t b O ff s e t ,

    15 b yt e b Le ng th ) t hr ow s I SO Ex ce pt io n {new Demo();

    17 }

    19 pub l i c vo id p roc ess (APDU arg0 ) th rows ISOExcep t ion {// TODO Auto genera ted method s tub

    21 }

    23 p u b li c b oo le an s e l e c t ( ) { re t u r n t r u e ; }

    25 p u b li c v oi d d e s e l e c t ( ) { }

    }

    Listing 1: Basic structure of a Java Card applet.

    2.2 Guidelines for Java Card development

    PIN codes and keys may not be stored in primitive arrays. The Java Card API pro-vides the class OwnerPIN that implements the PIN interface and provides protectionagainst attacks based on program ow prediction. Information about the usage of cryptographic keys can be found in section 6.

    Temporary session data are stored in transient arrays 2 . The API provides methods for

    creating transient data arrays: JCSystem.makeTransientByteArray(short length,byte memType) . This method creates a transient byte array in memory type memTypeof a certain length . Analogous methods exist for other types of arrays.

    Constants are declared as static final to reduce memory load. Instantiate all objects during initialization, typically in the constructor of the applet,

    to avoid running out of memory at runtime. This also includes the creation of transientobjects.

    2. Two types of transient memory are available: JCSystem.MEMORY TYPE TRANSIENT RESET andJCSystem.MEMORY TYPE TRANSIENT DESELECT. The former memory type is cleared when the card is re-moved from the reader while the latter is cleared upon deselection of the applet. Persistent memory holds itsvalues over different sessions.

    4

  • 8/10/2019 Java Card Tutu

    5/16

    Use the Java Card API for transactions if multiple values need to be updated simul-taneously: JCSystem.beginTransaction() , JCSystem.commitTransaction() and

    JCSystem.abortTransaction() . Note, however, that the transaction buffer capacityis nite. The sections that are protected by a transaction should, therefore, only containthe operations that are strictly necessary.

    Assignment: Set up the development environment (Windows).Download the JCDK3 . The smart cards in this tutorial support the Java Card 2.2.1 framework.Eclipse 4 is used as IDE for the development of Java Card applets. To integrate the functionalityof the JCDK, the eclipseJCDE must be downloaded and installed. This is either done by usingthe Install new software feature 5 of eclipse or by copying the eclipseJCDE jar les6 in theplugin directory of eclipse. The plugin can only be used with Java Cards 2.2.2 . However,after copying (and overwriting) the jar le org.eclipsejcde.core 0.1.0.jar 7 , the pluginbecomes compatible with Java Cards 2.2.x . The location of the JCDK needs to be specied

    in order to use the plugin (see gure 2). Finally, the environment variable JC HOME mustreference to the JCDK main directory (see Figure 3).

    Figure 2: Set location of the JCDK.

    Figure 3: Setting the environment variable JC HOME.

    Assignment: Create Java Card project.Java Card projects can now be created through the eclipse wizard (see Figure 4). Call yourproject Tutorial . Use the wizard to create an IdentityCard applet in package be.msec.smartcard .Select the default values for the applet and package AID. Note that the @Override annotation,possibly generated by eclipse, is not supported and should, therefore, be removed.

    Assignment: Paste and analyze identity card code.An identity card application is used throughout the tutorial for demonstrator purposes. Theapplet manages an identity le which can be released after the PIN was entered correctly.

    3. Different versions of the development kit can be found at:http://java.sun.com/javacard/downloads/index.jsp4. Several Eclipse distributions can be downloaded from http://www.eclipse.org/ .5. Choose the Add site option and use the following url: http://sourceforge.net/projects/eclipse-jcde/ .6. The plugin can be downloaded from http://eclipse-jcde.sourceforge.net/ .

    7. This le is included in smartcardtutorial.zip .

    5

  • 8/10/2019 Java Card Tutu

    6/16

  • 8/10/2019 Java Card Tutu

    7/16

    3.1 apdutool

    This tool can be executed via the command line (see Figure 6). The user can enter bytearrays representing APDU commands and send them to the (simulated) applet. The toolalso visualizes the applets response. Instead of manually entering the APDU commands, ascript can be passed.

    Figure 6: Using the apdutool to send and receive APDUs.

    Assignment: Test the simulated applet with apdutool.Simulate the IdentityCard applet and execute the scripts in apdutoolAssignment.zip withthe apdutool . Evaluate the APDUs sent and received from the applet. Add a command toretrieve the identity le from the card.

    3.2 apduio.jar

    The jar le apduio.jar is found in the lib directory of the JCDK and enables exchangingAPDUs with the simulator in Java programs. An example can be found in Listing 2. In thisexample a select applet command is sent to the applet. The simulator is initialized using thepowerUp and terminated using the powerDown method. Once the simulator is terminated,the state of the applet caused by the prior commands is lost.

    p u b l i c v o id s e l e c t A p p l e t ( b y te [ ] a i d ) {2 c o nn ec tTo Si m ul a to r ( ) ;

    powerUp ( ) ;4 // s en d a s e l e c t a p pl e t APDU

    transmi tAPDU(( by te )0x00 , ( by te )0xA4, ( by te )0x04 , ( by te )0x00 , a id , 127) ;6 / / . . . o th e r commands can b e s en d t o t h e s i m ul a t or h er e

    powerDown () ;8 }

    10 pub l i c Apdu t ransmi tAPDU(by te c l a , by te ins , by te p1 , by te p2 ,by te [ ] da ta , i n t l e ) t h rows IOExcep t ion , TLP224Excep tion {

    12 Apdu apdu = new Apdu( ) ;apdu . command[ 0] = cl a ;

    14 apdu .command[1 ]= in s ;apdu .command[2 ]= p1 ;

    16 apdu .command[3 ]= p2 ;

    i f ( data!=n ul l )apdu . se tDataIn ( data ) ;

    7

  • 8/10/2019 Java Card Tutu

    8/16

    18 apdu . Le=le ;t ran smit (apdu ) ;

    20 r e tu r n apdu ;}

    22p u b l i c v o i d c o nn e c tTo S im u l at o r ( )

    24 throws java . io . IOExcept ion , java . net . UnknownHostExcept ion {s o c k = new S o c ke t ( l o c a l h o s t , 9 0 2 5 ) ;

    26 I n pu tS tr e am i s = s o c k . g e tI n p ut S t re a m ( ) ;OutputStream os = sock . getOutputStream ( ) ;

    28 c ad = n ew C a dC l ie n t ( i s , o s ) ;}

    30pub l ic Apdu t ran smit (Apdu apdu) throws IOExcept ion , TLP224Exception {

    32 cad . exchangeApdu( apdu ) ;re tu rn apdu ;

    34 }36 p ubl ic void powerUp( ) throws IOExcept ion , TLP224Exception {

    cad .powerUp ( ) ;38 }

    40 pub l ic void powerDown() throws IOExcept ion , TLP224Exception {cad .powerDown ();

    42 }

    Listing 2: Creating and exchanging APDUs with applets.After transmitting the Apdu object, it will contain the response bytes of the applet. The statusbytes can be retrieved using apdu.getSW1SW2() ; the method apdu.getStatus() returns anint representation of the status bytes. If data is included in the response, it can be retrievedas follows:

    byte [ ] respDat a = new byte [ apdu . getLe ( ) ] ;2 System . ar raycopy (apdu . getDataOut ( ) , 0 , respData , 0 , apdu . getLe ( ) ) ;

    Assignment: Test simulated applet with apduio.jar.Simulate the IdentityCard applet and write a Java program in a different project that teststhe simulated applet by verifying the PIN and visualizing the identity le. The apduio.jar le should be added to the project as an external jar le. Try setting some break points

    in the applet code and run the simulator in debug mode. It is also possible to include thestandard JRE in the applet project. It is then possible to use the functions of the JRE such asSystem.out.println() .

    Assignment: Extend the applet with a certicate.The sample code can be found in CertificateTemplate.txt . The byte array certificatecontains a hardcoded certicate. Implement the getCertificate() method and test theimplementation using the simulator. Visualize some elds from the certicate via a Javaprogram.

    Some hints are provided. First, since the certicate is larger than 255 bytes, a mechanism thattruncates the certicate is required. Two approaches are possible. Either the host application

    passes to the applet which part of the certicate is requested. This can be done using the P1

    8

  • 8/10/2019 Java Card Tutu

    9/16

    or P2 elds. The applet can also keep a counter that determines which block of the certicateneeds to be sent to the host application. Second, use data blocks of 240 bytes since it then

    ts in the APDU buffer of the simulator. Finally, building a certicate from the ASN.1 DERencoding in Java can be done using the following code:

    C e r t i f i c a t e F a c t o r y c e r tF a c = C e r t i f i c a t e F a c t o r y . g e t I n s t a n c e ( X . 5 0 9 ) ;2 InputS t ream i s = new ByteArrayInpu tS tream ( encodedCer t ) ;

    X 5 0 9 C e r t i f i c at e c e r t = ( X 5 0 9 C e r t i f i c a te ) c e r tF a c . g e n e r a t e C e r t i f i c a t e ( i s ) ;

    4 Deploy smart card applications

    Once the applet is written, the class les can be compiled (i.e. the class les are convertedto a CAP le). The converter only supports class les generated with a Java compiler of aversion lower or equal to 4. The converter uses a le that contains several parameters requiredduring the conversion (see Listing 3). It can be executed through the command-line using thecommand: converter.bat -config paramFileName . The CAP le can now be passed to thecard with the open source program GPShell [6]. It uses a script le that contains the necessaryreferences and development keys to deploy applets on smart cards. To automate the wholeprocess, an Ant script was written. Some parameters, however, need to be adjusted dependingon the project conguration.

    1 ou t EXP JCA CAP

    c l a ss d i r . \ t a r g e t3 v expor tpa th C: \ Program F i l e s \ Java \ j a v a c a r d k i t 2 2 1 \ a p i e x p o r t f i l e s

    5 app le t 0x01 :0 x02 :0 x03 :0 x04 :0 x05 :0 x06 :0 x07 :0 x08 :0 x09 :0 x00 :0 x00 Ide nti tyC ardbe . msec . smar tca rd 0x01 :0 x02 :0 x03 :0 x04 :0 x05 : 0 x06 :0 x07 : 0 x08 :0 x09 : 0 x00 1. 0

    Listing 3: Example script for generating CAP les.The out parameter denes le types that are generated. The CAP le is required to deploy theapplet on the card, the others are optional. The classdir parameter references to the packagewhere the class les of the applet are stored. The v parameter enables verbose feedback aboutthe operations of the converter. The exportpath parameter references to the directory wherethe export les ( .EXP )8 of the used framework(s) is/are stored. The applet parameter denesthe AID, the name of the class extending the Applet base class, the package name and packageAID.

    mode 2012 gemXpressoPro

    e n a b l e t r a c e

    8. An export le contains the public API information for an entire package of classes. It denes the accessscope and name of a class and the access scope and signatures of the methods and elds of the class. Anexport le also contains linking information used for resolving interpackage references on the card. An exportle does not contain any implementation and can, therefore, be freely ditributed by an applet developer to the

    potential users of the applet.

    9

  • 8/10/2019 Java Card Tutu

    10/16

    4 e s t a b li s h c o n t e x tc a r d c o n n e c t

    6 s e l e c t AID A000000018434D00o p e n s c s e c u ri t y 3 k e yi n d 0 k e y ve r 0 key 47454 d5850524553534f53414d504c45

    8 d e l et e AID 0102030 4050607080 90000d e l e t e AID 0102 03040506070 80900

    1 0 i n s t a l l f i l e smart card . cap p r i v 04 sdAID A000000018434D00 nvCodeLimit 4000c a r d d i s c o n n e c t

    1 2 r e l e a s e c o n t e x t

    Listing 4: Example script for deploying applets using GPShell.Line 2 denes the card type on which the applet will be deployed. Line 7 sets up a securesession with the card; this requires a development key that allows you to place applets onthe card. Line 8 and 9 remove the original AIDs from the card. The previous version needs tobe removed if a new version is to be deployed on the card. Note that two delete commandsare issued. The rst one removes the applet AID and the second removes the package AID .Packages cannot be removed if applets within the package are still on the card. Line 10 installsthe applet on the card. This command requires the name of the CAP le and the AID of theinstaller applet ( sdAID ). priv is an optional attribute. Setting that value priv to 4 selectsthat applet by default. This means that the applet is automatically selected when the smartcard is inserted in the card reader. Hence, no select command needs to be sent. For furtherinformation about the different commands and attributes that can be used, we refer to thedocumentation that is included with the program. The program also comes with multiplesample scripts for several types of cards.

    Assignment: Deploy IdentityCard applet on a smart card.

    Copy the Ant script and additional les found in deployAssignment.zip in the Tutorial project. The script ( projectBuilder.xml ) requires the other les to deploy the identity appleton your smart card. Some les might require slight modications (paths to resources), depend-ing on your project conguration, namely CAPGenerationScript.txt , projectBuilder.xmland identityCard.txt (in the GPShell directory).

    To deploy the applet, run the Ant script. When running the script for the rst time, togglethe run configuration window of the script (see gure 7), select the method(s) of the scriptthat need to be executed (see Figure 8) and set the script to run in the same JRE as theproject workspace (see Figure 9).

    Figure 7: Toggle the run conguration window of the Ant script.

    10

  • 8/10/2019 Java Card Tutu

    11/16

    Figure 8: Select required method(s) for execution.

    5 Writing Java client applications

    From Java version 1.6, the package javax.smartcardio denes an API for communicating

    with smart cards using ISO/IEC 7816-4 APDU s. There are also methods that detect cardinsertion and card removal. The CommandAPDU and ResponseAPDU class support the differenttypes of APDUs9 described in section 1.2.

    The listing below shows an example usage of the API for sending and receiving APDUs. If the classes from javax.smartcardio are not recognized by eclipse, try removing and adding theJRE.

    TerminalFac to ry f ac to r y = TerminalFac to ry . ge tDe fau l t ( ) ;2 L i s t < CardTerminal > t e r m i n a l s = f a c t o r y . t e r m i n a l s ( ) . l i s t ( ) ;

    Card card = ter min als . get ( terminalNumber ) . connect ( ) ;4 CardChannel c = ca rd . ge tBas icChanne l ( ) ;

    byte [ ] comAPDUBytes = new byte [] { CLA, INS , P1 , P2 , Lc , data , Le } ;6 CommandAPDU command = new CommandAPDU( comAPDUBytes ) ;

    ResponseAPDU re sp = c . tr an sm it (command ) ;8 by te [ ] r ece ivedData = re sp . ge tDa ta ( ) ;

    i n t s t a t u s = r e s p . getSW ( ) ;

    Assignment: Write a Java application to test the applet on the smart card.Write a Java program that visualizes the identity le stored on the card and some elds fromthe certicate.

    9. The full API can be consulted on http://java.sun.com/javase/6/docs/jre/api/security/smartcardio/spec/javax/smartcardio/package-summary.html

    11

  • 8/10/2019 Java Card Tutu

    12/16

    Figure 9: Setting Ant script to execute in the same JRE as the workspace.

    6 Cryptographic operations with Java Cards

    The Java Card API has two packages javacard.security 10 and javacardx.crypto 11 that

    contain classes and interfaces for various types of cryptographic algorithms. However, manyJava Cards only implement a subset algorithms available in the API . More information aboutthe implemented algorithms can be found in the specications of the manufacturer. Thefollowing sections describe how the Java Card API can be used to perform cryptographicoperations such as encryption, digital signatures and hashing on smart cards.

    6.1 Random sequence generation

    The RandomData class can be used to generate random sequences on the smart card. Thesecurity of these sequences depends on the implementation of the smart card manufacturer.Note that RandomData.ALG SECURE RANDOM is not implemented in the simulator;

    RandomData.ALG PSEUDO RANDOM, however, is available.

    1 b yt e [ ] b u f f e r = new b yt e [ 2 0 ] ;RandomData ran d = RandomData . g e t I n s t a n c e ( RandomData. ALG SECURE RANDOM) ;

    3 rand . gene ra teData ( bu ffe r , 0 , bu f fe r . l eng th ) ;

    10. Package contents can be viewed in the JCDK or online:http://raud.ut.ee/ ~tec/static/api/javacard2.1.1/javacard/security/package-summary.html .11. Package contents can be viewed in the JCDK or online:http://raud.ut.ee/ ~tec/static/api/javacard2.1.1/javacardx/crypto/package-summary.html .

    12

  • 8/10/2019 Java Card Tutu

    13/16

    6.2 Key generation

    As symmetric keys are just random byte arrays, they can be generated with the RandomDataclass. For asymmetric key pair generation, the class KeyPair is used.

    1 s h o r t k e yS i ze = 5 1 2;KeyPair kp = new KeyPair( KeyPair .ALG RSA, keyS ize ) ;

    3 kp. genKeyPair ( ) ;RSAPrivateKey pr ivKey = kp. get Pr iva te ( ) ;

    5 RSAPubl icKey pubKey = kp. get Pub l ic ( ) ;

    It is also possible to create keys with a predened modulus and exponent. For this purpose,the KeyBuilder class is used. It generates empty key objects which can be initialized bysetting the modulus and exponent.

    1 s ho rt o f f s e t = 0 ;s h o r t k e y Si z e In B y te s = 6 4 ;

    3 s h o r t k e y Si z e I nB i t s = 5 1 2 ;RSAPrivateKey privKey = (RSAPrivateKey) KeyBuilde r . buildKey (

    5 KeyBuilder .TYPE RSA PRIVATE, keyS ize InB its , f a l s e ) ;p r ivKey . s e tExponent ( p r ivExponent , o f f s e t , keyS ize InBytes ) ;

    7 p r ivKey . s e tModulus ( p r ivModulus , o f f s e t , keyS ize InBytes ) ;

    9 RSAPublicKey pubKey = (RSAPublicKey) KeyBuild er . buildKey (KeyBuilder .TYPE RSA PUBLIC, keyS ize InB its , f a l s e ) ;

    11 pubKey. se tExponent (pubExponent , of fs e t , ( sho r t )3 ) ;pubKey. se tModulus (pubModulus , o f f s e t , keyS ize InByte s ) ;

    Creating symmetric key objects is similar.

    s h or t k e y Si z e I nB i t s = 1 2 8;2 AESKey symKey = (AESKey) KeyB uil der . buil dKey (

    KeyB uild er .TYPE AES TRANSIENT DESELECT, ke yS iz eI nB it s , f a l s e );4 symKey. se tKey( keyData , o f f s e t ) ;

    6.3 Encryption

    Multiple algorithms for both symmetric and asymmetric encryption are available. Both arepossible with the Cipher class. As can be seen in the code listing below, an algorithm identi-er is required when creating a Cipher object. These algorithm identiers are dened in theCipher class, examples are: Cipher.ALG AES BLOCK 128 CBC NOPAD and Cipher.ALG RSA PKCS1 OAEP.Note that if no padding is provided by the cipher (i.e. no AES implementation with paddingis available) the input data needs to be block aligned.

    Cipher c ip her = Cipher . get Ins tan ce (ALGORITHM, f a l s e ) ;2 ci ph er . i n i t (key , Ciph er .MODE DECRYPT) ;

    s h o r t e nc Le ng t h = c i p h e r . d o F i na l ( i n p u t , i n p O ff s e t , l e n g th , o ut pu t , o u t O ff s e t ) ;

    13

  • 8/10/2019 Java Card Tutu

    14/16

    Initialization vectors for symmetric encryption in CBC mode can be set with the cipher.init(key, MODE, iv, offset, length) method.

    6.4 Digital signatures

    Although the Signature class is mainly used to generate and verify signatures, multiple MACalgorithms are supported.

    1 S igna tu re s ig na tu re = S igna tu re . ge t I ns ta nce ( S igna tu re .ALG RSA SHA PKCS1, f a l s e ) ;s i gna tur e . in i t (pr ivKey , Sign atur e .MODE SIGN) ;

    3 s h o r t s i g Le n gt h = s i g n a t u r e . s i g n ( i n pu t , o f f s e t , l e ng t h , o ut pu t , 0 ) ;

    5 si gn at ur e . in i t (pubKey , Si gna tur e .MODE VERIFY) ;b o ol e an v a l = v e r i f y ( c h a l l en g e , c h a l O f f s e t , l e ng t h , s i g n a tu r e ,

    7 s i g Of f s et , s ig Le ng th ) ;

    6.5 Hashing

    The MessageDigest class can be used to generate several types of hashes.

    1 MessageDiges t d ig es t = MessageDiges t . ge t I ns ta nce ( MessageDiges t .ALG SHA, fa l s e ) ;s h o r t h as hL en gt h = d i g e s t . d o F i na l ( i n p u t , i n O ff s e t , l e n g th , o ut pu t , o u t O ff s e t ) ;

    Assignment: Extend BasicIdentityCard applet with sign functionality.To prove that the card actually contains the private key associated with the certificate ,a sign operation needs to be performed on a challenge that is sent to the card. This op-eration requires the user to enter his pin. Therefore, implement the sign method in thesample applet SignTemplate.txt . To test the implementation, simulate and/or deploy theapplication on a smart card and test it by importing the eclipse project IdentityCardHostand execute the ServiceProvider class found in package be.msec.identitycard . Note thatbcprov-jdk16-143.jar (included in the zip le) is a required library for the sample applica-tion to run. Simulated and deployed applets can be tested using IdentityCard.SIMULATORand IdentityCard.SMARTCARD respectively, when requesting an instance from the IdentityCardclass in the main method. The template contains a sample implementation of the prior assign-

    ments and the private key corresponding to the certicate as hard-coded attributes (modulusand exponent of a 512 bit RSA private key are available in byte array representation).Use the Signature.ALG RSA SHA PKCS1 algorithm for signatures 12 .

    Assignment: Extend BasicIdentityCard applet with update functionality.This extension allows to update the identity le remotely (e.g. by the government). A securesession is set up between the server and the card. A new identity le can be sent to thecard over the channel. The secure channel ensures data condentiality, data integrity, andmutual authentication. To realize this, complete the secureSession , getRemainingData andupdateIdentity methods in the sample applet of UpdateTemplate.txt .

    12. Signature.ALG RSA SHA PKCS1 PSS is not implemented in the simulator.

    14

  • 8/10/2019 Java Card Tutu

    15/16

    The secureSession method is called when the government initiates a secure session with thecard. The card receives an APDU which contains a 20 byte challenge c . The card then com-

    poses the following message (where the operator || denes a concatenation): asymEnc (K

    ses ,P K Gov ) || symEnc ([sign (c , SK Card ) || cert.length || cert || padding ], K ses ). In the aboveexpression, K ses denes a newly generated 128 bit AES session key. Since symmetric keysare random byte arrays, they can be generated using the RandomData class. P K Gov denesa 512 bit RSA public key of the government. The byte array representation of the mod-ulus and exponent of this key can be found in the sample applet. SK Card denes a 512bit RSA private key of the card. The same private key as in the above assignment can beused. The cert eld denes the certicate of the card. The certicate used in the previ-ous assignment can also be used here. The cert.length eld denes the byte length of cert . Use the Util class to convert a short to a byte array . Since the second part con-sists of a symmetric encryption with an AES key and no cipher implementations for AES with

    padding are available, the encrypted message needs to be block aligned. In AES, blocks of 16 bytes are used, which means the byte length of the encrypted message needs to be amultiple of 16. This message exceeds 255 bytes and, therefore, is sent in several steps (seegetRemainingData instruction). Use the Cipher.ALG AES BLOCK 128 CBC NOPAD algorithmfor symmetric and the Cipher.ALG RSA PKCS1 algorithm for asymmetric encryption. Althoughthe Cipher.ALG RSA PKCS1 OAEP is more secure, it is not implemented by the simulator.

    As illustrated above, the message consists of two concatenated encryptions. The rst one is anasymmetric encryption of the session key with the public key of the government. The secondone is a symmetric encryption of (1) a signature on the challenge with the private key of the card, (2) the length of the card certicate, (3) the card certicate and (4) padding. It isimportant that the message is constructed as indicated above to ensure compatibility withthe host application.

    The getRemainingData method is used to send large amounts of data to the host application.Realize this by maintaining a counter in the applet and implement the GET REMAINING DATA INSinstruction. This instruction sends consecutive blocks of 240 bytes of the buffered data to thehost application.

    The updateIndentity method receives the new identity le encrypted with the session key.This message is composed as follows: symEnc ([hash (data ) || data ], K ses ) where data isreplaced by: identityFile.length || identityFile || padding . The following operationsshould be performed on the card upon receiving this message: Decrypt the message. Check the integrity of the data by comparing the hash (20 byte SHA1) with a self-

    generated SHA1 hash of the data . Update the identity le of the card. Use the Util class to convert the length eld to a

    short and determine the bounds of the identity le.To test the implementation, simulate and/or deploy the application on a smart card and testit by executing the Government class found in package be.msec.identitycard . Simulated anddeployed applets can be tested using IdentityCard.SIMULATOR and IdentityCard.SMARTCARDrespectively, when requesting an instance from the IdentityCard class in the main method.

    A sample implementation of this assignment can be found in finalAssignment.txt .

    15

  • 8/10/2019 Java Card Tutu

    16/16

    7 Requently Occuring Problems

    I have problems importing the sample application projects in my workspace.Check that the privileges on the project les allow eclipse to read and write. In somecases the .project le is set hidden . In that case, make the le visible.

    I get an error message when converting class files or using the apdutool.First make sure that the JC HOME environment variable is set to the correct version of the framework. If the error messages still occurs, verify that no program has dened aCLASSPATH environment variable (the Belgian governmental eID middleware createsthis variable). If so, rename the variable to CLASSPATHOLD or redene this variable(set CLASSPATH=) via the command window prior to execution of the convertor.In the latter solution, the changes effect only the context of the command window inwhich the command was executed.

    When converting class files to a CAP file I receive a unsupported class fileformat error. This error occurs when the class les were compiled with a too recentversion of the Java compiler. In eclipse this is easily changed by right clicking on theproject, chose properties consequently Java compiler and then tick the enable project specic settings box and change the compiler compliance level to 1.4.

    References

    [1] Iso/iec 7816. http://www.iso.org/iso/search.htm?qt=7816&published=on&active_tab=standards .

    [2] Java card technology. http://java.sun.com/javacard/ .[3] Top im gx4. http://www.procard.pl/img/site/29/TOP_IM_GX4_Nov07.pdf .[4] Top dm gx4. http://www.gemalto.com/products/top_javacard/download/TOP_DM_

    GX4_Product_Information.pdf .[5] Global platform specications. http://www.globalplatform.org/

    specificationscard.asp .[6] Gpshell. http://sourceforge.net/projects/globalplatform/files/ .[7] Z. Chen, Java Card Technology for Smart Cards . Addison-Wesley, 2000.

    16