Smart Card Development with Java Guide
Smart Card Development with Java Guide
, Springer
Uwe Hansmann
Martin S. Nicklous
Thomas Schăck
Achim Schneider
Frank Seliger
IBM Deutschland Entwicklung GmbH
SchonaicherstraBe 220
71032 Boblingen, Germany
ISBN 978-3-540-43202-9
This work is subject to copyright. Al! rights are reserved, whether the whole or part of
the material is concemed, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilm or in any other way,
and storage in data banks. Duplication of this publication or parts thereof is permitted
only under the provisions of the German copyright law of September 9, 1965, in its
current version, and permission for use must always be obtained from Springer-Verlag.
Violations are liable for prosecution under the German Copyright Law.
[Link]
The use of general descriptive names, trademarks, etc. in this publication does not
imply, even in the absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general use.
--
Foreword - V
The unfortunate incidents on September 11 th, 2001 have re-
minded us that security systems are fragile and must be rethought.
New methods of identification must be developed - more secure,
more robust than the last generation and easy to use. New advances
in technologies, like smart cards, are paving the way to these new
systems combining means of high security and privacy at the same
time. Identification schemes need to be portable and totally reliable.
Whether the application is embedded in SIM cards for Mobil
phones, credit or debit cards, corporate or national identification
cards, the next steps are clear.
Michael D. Rhodin
Vice President, Pervasive Computing
IBM Corporation
February 2002
VI • Foreword
•
•
Foreword 1 to the First Edition
--
Foreword 1 to the First Edition - VII
smart ignition key, which will hold your preferences for seat and
mirror adjustments, and favorite radio stations.
Granted, you will not spend your day inserting plastic cards into
slots either. Smart card technology will remain mostly hidden from
you, seamlessly integrated into the products of your everyday life.
This book explains how such integration is possible. It teaches us
about developing smart card applications in "Internet time", mean-
ing in weeks instead of months. It shows us the merits of using open,
inclusive, proven standards developed by industry consortia to ad-
vance the state of the technology. It is about crossing the chasm
between the early adopters of smart card technology (mostly Euro-
pean and Asian telecommunication operators and banks) and the in-
cumbent deployers of information infrastructure technology (mostly
American IT companies).
It is somewhat ironic that you can find many of the technical
foundations of this book somewhere on the World Wide Web be-
cause of the very principles guiding the authors in their development
work. However, this book goes beyond the basic technology foun-
dations: You will find here a wealth of detailed diagrams as well as
examples and information on design rationales and tradeoffs. Smart
cards remain a relatively under-documented subject and it was in-
dispensable that the OpenCardsM and Java™ technologies explained
here, be preceded and integrated with a detailed explanation of ex-
isting smart card hardware and software platforms, as well as exist-
ing smart card standards.
Like with most other technologies, the devil is in the details. You
will find here the tools to chase the devil out of successful imple-
mentations of smart card capable products.
Patrice Peyret
Director, Sun Microsystems Inc.
Consumer & Embedded Platforms
August 1999
••
Foreword 2 to the First Edition
Sabine Schilg
Business Line Manager
IBM Pervasive Computing Solutions
August 1999
Preface ................................................................................................. 1
About This Book........................................................................ 1
The Audience of This Book ........................................... 2
No Need to Read the Whole Book ................................ 2
About the Authors ...................................................................... 8
Acknowledgements ................................................................. 10
Part I
Smart Card Introduction and Overview ...................................... 11
1 What Makes the Smart Card "Smart"? ............................. 13
1.1 What is a Smart Card? .................................................. 13
1.1.1 The Benefits of Smart Cards .............................. 15
1.2 Smart Card Hardware ................................................... 16
1.2.1 Memory Cards and Microprocessor Cards ....... 16
1.2.2 Contactless Cards ............................................... 17
1.2.3 The Computer on the Smart Card ...................... 17
1.2.4 Mechanical Contacts .......................................... 19
1.2.5 The Size of a Smart Card ................................... 20
1.2.6 Hardware Security .............................................. 21
1.2.7 The Manufacturing Process ............................... 21
2 Introduction to Smart Card Software ................................ 23
2.1 Smart Card Application Development Process ........... 23
2.2 Communication with the Card ..................................... 24
2.2.1 APDUs ................................................................ 24
2.2.2 T=O and T=I ....................................................... 26
2.2.3 TLV Structures ................................................... 27
2.3 Smart Card Operating Systems .................................... 28
2.3.1 File System Smart Cards .................................... 28
2.3.2 Java Card ............................................................ 31
2.3.3 Multos ................................................................. 32
2.3.4 Smart Card for Windows ................................... 33
--
Table of Contents - XI
3 Smart Cards and e-business ................................................. 35
3.1 Electronic Purses .......................................................... 37
3.1.1 GeldKarte ........................................................... 39
3.1.2 Mondex ............................................................... 40
3.1.3 Proton .................................................................. 41
3.1.4 Visa Cash ............................................................ 41
3.1.5 Common Electronic Purse Specification .......... 43
3.2 Authentication and Secure Access .............................. 43
3.2.1 Workstation Access ........................................... 44
3.2.2 Network- and Server-Login ............................... 44
3.2.3 Secure Communication ...................................... 45
3.3 Digital Signatures ......................................................... 46
3.4 Other Uses of Smart Cards in e-business .................... 47
3.4.1 Electronic Ticketing ........................................... 47
3.4.2 Loyalty Programs ............................................... 48
3.4.3 Growth Expected ................................................ 49
4 Cryptography ......................................................................... 51
4.1 Cryptographic Algorithms ........................................... 51
4.1.1 Symmetric Cryptographic Algorithms .............. 52
4.1.2 Public-Key Algorithms ...................................... 56
4.1.3 Hybrid Algorithms ............................................. 59
4.2 Smart Card Cryptographic Protocols ........................... 59
4.2.1 External Authentication ..................................... 59
4.2.2 Internal Authentication ...................................... 60
4.2.3 Secure Messaging ............................................... 61
4.3 TLS and Smart Cards ................................................... 67
5 Smart Card Readers and Terminals ••.............••..............•••. 69
5.1 Smart Card Readers ...................................................... 69
5.2 Smart Card Terminals .................................................. 71
5.3 Biometric Identification ............................................... 72
••
10 The Service Layer ................................................................ 145
10.1 The CardService Layer Core Components .................. 147
10.1.1 The Application Access Classes ................. 148
10.1.2 The Card Access Classes ............................ 152
10.1.3 The CardService Support Classes ............... 156
10.1.4 The CHV Support Classes .......................... 161
10.1.5 The CardService Exceptions ....................... 164
10.2 The CardService Optional Components .................... 166
10.3 Standard CardService Interfaces ................................ 168
10.3.1 The ISO File System CardService .............. 169
10.3.2 The Signature CardService ......................... 172
10.3.3 The Application Management
CardService .................................................. 173
11 The OCF Security Concepts............................................... 175
11.1 OpenCard Security Overview .................................... 177
11.2 OpenCard Security Classes ........................................ 179
11.2.1 Cryptographic Key Classes ......................... 180
11.2.2 The Smart Card Key Classes ...................... 181
11.2.3 CardService Interface Classes ..................... 183
11.2.4 Credentials ................................................... 187
11.3 Running OCF in Browsers ......................................... 188
11.3.1 Browser Security Models ............................ 189
11.3.2 Invocation of Privileged Methods ............... 190
11.3.3 Security Implications ................................... 191
Part III
Smart Card Application Development Using OCF .................. 193
12 Using OCF ............................................................................ 195
12.1 Preparing Your System .............................................. 195
12.2 Configuring OCF on Your System ............................ 196
12.2.1 Setting the OCF Configuration Properties. 196
12.3 The First Simple Application ..................................... 198
12.3.1 Starting OCF and Shutting it Down Again 199
12.3.2 Obtaining a SmartCard Object via
waitForCard( ... ) .......................................... 200
12.3.3 Obtaining a CardService Object ................. 201
12.3.4 Using this Sample Program with
Other Cards .................................................. 202
--
Table of Contents - XV
15.2 Using OCF for Card and Management.. ...................... 258
15.2.1 Example ....................................................... 259
15.2.2 Security ........................................................ 259
15.2.3 Architecture and Technology ...................... 261
15.2.4 Post-Issuance Application Download ......... 262
15.2.5 Post-Issuance Application Personalization. 264
16 OCF for 'Embedded Devices ................................................... 267
16.1 Device Profiles ............................................................. 267
16.2 OCF for Embedded Devices ........................................ 269
16.2.1 Differences between OCF and OCF for
Embedded Devices ...................................... 270
16.2.2 Footprint Statistics ....................................... 272
Part IV
Appendixes ...................................................................................... 273
A The Card .................................................................................... 275
Al The IBM MultiFunction Card ....................................... 275
A2 The File Structure on the Card ...................................... 276
A3 Accessing the Card ........................................................ 283
xv,-
,--
Taible,ai Contents
Preface
Application Developers
You will learn how to rapidly enable your applications for the use of
smart cards. You will also learn some typical patterns of smart card
usage and how to trade off various desirable properties in making
your design decisions. We assume that the reader possesses a basic
knowledge of Java.
2 • Preface
••
This book has three main parts and a supplementary section:
Chapter 4 Cryptography
Cryptography is used for the secure storage and transfer of data,
especially if smart cards are used as security tokens. We explain the
background of cryptography and give a short overview of the differ-
ent standards, algorithms, and protocols used.
4 • Preface
•
•
Introduction to OpenCard Chapter 7
We give a brief overview of the history of OpenCard and cover
the OpenCard Consortium, the driving organization behind the
OpenCard Framework. We explain the scope of OpenCard.
As an introduction to the OpenCard Framework, we explain its
objectives and give a high-level overview of its architecture, layers,
and components.
6 • Preface
•
•
tenninal could be enabled to support new or updated versions of
smart cards without manually installing software on that device.
Appendixes Part IV
Bibliography Appendix C
In this appendix, we reference the sources that we used. In addi-
tion, we point to material that is very helpful for learning more about
those areas that are not the focus of this book.
Glossary Appendix 0
The glossary briefly explains some of the most important terms.
Index Appendix E
The index helps you locate terms used and explained in this book.
8 • Preface
••
Smart Card ToolKit. The current product set of the IBM Smart Card
Solutions team in B6blingen include the IBM MultiFunction card
family, MONEO smart cards for the French market and VISA Smart
CreditlDebit smart card solutions as well as consulting and personal-
ization support for customer projects.
--
About the Authors - 9
Acknowledgements
10 • Preface
••
Part I
Smart Card Introduction
and Overview
1.1
What is a Smart Card?
Some of us already use one or more smart cards in daily life. The
smart card can be a phone card, a card carrying our health insurance
information, or an electronic purse. The latter allows us to store
digital "money" and to use this money later to pay for a ticket or buy
a drink from a vending machine.
The smart card itself is a device, which is able to store data and
execute commands. It is a single-chip microcomputer with a size of
25 mm2 at most. This microcomputer is mounted on a plastic card of
the size of a standard credit card. Plastic cards have a long tradition.
The plastic card started its career in the early 1950s when Diners The first cards
Club introduced the first credit card. This card had the name of the
cardholder printed on the front. It was used to confirm that the or-
ganization that issued the card had enough confidence in the card-
holder to allow her to buy goods or services on credit at selected
hotels or restaurants. It was now easier to go on business travel
without worrying about the amount of money that might be needed
to pay the bills. Showing the credit card at hotels or restaurants was
sufficient and the amount would be charged later to the traveler's
account at home.
Figure 1.1:
Magnetic Stripe
Card and
Smart Card
The first trials in The success of the smart card in Europe started in the early
Europe eighties. Between 1982 and 1984, Carte Bancaire (the French Bank
Card Group) had the first pilot running. Together with Bull, Philips,
and Schlumberger, Carte Bancaire launched trials in the French cit-
ies of Blois, Caen, and Lyon. The trials were a great success and had
only minor problems [TOW02]. One improvement that resulted
from these trials was the integration of a magnetic stripe onto the
smart card to maintain compatibility with existing systems.
1.1.1
The Benefits of Smart Cards
A smart card is a portable computer. Usually it has the shape and PhYSical
size of a credit card. A smart card can be made physically tamper- improvements
resistant. Therefore, it can be used as a highly secure storage for all
kind of confidential information, such as secret keys. Security and
portability are two reasons to use smart cards.
In the case of an electronic purse, the card can store the current Usage examples
balance and can tightly control increasing or decreasing it. Smart
card based electronic purses can reduce the cost of cash handling.
An important characteristic of a smart card is that the information
on it cannot be copied. A credit card's magnetic stripe can easily be
copied and then be misused. This could never happen with a smart
card-based credit card. Therefore, smart cards are recognized as the
next generation financial transaction card [VIS02].
In a building access system, the card can be used to store the data
required to open a door. The same data can later authenticate the
employee to his computer. Or it can be used for payment in the
company's cafeteria.
In home-banking applications, the card can be used as a secure
token to authenticate the user over a public network between the
user's computer and the bank's system. This is more secure than
using today's passwords l •
In a mUlti-company loyalty scheme, the card can store the loyalty
points that the customer already earned.
In a mass-transit system, the card can replace paper tickets. The
fare can be calculated based on the distance. This can be done at the
time the customer leaves the public transport system, and the fare
I We will explain the advantage of smart cards for securing network and server ac-
--
1. 1 What is a Smart Card? - 15
can be deducted from the card on the spot. Using a contactless card,
the traveler could even leave the card in her pocket.
With all these benefits of the smart card as a secure and portable
computer, we will see smart card usage grow year by year.
1.2
Smart Card Hardware
In this chapter, we touch upon the general concepts of smart card
hardware and give an overview of the technology. We do not cover
hardware technology extensively. We explain just as much as you
probably need for smart card programming in Java. You can find
more on smart card hardware and technology in the excellent book
by Rankl & Effing [RANOO].
1.2.1
Memory Cards and Microprocessor Cards
In the early days of the smart card, the card was not really smart, be-
cause it had no microprocessor. Such cards are called memory cards.
Memory cards are able to store limited information, such as the
name of the cardholder. The software in the host computer2 can then
retrieve this information.
Figure 1.2:
Memory Cards
and Microproc-
essorCards Smart (Micro-
processor) Cards
2"Host computer" here refers to the computer as host to the smart card. This can
be any computer: a PC, a larger machine, or a smaller device.
1.2.2
Contactless Cards
1.2.3
The Computer on the Smart Card
--
1.2 Smart Card Hardware - 17
Programmable Read Only Memory), and RAM (Random Access
Memory). An EEPROM requires a larger surface than a PROM of
the same size. This makes EEPROM more expensive and lets
EEPROM size become an important factor for the price of a smart
card.
Memory cards have only ROM and EEPROM. They do not con-
tain programmable logic. The EEPROM can be secured by a hard-
wired key, which is checked on every access.
Figure 1.3:
Exampleofa ROM (16 kb) EEPROM (16
Smart Card Chip • Operating System • Filesystem
and its • Communication • Program files
Components • Security (DES, • Keys
RSA) • Passwords
• Applications
CPU RAM
. 8 bit • 4kb
• 5 MHz, 5 V
• optional:
crypto-coprocessor
Figure 1.4:
Vee GND Mechanical
RST Vpp Contacts of a
elK lID
Smart Card
RFU RFU
Two out of the eight contacts are reserved for future use (RFU)
and six are actually used3• The six active contacts are:
3 Several types of cards today only have actually six contacts, for example the
phone cards in Germany. This is less expensive to produce and the lifetime of a
prepaid phone card is short enough not to conflict with potential future use of these
two contacts.
--
1.2 Smart Card Hardware - 19
1.2.5
The Size of a Smart Card
Several forms and sizes were specified for plastic cards. The two
most important forms for smart cards are ID-l and ID-ooO.
The form ID-1 has the size of a credit card and is used for most of
the applications.
The form called ID-Ooo is mostly used in mobile phones and for
Security Access Modules in terminals. ID-1 cards do not fit inside
modem mobile phones.
Figure 1.5 shows the form ID-1 and ID-OOO in one graphic, cen-
tered on the chip. Some smart cards actually come in ID-1 form with
the ID-OOO form scored to allow to break out an ID-OOO card.
1+-25mm~
10-1
14t-------85,6
.... m m - - - - - -...~~!
The main reason for the size and shape of the smart card is to
make it geometrically compatible with magnetic stripe cards. This
allows for using the same card either as smart card in new applica-
tions or as magnetic stripe card in legacy applications.
For applications where the compatibility to standard magnetic
stripe cards is not an issue, physically secure small cryptographic
units are available in other forms like a ring or button (for example
Dallas Semiconductor's iButton [ffitn02]) or as a token directly at-
tachable to the universal serial bus (for example Aladdin's eToken
[Ala02]).
1.2.7
The Manufacturing Process
Usually the following eight steps are necessary to produce and issue
a smart card [GUT98]:
2.1
Smart Card Application Development
Process
Usually a smart card application consists of the following two parts:
• Off-card application
• On-card application
The off-card part of the application is the part that resides on the Off-card
computer or terminal connected to the smart card through a smart
card reader device. The OpenCard Framework (OCF), for example,
is a framework that supports off-card application development using
Java. We will cover the development of the off-card part using OCF
in more detail in Part II of this book.
The on-card part of an application is stored in the chip of the On-card
smart card. This part can consist of data and maybe executable code.
If the on-card part has executable code, this code is executed by the
smart card operating system and can use operating system services.
2.2
Communication with the Card
The protocol stack of the communication between the smart card
and the host has several layers. On the top layer, the communication
takes place between the off-card part of an application and its corre-
sponding on-card part. The commands and data exchanged have a
meaning only for the particular application.
The next lower layer is the layer of the Application Protocol Data
Units (APDUs). The format of the APDUs is independent of the ap-
plication, but the contents and meanings are application-specific.
One layer below that, we encounter protocols with names such as
T=O and T=1. We briefly introduce these protocol layers in the fol-
lowing sections.
2.2.1
APDUs
-Header- Body
Response APDU
1 Here and in the following, we use Java syntax for expressions like this one.
--
2.2 Communication with the Card - 25
Response A Response APDU contains:
APDU
• Optional data.
• Two status word bytes SWI and SW2. They contain the status
information as defined in ISO 7816-4.
2.2.2
T=O and T=1
The protocols T=O and T=1 are the two most-used variants of half-
duplex asynchronous protocols defined in ISO 7816-3.
With T=O, each character is transmitted separately, while with
T=I, blocks of characters are transmitted.
ATR Most modem smart card readers (see Chapter 5 "Smart Card
Readers") are capable of transmitting with either one of these proto-
cols. From the card's answer to reset (ATR), the reader can find out
which protocol the card requests. The ATR is the first data block
returned to the reader after a card became powered up. In addition to
the protocol information, the ATR can contain data identifying the
type of card. The ATR is specified in ISO 7816-3.
T=0 The T=O protocol has been in use since the first days of smart
cards. The GSM card is probably the best-known application of this
protocol. Its advantage is that it has simple and space efficient im-
plementations. The price to pay for that simplicity is the incomplete
separation of the transport layer from the layer above.
To retrieve data from a smart card, two command exchanges are
necessary. In the first, the host issues the command and the smart
card returns the length of the response that it will return. In the sec-
ond (GETRESPONSE), the host asks for the expected number of re-
sponse bytes and the card returns these.
2.2.3
TLV Structures
For the encoding of data objects on the smart card, ASN.1 BER
TLVs are very popular. ASN.1 BER stands for Abstract Syntax No-
tation One basic encoding rules. This is a way of describing data
objects, which is specified in ISO 8824 and ISO 8825. In this
scheme, every data object is described as "TLV" or "Tag-Length-
Value" with a tag that identifies the type of the object, a length of the
contents, and the contents (value) itself.
TLVs allow for adding of new object types without breaking ex-
isting programs. TLVs can be nested: The value can be a TLV.
2.3.1
File System Smart Cards
ISO 7816-4 defines the smart card file system. Such a file system is
built based on the following three components (see Figure 2.3):
Figure 2.3:
Exampleofa
Smart Card File
System
• Transparent
• Fixed Record
• Variable Record
• Cyclic Record
Figure 2.4:
Fixed Variable Smart Card File
Transparent Cyclic
Records Records Types
With a transparent file, reading and writing is done as when ac- Transparent file
cessing a memory range. To access data in a transparent file, the file
identifier, the offset within the file where the reading or writing
should start, and the length of the data have to be specified.
A record file with variable or fixed record length is a structured Record file
file. The content is structured in records, as the name suggests. In a
fixed record file, all records have the same length. Within a variable
record file, the length of the records can be varying. On one hand,
this can save space on the smart card because only the necessary re-
cord length is allocated. On the other hand, a variable record file
needs some space to record each record's length. Data within the file
is in both cases accessed by specifying the record number.
The cyclic file is structured like a record file with fixed length. A Cyclic file
write operation always writes to the next record; a read operation
always reads the last written record. If all allocated memory is filled,
• Select File
• Read Binary
• Write Binary
• Update Binary
• Append Record
•
Before any other operation on a file can be performed, the file
must be selected. ReadlWritelUpdate Binary is used for transparent
files. The equivalent operations for record files are ReadlWrite/-
Update/Append Record.
Access Access to data in files (EFs) is controlled by access conditions.
conditions Before a certain operation can be performed on a file, the access
conditions for the specified operation and file must be satisfied.
These access conditions are not specified in ISO 7816-4 and vary
considerably between current operating system implementations.
Examples of some access conditions specified for IBM Multi-
Function Cards, are:
Figure 2.5:
Software Stack
of a Java Card Java Card
Frame-
work
Q)
C
:Ell>
I Java Virtual Machine (JVM)
--_.....
0-0
(Q
:?!u
0
2.3.3
Multos
MEL-API
Mullos -AAM
Silicon (Hardware)
Multos for example is in use as one of the operating systems car- Figure 2.6:
rying the Mondex purse system, which we explain in Section 3.l.2 The Multos
"Mondex". For more information on MUltos, please see Maosco's Operating
homepage: [Link] System
2.3.4
Smart Card for Windows
r----- (verified )
I Runtime
I Environment I
_ _ -.J
Internal API
I--
Access Control
(Authorization/Authentication)
G /O ~ Crypt:-
graphy
~---
I
@le g i
System
Authentication _ A merchant must know the identity of the customer. For some
kinds of business it is not sufficient that the customer authenti-
cates himself by the use of a password. In these cases an elec-
tronic version of today's identity or credit card is required. The
recipient of a message or an order should know the identity of
the sender and should also be sure that the data wasn't altered
during its transmission. This challenge is met using various
cryptographic methods to authenticate persons or messages.
Non-repudiation _ It is often necessary to assert that a particular person sent an or-
der or message and that no other person could possibly have
sent it. In traditional business the personal signature is used to
assert this, in cases of high importance combined with a witness
of the signing act. In e-business, this challenge is met using
digital signatures based on public key cryptography.
Privacy _ In most cases the exchange of data between the merchant and
the customer should be kept in secret. No unauthorized party
should be able to read or copy such a communication. This
challenge is met using encryption.
Payment _ Another issue for e-business is the method to pay for the goods
or services. Today, electronic shopping malls usually require the
customer to enter his credit card number. This is not ideal for
two reasons: First, the customer must trust that his credit card
information is kept in confidence and not abused. Second, credit
card transactions incur a cost that might be out of proportion for
low cost goods like individual newspaper articles. A replace-
ment for cash is desirable in these cases.
I The term "e-business" is more general than e-commerce. It includes also appli-
cations like supply chain management and other business-to-business flows.
--
36 - 3 Smart Cards and e-business
Smart cards can help to address all these challenges. They can be
used to authenticate persons and transactions, to get secure access to
data or services, and to protect the privacy of communication. Smart
cards are a central element for digital signatures and for electronic
purses.
In this chapter we cover security mechanisms for e-business with
a focus on smart card based schemes. In [Smith97] you can find a
detailed coverage of all major security mechanisms used to protect
communication in the Internet.
3.1
Electronic Purses
The most promising types of digital money are based on smart cards.
Several payment systems either use smart cards today or have an-
nounced plans to do so in the near future.
For security reasons, today's credit card payments usually require
on-line transactions. Having a permanent online connection or es-
tablishing a connection for every payment transaction involves costs
that can be too expensive for the payment of small amounts (some-
times referred to as "micropayment"). For the payment of small
amounts, purse systems based on a smart card provide a secure, reli-
able, and inexpensive solution. Electronic purse cards are also an at-
tractive alternative to cash in areas where cash handling is an expen-
sive task, for example, in vending machines.
As an electronic purse, the smart card stores the actual balance.
To prevent unauthorized manipulation of this balance, the smart card
requires the commands to be authenticated. Increasing and decreas-
ing the balance is secured by the use of two different cryptographic
keys.
To load money into the card, a load key is required, which is usu-
ally owned by the bank.
To draw money from the card and to transfer it to the merchant's
account, again a key is required. The merchant's terminal has this
required key. It keeps it safely inside a "Security Access Module"
(SAM). This SAM is often a second smart card, which is perma-
nently inserted in the terminal.
These security mechanisms prevent unauthorized persons from
increasing or decreasing the balance of an electronic purse card.
The concept of digital tokens provides an alternative way of im- Digital tokens
plementing digital money. This concept does not require a smart versus smart
card as a secure purse carrier, but it has the disadvantage that the card based
payment needs an on-line connection. purses
--
3. 1 Electronic Purses - 37
Digital tokens can be held on computer hard disks and manipu-
lated with the standard mechanisms provided by the operating sys-
tem. These tokens provide some resistance to simple fraud attempts.
Every token has a unique number and is digitally signed by the is-
suer. The receiver of a token can verify its signature.
When a merchant transfers a digital token to the issuer to get the
money credited to his bank account, the issuer of the token also does
some verification. The issuer again verifies the token's signature,
checks if a token with this number has been issued, and if this token
has not yet been spent.
While not being connected to the issuer's system, a merchant
cannot be sure that a digital token is not a copy of a token that was
already spent. In contrast, systems based on smart cards do not re-
quire that a merchant is connected to the issuer's system while ac-
cepting a payment.
Many Currently there are more than 40 different electronic purse sys-
electronic tems in use or in trial operations. Some of the more widely known
purses - all systems are listed in Table 3.1. Cards are valid for one system only
incompatible to and cannot be used to pay in any other system. Money cannot be di-
each other rectly transferred from a card of one system to a card of a different
system. It does not help the attractiveness of electronic purses if the
cards of one system are accepted in just one country. Especially with
the Euro now being the currency for 300 million people in twelve
European countries, consumers will hardly prefer a great selection of
incompatible electronic purses to cash in a common currency.
A new initiative, the Common Electronic Purse Specification
(CEPS) attempts to lay the foundation for a global system of com-
patible individual electronic purse systems [CEPSOO].
3.1.1
GeldKarte
2 The ZKA counts as active and in use every card which has been used for pay-
ment or loading at least once a month.
--
3. 1 Electronic Purses - 39
Internet. These pilots used standard smart card reader without the
enhanced security required by the ZKA. Currently several of these
systems are going into production. The reader required for Geld-
Karte payments over the Internet must have an integrated display
and PIN-pad. This type of readers is also called "class-3 reader".
3.1.2
Mondex
3.1.4
Visa Cash
--
3. 1 Electronic Purses - 41
card acceptance infrastructure forms a good base for a chip-based
purse as an add-on to the Visa credit card.
Visa Cash cards can be reloadable or disposable, associated with
an account or not associated with an account. Reloadable Visa Cash
cards can be loaded. Disposable Visa Cash cards can only be bought
with prepaid value on it. With a reloadable Visa Cash card that is as-
sociated with a bank account, the customer can transfer money from
his account to his card and vice versa. In the case of reloadable cards
that are not associated to a bank account, the funds can be obtained
from cash or any account and be loaded onto the card.
The merchant has to pay a transaction fee that is usually a per-
centage of the transaction amount. There is no transaction fee for the
customer.
Trials Together with local banks, Visa International has trials running in
several countries around the world. The first trial started in 1995,
when Bank of America issued about 2,000 Visa Cash cards to em-
ployees of Visa International. These cards are used at Visa's head-
quarter at vending machines and in its cafeteria. During the 1996
Olympic Games in Atlanta, three large local banks issued about two
million Visa Cash cards to visitors and citizens of Atlanta. The cards
were used at merchants, Olympic venues, and in the public transit
system of Atlanta.
Components A Visa Cash system consists of the following three components:
3.1.5
Common Electronic Purse Specification
Since 2002, the Euro replaces national bank notes and coins in
twelve European countries. This common European currency will
create additional momentum to merge the electronic purse systems
that are not interoperable. Consumers will expect that they can use
their electronic purse in the same way they could use the Euro in all
participating countries.
Europay International (the organization behind Europe's Euro-
card), Visa International, Visa Spain, and the ZKA (the owner of
Germany's GeldKarte specification) founded the Common Elec-
tronic Purse Specification (CEPS) Group. Mondex is notably not a
member of this group. The CEPS group works on defining a com-
mon standard for electronic purse systems, which can be used and
are compatible worldwide. Organizations from 22 countries, repre-
senting more than 90 percent of the world's electronic purse cards,
have agreed to implement CEPS. The specifications were finalized
in August of 1999 and during 2001 the first cards supporting CEPS
were available.
It is natural that CEPS tries to accommodate existing specifica-
tions and systems as much as possible. For the chip cards, CEPS is
based on the EMV specifications (see Section 6.2 "ICC
Specifications for Payment Systems"). In addition, CEPS specifies
the card-to-terminal interface, the terminal application for point-of-
sale and load-transactions, and the data elements and recommended
message formats for transaction processing. It also provides func-
tional requirements for the various electronic purse scheme partici-
pants. For enhanced security, CEPS requires the use of public key
cryptography.
3.2
Authentication and Secure Access
The challenge of identifying a person on the local computer, or on
the other end of a communication session, or in the role of the sender
of a message, is a recurring theme in e-business. Here the smart card
plays an important role as a secure device with cryptographic capa-
bilities.
3.2.1
Workstation Access
3.2.2
Network- and Server-Login
3.2.3
Secure Communication
--
3.2 Authentication and Secure Access - 45
many nodes. To protect its privacy, the e-mail client of the sender
encrypts the data and the e-mail client of the receiver decrypts them.
Established schemes for encrypting and decrypting e-mail use
public key cryptography (for example PGP [PGP02]). On the
sender's side the data is encrypted using the public key of the re-
ceiver, and on the receiver's side it is decrypted using the receiver's
private key. If the receiver stores his private key on a smart card, it
will be always with him and still be kept secure.
3.3
Digital Signatures
3.4
Other Uses of Smart Cards in e-business
The Internet as a ubiquitous network leads to new opportunities in
various areas of commerce. We have seen examples of how the
smart card can help to protect the data and communication on the
net.
On the other hand, we can think of the smart card as an extension
of the network. It allows the owner to load data onto the card while
connected to the net and to later use this data at off-line devices.
In the following we present some applications of smart cards, in
which the smart card is used at times connected to the network and
at other times off-line.
3.4.1
Electronic Ticketing
--
3.4 Other Uses of Smart Cards in e-business - 47
with the smart card through the local software stack and attached
hardware.
In the theater or bus or at the gate, it is often not practical or cost
effective to have the device receiving the electronic tickets con-
nected to the ticketing server. With an online device the server could
detect and prevent fraud attempts, like using the same ticket more
than once. Having no online connection, we need a smart card to
prevent fraud. A smart card with its cryptographic function and se-
cure data storage can prevent the copying or forging of tickets (see
our discussion on electronic purse cards and digital tokens in Section
3.1 on page 37). Therefore a smart card allows the secure use of
electronic tickets with devices that are currently off-line. Requiring a
permanent network connection for all collecting devices in trains, at
airports, or at theater entries would make electronic ticketing too ex-
pensive in most cases. For these applications the use of smart cards
is attractive.
Especially contact-less smart cards are very convenient for users.
With contact-less smart cards users can pass for example a gate to a
subway without pulling the smart card out of his pocket and the
ticket is automatically checked while he passes the gate.
3.4.2
Loyalty Programs
--
3.4 Other Uses of Smart Cards in e-business - 49
4 Cryptography
4.1
Cryptographic Algorithms
In this section we give an overview on the most relevant crypto-
graphic algorithms in the smart card environment.
There are two important classes of cryptographic algorithms that
we want to present - symmetric algorithms and asymmetric algo-
rithms. While symmetric algorithms use the same key for encryption
and decryption of data, asymmetric algorithms use two keys - what
one key encrypts, the other one decrypts.
--
4.1 Cryptographic Algorithms - 51
4.1.1
Symmetric Cryptographic Algorithms
[Link]
DES
The Data Encryption:Standard was developed in a program to pro-
tect computer and communications data, initiated by the National
Bureau of Standards ',(NBS) and the National Institute of Standards
and Technology (NIST) in 1972. The first request for proposals was
issued in 1973, but none of the submissions met the requirements. A
second request was issued in 1974 and this time, the NBS received a
promising proposal from IBM, which became DES.
The DES algorithm is a block cipher, i.e. an algorithm that di-
vides the data to be encrypted into blocks and operates on one block
at a time. DES uses a block size of 64 bits and a key size of 56 bits.
Actually, DES keys are represented by 64 bits, but the least signifi-
cant bit of each byte is used for parity checking only and ignored by
the algorithm.
The fundamental building block of DES is a substitution followed
by a permutation, called a round. DES has 16 rounds i.e. 16 substi-
tutions and permutations are applied to each 64-bit block of data.
Because of its repetitive nature, DES can be easily implemented in
hardware.
The key size of 56 bits used in the DES algorithm is quite small.
Given today's powerful computers, the DES algorithm offers only
mediocre security. At RSA '99, a DES challenge was announced
52 • 4 Cryptography
•
•
where the 56-bit key was broken in less than 24 hours, although
more than the average of 50 percent of the key space had to be
searched by a network of many cooperating computers.
[Link]
Trip/eDES
Triple DES is based on DES, but uses 112-bit keys. The key is di-
vided into two 56 bit keys, K j and ~. The data to be encrypted is
first encrypted under Kj' then decrypted under ~ and encrypted
once again under K j • This is also known as the encrypt-decrypt-
encrypt (EDE) mode. To decrypt, the cipher is decrypted using Kj'
encrypted using ~ and decrypted using K j again.
Triple DES offers a very high level of security. Brute force at-
tacks like against DES are not feasible, because the key space to be
searched grows exponentially with the size of the key, i.e. finding a
112 bit key by exhaustive search takes i 6 times more time than
finding a 56-bit key.
[Link]
DES Encryption Modes
There are several different DES modes that are often used in con-
junction with smart cards. The simplest mode is the Electronic Code
Book (ECB) mode. ECB mode encryption means that the encrypt-
operation is applied to each single 64-bit block of plaintext, as
shown in the following Figure 4.1:
Figure 4.1:
Plaintext 1
DES ECBMode
64 bit - Each 64-bit
Block is
DES Encrypt Separately
Encrypted
64 bit 64 bit
Ciphertext 1 Ciphertext 2
--
4. 1 CryptographiC Algorithms - 53
block of plaintext is XORed with the ICV and the result is en-
crypted, obtaining the first ciphertext block. Each following data
block is XORed with the result of the previous DES operation, the
result is encrypted to obtain the next block of ciphertext.
Figure 4.2:
DESCBCMode
Encryption
Figure 4.3:
DESCBCMode
Decryption
[Link]
Message Authentication Codes
DES cannot only be used for encrypting data, it is also possible to
use the DES algorithm for calculating Message Authentication
Codes (MACs). A MAC ensures data integrity and can also be used
for authentication. Here we present MAC calculation according to
ANSIX9.9.
54 • 4 Cryptography
••
Figure 4.4:
DESCBCMode
MAC
Calculation
You may realize that the result is equal to the last ciphertext block
obtained from CBC encryption. This means that given a DES CBC
implementation, a MAC can be obtained by encrypting the relevant
data and taking the last 64-bit block of the cipher text.
[Link]
AES
The Advanced Encryption Standard (AES) is the successor of the
Data Encryption Standard. Many algorithms have been proposed for
the new standard and had to go through an extensive selection pro-
cess. Out of five finalists, the NIST chose the Rijndael algorithm de-
signed by Joan Daemen and Vincent Rijmen.
Rijndael is a block cipher with variable block length and key
length that allows using keys with a length of 128, 192, or 256 bits
to encrypt blocks with a length of 128, 192 or 256 bits. All nine
combinations of key length and block length are possible in Rijndael
and it is possible to extend both block length and key length to mul-
tiples of 32 bits.
Choosing from these options, the Advanced Encryption Standard
specifies a block size of 128 bits and key lengths of 128, 192, or 256
bits, the other options are not adopted in the standard. The AES al-
gorithm can be implemented very efficiently in software on a wide
range of processors as well as in hardware. For detailed information
about the AES algorithm, see [AESO 1].
--
4. 1 Cryptographic Algorithms - 55
[Link]
Other Symmetric Algorithms
There are many other symmetric algorithms besides DES, like RC4,
RC5, IDEA, Skipjack etc., but these algorithms are virtually irrele-
vant in the smart card area. You can find information on these algo-
rithms as well as more details on the concepts and history behind
DES and Triple DES in [SCH96].
4.1.2
Public-Key Algorithms
The basic idea that led to public key algorithms was that keys could
come in pairs of an encryption and a decryption key and that it could
be impossible to compute one key given the other. This concept was
invented by Whitfield Diffie and Martin Hellman [DIF76], and in-
dependently by Ralph Merkle [MER78].
Since then, many public-key algorithms have been proposed,
most of them insecure or impractical. All public-key algorithms are
very slow compared to secret key algorithms. The well known RSA
algorithm for example takes about 1000 times longer than DES
when implemented in hardware, 100 times longer in software to en-
crypt the same amount of data. However, public-key algorithms
have a big advantage when used for ensuring privacy of communi-
cation: Public-key algorithms use different keys for encryption and
decryption. The private key may only be known to its owner and
must be kept in secret. It may be used for generation of digital sig-
natures or for decrypting private information encrypted under the
public key. The public key may be used for verifying digital signa-
tures or for encrypting information. It needs not to be kept secret,
because it is infeasible to compute the private key from a given pub-
lic key. Thus, receivers or signers of messages can post their public
key to a directory, where everybody who wants to send a message
can look it up. Each entity in the network only needs to store its own
private key and a public directory can store the public keys of all
entities, which is practical even in large networks.
[Link]
RSA
The RSA algorithm was invented by Ron Rivest, Adi Shamir, and
Leonard Adleman [RlV78], [RlV79]. It is based on the difficulty of
factoring the product of two large prime numbers. RSA uses key
pairs, where the public key consists of a modulus m and a public ex-
56 • 4 Cryptography
•
•
ponent e and the private key consists of the same modulus m and a
private exponent d.
The two keys are generated from two randomly chosen large
prime numbers, p and q. To assure maximum security, the lengths of
these numbers should be equal. The modulus m is computed as the
product of the two primes:
m=pq
Let x be the plaintext with the same size as the modulus and y be
the ciphertext. Then the formulas for encryption and decryption are
as follows:
y =xe modm
x=/modm
[Link]
DSA
The National Institute of Standards and Technology (NIST) pro-
posed the Digital Signature Algorithm (DSA) in 1991 for use in the
Digital Signature Standard (DSS). The security of the algorithm re-
lies on the difficulty of computing discrete logarithms in a modulus
whose length defines the key size. The algorithm was designed by
the NSA, which along with the proposed key size of only 512 bits
led to criticism regarding its security. In 1994, the standard was is-
sued with a variable key length from 512 to 1024. The DSA algo-
rithm works as follows:
--
4. 1 Cryptographic Algorithms - 57
p = a prime with 512 to 1024 bits, a multiple of 64 bit.
q= 160-bit prime factor of p-l.
g= mod p, where < p-1 such that
h(p-J)/q h mod p > 1.
h(p-J)/q
x<q.
y = g'modp.
r and s are the signature and are sent along with the message. The
receiver verifies the signature by performing the following calcula-
tions:
w=s-J mod q
uJ = (H(m) * w) mod q
u2 = (rw) mod q
v = ((gUJ * yU2) mod p) mod q
[Link]
Elliptic Curve
Elliptic curves were first proposed for use in public-key cryptosys-
terns in 1985 [KOB87, MIL86]. Algorithms using Elliptic Curves
are faster than RSA or DSA and require smaller key sizes for the
same level of security. Elliptic Curves over the finite field GF(2n) are
especially interesting, because they allow for efficient implementa-
tions.
The advantages of Elliptic Curves make them good candidates for
use on smart cards, because the computations can be conducted even
on smart cards without a cryptographic coprocessor and the small
key sizes save valuable space in the smart card's memory. However,
the Elliptic Curve Algorithm is supported by few of today's smart
cards. Virtually all e-business products on the market, like Web
Servers, Certificate Authorities, middle-ware, cryptographic librar-
ies, SSL implementations etc., already support RSA and DSA, so
that smart cards must support these algorithms to be usable in exist-
58 • 4 Cryptography
••
ing public-key infrastructures. Support of RSA and DSA on smart
cards requires a cryptographic coprocessor and a persistent memory
size of at least 8 Kbytes anyway, so that not needing a coprocessor
in not a real advantage in many cases.
4.1.3
Hybrid Algorithms
As mentioned above, symmetric algorithms are fast but have the dis-
advantage of being impractical in networks connecting many enti-
ties. Asymmetric Public Key Algorithms on the other hand are prac-
tical in such networks, but have the disadvantage of being slow.
However, the advantages of both can be combined while avoiding
the disadvantages. Hybrid Algorithms use randomly generated ses-
sion keys for symmetric algorithms used for the symmetric bulk en-
cryption. Then, the session key is encrypted using an asymmetric al-
gorithm. The fact that the asymmetric algorithm is slow doesn't
matter in this case, because only the session key is encrypted using
that algorithm. Most of today's software uses such a combination of
secret-key and public-key algorithms.
4.2
Smart Card Cryptographic Protocols
In this section we give some examples of cryptographic protocols -
protocols including cryptographic operations for establishing trust
between involved entities - in the smart card area. The most impor-
tant protocols are external authentication, internal authentication and
secure messaging.
4.2.1
External Authentication
--
4.2 Smart Card Cryptographic Protocols - 59
2. The smart card creates a random number r, stores it and returns it
in the response to the external entity.
3. The external entity uses a cryptographic key corresponding to a
cryptographic key in the smart card to encrypt r. It sends an
authentication command containing the encrypted random num-
ber to the card.
4. The smart card receives the authentication command and decrypts
the encrypted random number contained in that command. If the
result is equal to the stored random number r, the smart card as-
sumes that the external entity is authentic.
Result
4.2.2
Internal Authentication
60 • 4 Cryptography
••
External Entity Smart Card Figure 4.6:
Pick Key Number Internal Authenticate(r, '.!!. Authentication of
a Smart Card to
n to be used
an External
Entity
4.2.3
Secure Messaging
[Link]
Protected Mode Operations
The first scheme we want to explore is a very simple one, where the
smart card and the external entity accessing the card share a com-
mon key, which is used for calculating a Message Authentication
Code (MAC) over the transmitted data. The purpose of a MAC is to
--
4.2 Smart Card Cryptographic Protocols - 61
ensure integrity and authenticity of transferred messages. Figure 4.7
shows how this scheme works when reading data from a smart card
with a file system:
62 • 4 Cryptography
•
•
External Entity Smart Card Figure 4.8:
Secure
Messaging
Get Random in Write-
Generate and store Operations
random number r
Calculate MAC r
over data using WriteProtected(
rand ke" file, offset, data, MAC)
Calculate MAC' over
data using rand kflle,
write data to file if
MAC =MAC'
data + MAC
[Link]
Protected and Encrypted Mode Operations
Now we take a look at reading and writing data in encrypted mode.
Usually, the smart card or the external entity first calculates a MAC,
then appends it and encrypts the data plus the MAC. Figure 4.9
shows the read operation:
--
4.2 Smart Card Cryptographic Protocols - 63
Figure 4.9: External Entity Smart Card
Secure Generate and
Give Random(r)
Messaging and store random
Store random
Encryption of numberr
numberr
Data Read from
ReadProtected(file, offset, len)
a Smart Card ~
Read data, calculate
Decrypt data+MA,C MAC using rand [Link],
Calculate MAC' encrypt data + MAC,
over data using send back cipher
rand k..t eldlle{data + MAC)
=
MAC MAC'?
64 • 4 Cryptography
•
•
3. The external entity computes a MAC over a part of the write
command APDU header and the data to be written to the smart
card using the random number r and the key kext' This key must
match the key kfile that protects the file on the card. Then, the ex-
ternal entity encrypts the relevant part of the APDU, the data and
the MAC and constructs the entire command from the clear part
ofthe APDU header and the ciphertext.
4. The smart card receives the write command. It decrypts the cipher
contained in the command using the random number r and the
appropriate key kfile' It calculates a MAC over the relevant part of
the command APDU header and the contained data using the
same key kfi/e and random number r. If that MAC equals the MAC
contained in the command, the data is actually written to the
smart card's persistent memory.
66 • 4 Cryptography
•
•
4.3
TLS and Smart Cards
TLS is the abbreviation for Transport Layer Security, the successor
of SSL 3.0. The current version is TLS 1.0, which is still very simi-
lar to SSL 3.0 (see [DIE99]). The primary goal of TLS is to provide
privacy and data integrity of messages exchanged between two
communicating parties over an untrusted network - like the Internet.
In addition, TLS also allows for mutual authentication of the com-
municating parties.
The TLS protocol consists of several layers. The lowest layer is
the TLS Record Protocol that assures privacy and reliability of con-
nections and is used for encapsulating higher-level protocols, like
the TLS Handshake Protocol. This protocol provides connection se-
curity that ensures that the peer's identity can be authenticated using
public key cryptography and that the negotiation of a shared secret is
secure and reliable.
When TLS is used to secure client-server communication, in most
cases the handshake protocol only conducts server authentication:
During the handshake protocol, the server transmits its certificates to
the client. The client validates the server certificates and extracts the
public key from one of the certificates. This key is used to encrypt
the session key for further communication.
However, for e-business applications additional client authentica-
tion is often required to ensure that only authorized people can ac-
cess certain services or information. TLS allows for optional client
authentication: During the handshake protocol, the server can send a
Certificate Request that requires the client to send its certificate and
a Certificate Verify message to the server. The server can authenti-
cate the client by validating the obtained certificate and using the
public key from that certificate to verify the client's signature con-
tained in the Certificate Verify message.
Client authentication in TLS requires a private key and a certifi-
cate at the client; its security relies on the security of the private key
of the client. To achieve maximum security and mobility, the private
key and the certificate for authentication can be stored on a smart
card with a cryptographic coprocessor. Such a card can generate the
digital signature for the Certificate Verify message on-card, so that
the private key never has to leave the secure storage of the smart
card. An additional advantage of using smart cards for client
authentication is that the user is not bound to a particular PC that
holds the authentication credentials; she can use the smart card with
the authentication credentials in various devices.
_ Readers and
_ Terminals.
5.1
Smart Card Readers
Smart card readers often have their own housing and are connected
to the serial-, parallel-, or USB-port of a computer. Other reader
types are integrated in a keyboard or fit into a PCMCIA slot. An-
other reader type has the size of a 3.5" diskette and is inserted into a
diskette drive to be connected to the computer.
--
5. 1 Smart Card Readers - 69
Readers can In addition to the card slot and the computer interface, a smart
have a display card reader can also have a display and a PIN-pad (see Figure 5.1).
and a PIN-pad The main use of the PIN-pad is to enter a PIN (Personal Identifica-
tion Number), which is sent to the smart card to identify the card
owner.
Most readers have only one slot for a smart card. For special ap-
plications like a medical patient card, which can only be accessed
upon authorization through a doctor card, the reader can have a sec-
ond card slot.
Figure 5.1:
Smart Card
Readers
(TOWITOKO)
5.2
Smart Card Terminals
The advantage of a smart card terminal over a smart card reader at-
tached to a computer is a tighter control of the smart card access. A
terminal can be sealed to prevent tampering with the hardware. The
software installation can be tightly controlled by special schemes,
which could not be applied to a general-purpose computer.
Figure 5.2:
Smart Card
Terminal
(Intellect IPT
200012010)
5.3
Biometric Identification
Often, it is not sufficient just to have the card (identification through
"something that you possess"). Most of the systems require the user
to identify himself as the rightful holder of the card. The most com-
mon additional cardholder identification is to enter a password or a
Personal Identification Number ("something that you know").
Passwords and PINs are not very user-friendly and not com-
pletely immune to misuse and fraud. The cardholder can forget them
and bystanders can steal them. Therefore, various biometric identifi-
--
5.3 Biometric Identification - 73
Part II
OpenCard Framework
Standards like ISO 7816 and industry initiatives like EMV or Open-
Card are necessary to ensure that smart card aware applications,
cards, and card readers are built to uniform specifications. Without
standards, interoperability is not possible. A smart card application
or a card itself would be usable only in a very limited environment.
But smart cards, readers, and applications developed and manufac-
tured according to standards also work with devices developed by
another company in a different part of the world.
In this chapter we will give a brief overview of some standards
and industry initiatives important for developing a smart card appli-
cation.
6.1
ISO Standards
6.2
EMV ICC Specifications for Payment
Systems
In June of 1996, Europay, MasterCard International, and Visa Inter-
national (EMV) published EMV'96: ICC Specifications for Payment
6.3
PC/SC
PC/SC, with full name Interoperability Specification for ICCs
and Personal Computer Systems 1.0 [PCSC02], covers the use of
smart cards with personal computers. In eight parts, this specifica-
tion spans the entire range from the physical characteristics required
from smart cards and readers to the layer of application program-
ming. The specification is based on and is compatible with ISO
7816. The focus is on the interoperability of smart card (called In-
tegrated Circuit Card or ICC) and smart card reader
(called Interface Device or IFD) and on the cooperation
between the reader and the PC operating system.
The PC/SC Workgroup was formed in May 1996. The companies
that drove the PC/SC specification 1.0 are: CP8 Transac (Bull),
Gemplus, Hewlett-Packard Company, IBM, Microsoft Corporation,
Schlumberger SA, Siemens Nixdorf Informationssysteme AG, Sun
Microsystems, Toshiba, and Verifone. Most members are today of-
fering PC/SC compliant products, particularly smart card readers of
all kinds. Today the core members of the PC/SC workgroup are Ap-
ple, Bull, Gemplus, Hewlett-Packard, Infineon, Intel, Microsoft,
Schlumberger, and Toshiba.
The eight specification parts ofPC/SC 1.0 (see Figure 6.1) are:
6.3 PC/SC • 79
•
•
PC/SC 1.0 Requirements for PC-Connected Interface
Part 3 Devices
Part 3 specifies the characteristics of the Interface Device Sub-
system. To let the higher layers of PCISC communicate with the In-
terface Device (IFD) in a device independent way, an IFD Handler
adapts the IFD to a common programming interface. The IFD must
provide basic functions like sending commands to the card or
checking for card insertion. Optionally it can have various other ca-
pabilities, such as powering up or down the card inserted, or getting
a user authentication with a PIN pad, keyboard, fingerprint scanner,
etc.
Figure 6.1:
PART 7 Layers of the
Applicalion~
PC/SC
Architecture and
the Eight Parts
of the
Specification
P
0\
I' RT ~ R
r
PARI 3
1m 110 ltD
lIandler lIandl .. [Link]
1..0 11'0
•
ICC
• •
6.3 PC/SC • 81
•
•
Implementations Microsoft has provided implementations of the PC/SC 1.0 speci-
ofPC/SC fications on the Windows 95 and Windows NT 4.0 platfonns and
has released this implementation to the World Wide Web. For Win-
dows 98, the implementation is shipped as part of the installation
package. In Windows 2000, as well as in Windows XP, the resource
manager is part of the operating system.
PC/SC 2.0 was originally scheduled for 2000, but currently no
date is foreseeable. An update on the status on PC/SC 2.0 and a list
of planned items can be found on the PCSC Workgroup homepage
on [Link] list was published as part
of a white paper in 1999.
6.4
GlobalPlatform
In the mid 90s, Visa started its Open Platfonn activities to specify an
integrated environment for the development, issuance, and operation
of multi-application smart cards. This environment should guarantee
the interoperability of smart card solutions (including the card, the
terminal, as well as the required software on the card, the terminal,
and the backend system) on card application and card content man-
agement level.
GlobalPlatfonn was founded in 1999 by Visa together with sev-
eral other companies to maintain and continue the development of
the Open Platfonn specifications. In early 2002 GlobalPlatfonn had
about 45 members including companies like British Telecom Ignite,
Gemplus, Giesecke & Devrient, Infineo, Mastercard International,
Microsoft, NEC, NIT, Proton World, Schlumberger, STMicroelec-
tronics, Sun, Toshiba, and of course Visa International. The Open
Platfonn specifications have been renamed to GlobalPlatfonn speci-
fications.
The GlobalPlatfonn Specifications consists of three parts: A card
specification, a device specification, and a system specification.
The device specification, also called terminal specification, fo-
cuses on stand-alone payment terminals. This part was started later
than the card specification. Its first version was made available to the
public in spring of 1999. The current version 1.5 was published in
November 1999.
The system specification is the latest addition to the GlobalPlat-
fonn family of specifications. It covers at a high level the infra-
structure, processes, and systems required to manage a multi-
application card and its content.
--
6.4 G/oba/P/atform - 83
curity of any particular provider or application. Each Security
Domain implements the SecureChannel interface for its respec-
tive applications.
• Card Content - The applications, which are loaded onto the card
with an Executable Load File.
7.1
The History of the Open Card Framework
The history of the OpenCard Framework begins in 1997 with the The beginning
introduction of the Network Computer. Companies like Sun, Oracle,
and IBM worked on Network Computers to combine the advantages
of a desktop computer with the low administration and maintenance
cost of a terminal. The first Network Computers already contained
smart card readers, and since Java is the language of choice on Net-
work Computers, the idea of a Java framework for smart card access
was born.
Until recently, writing a smart card application was quite a diffi-
cult job mastered by a few specialists only. These specialists knew
the APDUs and the protocols needed to drive smart cards as speci-
fied by the respective smart card operation systems.
In 1997, the first meeting of what later became the OpenCard
Consortium was held. Computer manufacturers, solution providers,
card manufacturers, and card reading device manufacturers met to
work on a Java framework for smart card access. This framework
was named "OpenCard Framework" or "OCF" for short.
For the reference implementation of a framework, researchers and
developers from IBM took the lead in close cooperation with devel-
opers from Bull, Gemplus, Schlumberger, and Sun.
In September 1997, version 0.9 of OCF was published on the OCF 0.9
newly created OpenCard homepage [Link]
During the spring 1998 CardTechiSecurTech conference and OCF 1.0
trade show, OCF version 1.0 was released to the public. The six in-
dustry leaders Bull, Gemplus, IBM, Schlumberger, SCM Microsys-
terns, and Sun demonstrated the interoperability achieved by using
the OpenCard Framework: The same application was shown on dif-
ferent hardware platforms, with different operating systems access-
ing the data on a smart card using readers from different manufac-
7.2
The OpenCard Consortium
During the 1998 CardTechiSecurTech conference and trade show,
eleven of the companies supporting and working on the OpenCard
Framework came together at the Inaugural Meeting of the OpenCard
Consortium.
Figure 7.1:
The Members
of the OpenCard
Consortium
§~~--:
==-=.=
---- un
C
rei TOWITOKO
~~
tJi
"'. t ,
88 • 7 Introduction to OpenCard
••
The purpose of the consortium is to produce the OpenCard Purpose
Framework specification, to extend it, to foster its acceptance, and to of the
assist in its use. This is done to promote and accelerate smart card consortium
interoperability at the point of card use, and to simplify application
development [OCC99].
The founding members of the OpenCard Consortium are Bull, Founding
Dallas Semiconductor, Gemplus, IBM, Liberate Technologies (for- members
merly Network Computer Inc.), Schlumberger, SCM Microsystems,
Sun, UbiQ Inc., and Visa International.
In the fall of 1998, 3-G International and Siemens joined the con-
sortium. In spring of 1999 American Express and Toshiba also
joined the consortium.
The OpenCard Consortium has a management board and a tech- Organization
nical committee.
The management board is the main steering committee of the
consortium. It also elects the officers of the OpenCard Consortium:
the chair, the treasurer, and the secretary.
The technical committee is responsible for the evolution of the
OpenCard Framework.
7.3
The Objectives of the Open Card
Framework
When looking at smart card applications from the point-of-view of
application developers, at least three parties with a crucial role can
be identified:
• Card Terminal Vendors: The card terminal vendors provide the Card terminal
actual card readers (also called "card acceptance devices", or, in vendors
OCF parlance "card terminals"). Each vendor carries a more or
less broad spectrum of card terminals, ranging from the very
simple units to more sophisticated models (featuring perhaps
displays, Pin pads, or even biometrics input devices). Unfortu-
nately, card terminal vendors have not yet agreed on a common
standard interface. They still provide a number of APIs that are
not compatible.
• Card Operating System Providers: There are also numerous Card OS
competing companies offering various different card operating providers
systems and APIs. This results in a variety of commands and re-
sponse codes.
7.4
The Advantages of Using OCF
The architectural model of OCF makes a distinction between appli-
cation and service developers on one hand and card and terminal
providers on the other, offering significant advantages to all.
Benefits for Application- and service developers benefit from the OpenCard
application and Framework as follows:
service
developers • Vendor independence: Developers can choose cards and termi-
nals from different suppliers.
• Asset protection: Extensibility of the architecture enables devel-
opers to participate in future developments in smart card tech-
nology at low cost by migrating at the level of the API.
• Improved time-to-market: Developers profit from shorter devel-
opment cycles by programming against a high-level API.
• Lower development cost: Developers save the extra cost of
porting their applications to different platforms and benefit from
using the high-level API of OpenCard Framework instead of
dealing with low level programming.
7.5
The OCF Architecture
7.5.1
A Note on Notation
,,
~
• [Link]()
• r.... rold()
• tenlold( )
(from miooteS)
public c1a •• Anoth.r (
- privateAttribute : int public Strio;, pub11cAttribut.;
public .tatic String publicStaticAttribute;
protected String [Link]:lAttribute;
+ tolnt(s : String) : int
pr! vate int pr11" ...teAttribute;
7.5.2
Architecture Overview
Figure 7.4:
Involved
Parties
--
7.5 The OCF Architecture - 93
operating system on which the on-card application runs. The card
reader provider contributes the devices that interface directly with
the smart cards.
Figure 7.5 shows the high-level architecture of OCF and the party
that provides each component (horizontal layers).
The application provider develops the off-card application pro-
gram seen by the end user. This program uses the interfaces offered
by OCF and the CardServices that are plugged into the framework to
communicate with the on-card application. This ensures that differ-
ences or changes in the card operating system, in the card reader
software, or in the application management scheme used by the card
issuer do not impact the application code.
The card issuer is responsible for the application management layer.
This layer manages the coexistence of the various application func-
tions (assuming a multi-application smart card) and of the applica-
tion data on the same card. Application management schemes are
found in ISO 7816-4,5 and in EMV 2000 4.0.
Figure 7.5: .-
I Application
The OpenCard PrOVider
Framework
Architecture .--- ----tl·l;;.=:=4:::=~- 1 r=-~~
Il _____
Card
Issuer _
Card Service
[ ~~:ider Registry
1- ---.--l~=4F=~:::::::::~
Reader
; Device
i PrOVider
94 • 7 Introduction to OpenCard
•
•
as the card operating system provider can develop the on-card appli-
cation. Activating on-card executable code requires use of applica-
tion specific data packets, regardless of the application provider.
The OCF CardService encapsulates the card operating system CardService
and on-card application dependencies, shielding the application from
changes in those components.
A CardService that provides a standard way to access files on CardService
an ISO file system card is an example of a general-purpose compo- examples
nent. Internally, this component would use basic services provided
by the smart card vendor. A digital signature CardService is an-
other example of a general-purpose component. Both of these are
typical services that could be provided be the card vendor.
The application management components, discussed in the previ-
ous layer, also consist of CardService modules. Since the card is-
suer determines the application management scheme for a card, the
card issuer is the logical source for these components.
With programmable cards, the APDUs sent to the card are not
determined by the card operating system, but by the on-card appli-
cation. Here, a single CardService developed by the application
provider could be used regardless of the card provider. An example
of this is seen with the Java Card. The APDUs and data needed by
the application are determined by the card-resident applet.
Each card acceptance device, or card reader, has its own cornrnu- CardTerminal
nication protocol. The terminal layer encapsulates these device dif-
ferences. In this framework layer, the card reader provider can sup-
ply a CardTerminal implementation to drive his specific card
reader hardware.
We will now return to Figure 7.5 to address the OCF architecture
in more detail. The OpenCard Framework core covers the right side
of the figure. We will now discuss the core abstractions, the Card-
ServiceScheduler, Smart Card, CardID and the two registry
I
classes.
The class SmartCard is the central abstraction. A Smart Card SmartCard
object has a CardID that contains the information identifying the
card type. Contained in the CardID is the answer to reset (ATR)
response from the card. The Smart Card is the primary object used
by the application program. To obtain CardService modules for
the card, an application uses the SmartCard object to request them.
A CardService encapsulates the implementation details of the CardService
application or function it supports and of the card operating system
on which it can run. CardServices can draw on other Card-
Services. For example, a PurseCardService, which needs to
access card files, can use the FileSystemCardService available
for the card.
••
CardService- All knowledge about the availability of CardServices is encap-
Factory sulated in a CardServiceFactory for a family of services. The
use of such factories is a standard object-oriented design pattern.
The same developer usually provides the CardServiceFactory
and associated CardServices.
CardService The system-wide CardServiceRegistry keeps track of the in-
Registry stalled CardServiceFactory objects. When a CardService
with a particular interface is requested from OCF, the Card-
ServiceRegistry calls every registered CardServiceFactory
until an appropriate CardService has been created. The new
CardService object is connected to the SmartCard object with
which it will be used.
While we can have many CardService and CardService-
Factory objects in a system, there is always only a single Card-
ServiceRegistry.
The CardService calls any cryptographic functions needed to
access the card. Again, the CardService knows the most about the
security mechanisms and protocols needed for the specific card op-
erating system.
Card- A CardService object communicates with the smart card
Service- through the CardServiceScheduler, which is also a class pro-
Scheduler vided by the OpenCard Framework core. The CardServi-
ceScheduler synchronizes concurrent accesses to one card from
different applications. Consequently, there is exactly one Card-
ServiceScheduler object for every Smart Card.
CardTerminal The main abstraction in the terminal layer is the CardTerminal.
An OCF CardTerminal provides the interface for smart card
reader devices ranging from simple card readers with no intelligence
to highly sophisticated, programmable payment terminals with sev-
eral slots and user interface support. To support a hardware device, a
CardTerminal implementation must be provided.
A CardTerminal supports one or more slots. Each slot is des-
ignated by a slot number. This allows exact modeling of real card
terminals with more than one slot for card insertion. Such multi-slot
terminals are used in the health industry, for example, to allow a pa-
tient data card and the authorization card of the doctor to be inserted
at the same time.
CardTerminaJ As we have previously discussed, a CardServiceFactory cre-
Factory and ates a CardService. The CardServiceRegistry administers all
CardTerminal CardService and CardServiceFactory objects. Looking at
Registry the terminal layer, we find similar mechanisms: A CardTerminal
object is created by a CardTerminalFactory, and keeping track
of ail known CardTerminals is the responsibility of the CardTer-
minalRegistry.
96 • 7 Introduction to OpenCard
•
•
The application management layer consists of the CardService Application
and CardServiceFactory classes for application management. Management
An ApplicationManagementCardService can interpret the ap- CardServices
plication management scheme used by the card (typically controlled
by the card issuer). Using information from the card, the service can
list, select, install, and delete on-card applications.
Industry initiatives in specific business domains have agreed on
application management schemes (for example EMV'96). Until
these agreements are accepted across all domains, exchangeable ap-
plication management card service objects will protect the applica-
tion writers from differences and changes in the application man-
agement scheme.
OCF offers an optional separate component to encapsulate the file FileAccess- and
system of a smart card as specified in ISO 7816-4. Here we find a FileSystem-
CardFile abstraction with attributes like TRANSPARENT, CardServices
LINEAR_FIXED, LINEAR_VARIABLE and CYCLIC_FIXED along
with support classes such as CardFilePath, CardFileInput-
Stre~ CardFileOutputStre~ CardFileReader and
more.
OCF has its own event objects, the most important of which are Events
the CardTerminalEvents. A CardTerminal creates these events
on card insertion and removal. They are delivered to registered
CTListeners by the terminal via the CardTerminalRegistry.
Each CardTerminalEvent carries a reference to the terminal and
to the slot, which allows starting or closing down the communication
with the card inserted or removed respectively.
For diagnostic tracing, OCF defines the TracerEvent. Tracer ob-
jects create these events and TracerListener objects can register
to receive them for filtering and post-processing. Since
TracerListener objects can run in independent program threads,
they can do arbitrarily complex filtering and formatting without im-
pacting the threads being traced.
--
7.5 The OCF Architecture - 97
Figure 7.6: SmartCard
Ca-d Cha"lnel
CardChannel, om"""') om",,"')
.$ OCFisSl.,ted : bool.. n= [Link]
SlotChannel and . is_open: boolean = false
.$ ,efCount_ : inl= 0
- is.,jammed: boolean = false
Related Objects
+ getV@liionO
+ isOpenO
- mutexCardChannel + Sm.,tc .,dO
+ goiC .,dTe,min.{)
+ beginMute>«)
+ .etSllteO
0 ..1 + [Link]
+ goiState() 1 + end Mute>()
+ .endC [Link] UO + goiC .,dIDO
. 0:::<:
+ openO + goiC .,dServioe()
+ [Link] -free_channel
+ [Link].,<I:)
+ [Link] ~[Link] + [Link]
+ toSt'ingO 1 .."
+ .hutdo...nO
0 .." + .[Link]()
Ca-d Ser'Ji ceSchedul er
om .... "') + .... ~Fo'C.'dO
- s martcard_refs: : int = 0
·.Iot_ hannll - is_aliv'e : boole an = false
om", .. ··D
1
Sial Chan nel
/h:nnel
0 .. 1
~ om", ....
CoO'D • • "'
.• Iotc ounl : int= 0
•• IoID : inl
.• Iotc [Link]: boole.n = f.1s e
+ featu,e·O
+ getAdd,e·.O
+ [Link]
+ goiC .,dIDO
+ goiScheduleo()
+ [Link]
+ .etSohedule,O -terminal + golTl'peO
+ .endAPD UO
+ goiSlolsO
+ g015 10tN umbeo() 0 .." 1
+ isC .,dP,e.en1()
+ golC.,dTe,min·O
+ isSlotC [Link]
+ goiLockH .ndleO
+ resetO
+ openO
+ [Link]
+ isOpenO
+ [Link]
+ [Link]
+ [Link]
+ goiC .,dIDO
+ ,e.e1()
+ toSt'ingO
+ .endAPD UO
SmartCard and There are a number of objects governing the interaction between
CardChannel the terminal layer and the service layer. We want to take a closer
look at these (see Figure 7.6) because they are essential for the con-
trol of concurrent smart card access as it will occur in typical multi-
application card scenarios. This brief overview will give you an idea
of how the OCF layers interact without going into detail on the indi-
vidual classes - this will be saved for later sections.
CardTerminal Let's start from the slot in which the smart card is inserted. A
CardTerminal object can support one or more slots. Each slot rep-
resents one physical slot in the card reader. For every slot, there can
be at most one SlotChannel. The association between slot and
SlotChannel is set up when the SlotChannel is opened. The
CardServiceRegistry creates a CardServiceScheduler ob-
ject and opens the SlotChannel when the application requests a
CardService from the Smart Card object for the first time.
•••
98 7 Introduction to OpenCard
After a card has been inserted and OCF has prepared the commu- SlotChannel,
nication path, we have for that card exactly one SlotChannel and SmartCard
one CardServiceScheduler object. We have one or more
Smart Card objects (typically one for each thread desiring access)
and one or more CardChannel objects (one for each logical chan-
nel supported by the card).
Maybe you wonder why we need a CardChannel at all, and why CardChannel
there should be more than one CardChannel per SlotChannel?
The CardChannel represents the logical path to the card. ISO 7816
has a concept of logical channels to a card that allows up to four
separate communication sessions. With the CardChannel mecha-
nism, OCF is ready to support this ISO 7816 concept as soon as the
ftrst real smart card can support it.
Having whetted your appetite with a general overview of the
OpenCard Framework, we will move on to take an in-depth look at
the packages and classes making it up.
This chapter covers some support classes that are used throughout
the OpenCard Framework. These classes define constants and ex-
ceptions that provide a foundation for the rest of the OpenCard
classes. The utilities also provide service classes offering useful
functionality such as string handling and property loading. These
classes are used by the framework but are also available to the
OpenCard application programmer.
We will cover three packages: opencard. core, which contains OpenCard
constant and exception definitions, opencard. core. uti 1, which utilities
contains standard utility classes, and opencard. opt. util, which
contains optional utility classes.
8.1
The OpenCard Core Definitions
Figure 8.1 shows the classes contained in the opencard. core
package.
The class OpenCardConstants is an interface having no meth- Constants and
ods. It defines constants such as the names of the properties that are base
used for configuring the framework. exceptions
The OpenCardException class is the base for all checked
OpenCard exceptions. The base exceptions in the OpenCard service
and terminal sub-packages - CardServiceException and Card-
TerminalException - are derived from this base class.
The OpenCardRuntimeException is the base class for all un-
checked OpenCard exceptions. When a runtime exception is thrown
it indicates a possible programming error in the application.
--
8. 1 The OpenCard Core Definitions - 101
Figure 8.1:
The OpenCard II~I I SIring
1.... ,)
_Iong) I
+SOPENCARD_PROPERTY
Core Classes +$OPENCARO_PROPERTIES
+$OPENCARD_DOTPROPERTIES
+$DEFAULT_OPENCARD_LOADER_CLASSNAME
...................
OponCa'dException +$CARD_SERVlCE_REGISTRY_TAG
+$CARDJERMINAL_REGiSTRYJAG
+ OpenCardExc:eptlon() +WPID_ENCODING
+ OpenCardExc:eptlon("""""'II": Siring} +$CARD_SERVICE_URL
+$CARD_SERVICE_LiSTER_CLASS
+$CARD_SERVICE_CHECK
I RunllmaExcoptlon
--",no)
I +$CARD_SERVICE_CACHEPATH
+$CARD_SERVICE_CACHETIME
--.-
«Interface»
OpanCardCons_
OpanCardRuntimeException
+ OpanCardRunllmaExcoptlonO
+ OpanCardRunlimeEJo:apllcn(mog : SIring}
8.2
The Core Utility Classes
Core utilities The core utility classes are essential for tracing, accessing system re-
sources, and automatic configuration of the OpenCard Framework.
These classes, shown in Figure 8.2, are primarily contained in the
opencard. core. util package.
8.2.1
Hex String Processing
HexString The HexString class provides a number of static methods that ma-
nipulate hex-coded strings - i.e. strings encoded in such a way that
each string character represents one hex digit.
The dump (... ) methods convert binary data stored in a byte array
into a string format suitable for printing or display. This overloaded
method can convert either the entire byte array or only a sub-array
from binary to string format.
The hexi fy (... ) methods convert integers and short integers
from binary to string format.
«Interface»
OpenCardPropertyLoadingException
TraceLevels
(from [Link])
(from [Link]
+ OpenCardPropertyLoadingExceptionO
«Interface» Tracer
OpenCardConfigurationProvider (from [Link])
, (from [Link])
+ loadPropertiesO
The dump (... ) and hexify (... ) methods are frequently used
within toString (...) methods of OpenCard classes and when pre-
paring data for tracing.
The parseHexString (... ) method accepts a string of hex digits
as input and returns the corresponding byte array. Similarly, the
parseLittleEndianHexString (... ) method accepts a hex-coded
string as input and returns a byte array with the digit order reversed.
lfthe input string contains data in little-Endian (low-order digit first)
format, the output byte array will be a positive integer in big-Endian
format. This method is useful when preparing data for Biglnteger
computations.
8.2.2
The Configuration Provider
8.2.3
The Tracer
+ addTracerListenerO
\
+ removeTracerListener()
\
«Interface» TracerEvent
TracerListener
I(from opencan:[Link])
+ traceEvent(trEvent : TracerEvent) : void
[Link]
Using the Tracer Class
Each class instrumented for tracing must create a Tracer object.
The Tracer object can be created for each class instance, but it is
often more convenient and less costly in terms of performance to
create a static object that is used by all instances of the class.
The Tracer constructor requires the name of the class being
traced. The Tracer object uses this information at runtime to de-
termine whether trace information should be recorded, as we will see
below.
After a Tracer object has been constructed, the programmer can
call the trace methods from within the application methods.
The tracer provides a concept of trace level that can be used to Trace Level
categorize the trace information according to severity. The trace lev-
els were modeled on those defined for the Linux syslogO facility
(see [Link] They are defined in the Trace-
Levels interface of the core utility package.
The programmer specifies the trace level by calling the corre-
sponding method of the Tracer class. The following table shows the
severity level definitions along with the corresponding Tracer
method names.
Trace method There are two methods defined for each trace method name. Both
definitions methods require a parameter that specifies the name of method being
instrumented and a parameter that specifies the message to be in-
serted into the trace stream.
[Link]
Trace Output
Each time a trace method is called, the Tracer creates a data record
containing the information provided by the calling code. The record
includes the trace level, name of the method causing the trace, trace
message, the Throwable object causing the trace (optional) and
thread performing the trace.
TracerEvent, The Tracer posts this record as a TracerEvent to all registered
TracerListener TracerListener classes (see Figure 8.3). The TracerEvent
class from the opencard. core. event package provides acces-
sors for all of the trace record fields. The TracerListener, also
from opencard. core. event, is an interface containing one
method - traceEvent (... ). This method is called for each
TracerEvent that occurs.
[Link]
Activating Trace Output
The OpenCard. trace system property governs the behavior of the Trace system
Tracer. This property specifies a list of tokens specifying packages properties
or classes to be traced along with their associated trace level. The
trace level is separated from the class or package name by a colon.
The tokens containing name and trace level are separated from one
another by blanks. When the OpenCard. trace property is not set,
no tracing is performed.
The following property definition activates tracing for all classes
and packages contained in the opencard. core package and spe-
cifically sets a higher trace level for the CardTerminalRegistry
class.
8.2.4
System Access
! \
/[I.
NetscapeSystemAccess MicrosoftSystemAccess
(from [Link]) (from [Link])
8.3
The Optional Utility Classes
The opencard. opt. u til package contains six classes that pro- Optional
vide diverse functionality to the rest of the framework and to the ap- utilities
plication programmer. Since they are contained in the optional
branch of the OpenCard tree, they might not be present in OpenCard
implementations for small devices where space is at a premium.
The optional utility classes can be divided into three groups. The
PassThruCardService and corresponding factory provide a sim-
ple way for an application to send APDUs to any smart card. The
Tag and TLV classes aid in parsing tag length value structures. Fi-
nally, the loader classes URLClassLoader and OpenCardProp-
ertyFileLoader can load class files through the Internet and con-
figuration data from a file, respectively.
1. [[Link]]/lib/[Link]
2. [[Link]]/.[Link]
3. [[Link]]/[Link]
4. [[Link]]/.[Link]
The java. home, user. home, and user. dir directories are
read from the system properties when composing the fully qualified
pathnames for the property files.
If properties being added conflict with the properties read from a
previous file, the properties from the subsequent file take prece-
dence. This allows a general set of properties to be placed in a cen-
tral location such as java. home above. More specific properties
could be placed in a location such as user. dir above to customize
OpenCard behavior for a particular use.
The property file must be in a format that can be read by the
java . lang . Properties . load () method. Each line in the file
contains a property key and its value. Key and value are separated
by an '=' sign. Lines beginning with a pound sign '#' are treated as
comments and ignored.
Table 8.2 shows the properties affecting the Framework classes.
Naturally, specific CardTerminal and CardService components
can define additional properties.
8.3.2
The PassThruCardService
8.3.3
The Tag and TLV Classes
The ISO 8825 standard defines rules for encoding information in a Tags and TL V
Tag Length Value (TLV) structure, where each data unit consists of structures
a tag defining the type of data, the length of the data, and the value,
or the actual data itself. These encoding rules are frequently used in
the world of smart cards.
The variable-length tag consists ofthree fields. The tag class field Tag field
is two bits long and specifies whether the tag is of the Universal,
Application, Context-Specific, or Private class. The constructed bit
indicates whether the tag is a primitive or is composed of further
TLV structures. The tag code field has a variable length and identi-
fies the data contained in the value field.
••
Figure 8.7: TLV
.... [Link]",}
TagandTLV Tag oTLVO
from [Link] o TLV(binary : byte{J)
Classes oTagl) o TLV(tag : Tag, value: byleD)
o Tag(t : Tag) o TLV(tag : Tag, number: in!)
o Tag(tag : int, tagClass : byte. constructed: boolean) o TLV(tag : Tag, Uv : TLV)
+ Tag(binary: byteD, offset : intO) o add(tlv: TLY): TLV
+ Tag(binary : byteO) + findTag(tag : Tag, cursor: TLY) : TLV
+ size() : inl + fromBinary(binary, offset, Uv, parent)
+ fromSinary(binary : byteD, offset : intO) : void ,tag • opname(argname) : return
+ get8ytesO : byteD + IenBytes(length : inl) : inl
+ toBinary(b"ary : byte{J, offset : intO) : void + Iength() : int
+ set(tag : int, tagclass byte, constructed) : yoid + IengthToBinary(length: ..I): byteD
+ setConstructed(constructed : boolean) : void + setValue(newValue : byteO) : void
• codaO: int • tagO: Tag
+ isConstructedO : boolean + tDBinaryO : byte{J
+ hashCode() : inl + tDBinaryContent() : byieD
+ equals(o : Object) : boolean + toStringl) : String
+ toStringO : String • toString(ht : Hashtable, level : in!) : String
• valueAsByteArray{) : byteD
• valueAsNumbelt) : inl
1 In the literature, many terms are used to designate devices that interface with
smart cards. Common terms are card acceptance device, card terminal, and card
reader. In this chapter, we will use the term card reader for such devices.
Optional
Components
«[Link]» «Interface»
PowerManage<MnUnterf.c:e r erm lnalCommond
~(""'---~------------~I""'~
9.1
Terminal Layer Core Components
Terminal layer This section describes the core terminal layer components. These
core are contained in the opencard. core. terminal and open-
components card. core. event packages and make up the basis for Card-
Terminal programming.
We will organize the core components into groups to aid discus-
sion. The first group is oriented around the terminal registry and
event mechanism. We will then cover the device abstractions, the
data transport classes, and the terminal layer exceptions. Finally we
discuss the PIN and password support.
•••
116 9 The Terminal Layer
9.1.1
Terminal Registry and Event Mechanism
CardTerminalRegistry \ EventGenerator
from [Link] \ from [Link]
- CardTerminalRegistryO - EventGeneratorO
+ getRegistryO : CardTerminalRegistry \ +getGeneratorO : EventGenerator
+ add(terminal : CardTerminal) : void +addCTListener(ctl : CTListener) : void
+ addPoliable(p : Pollable): void +createEventsForPresentCards( ... ) : void
+ countCardTerminalsO : int +getPolllntervalO : int
+ getCardTerminalsO : Enumeration +updateCards(term,slot,inserted) : void
+ remove(terminal : CardTerminal) : boolean +removeCTListener(cti : CTListener): void
+ runO: void +runO: void
+ removePoliable(p : Pollable) : boolean + updateTerminals( p : Pollable,
+ setPolllnterval(duration : int) : void term_add: boolean): boolean
+ ... and others ... 0
T -$reglstry T -$theGenerator
Event •• I~)
po l~)
ulfdlnurtedO
.. ,~)
urdln •• rted(C.,c
...; ::::::::
'·' ~I
..""
9.1.2
Device Abstractions
«Inlerface»
CardTerminalFaclory
(from [Link])
+ crealeCardTerminals(clr, lerminalinfO)
+ open() : void
+ close() : void
A physical card reader can have one or more slots. Each physical
slot can accept one smart card. An OCF CardTerminal implemen-
tation can support one or more slots. The application can obtain the
number of supported slots from the CardTerminal, which is useful
when testing for card presence at a particular location.
When a smart card is inserted into a slot, the CardTerminal CardlD
automatically powers up the card and retrieves its CardID (the
OpenCard packaging for the ATR). The application can obtain the
CardID from the CardTerminal for a specified slot. Before calling
this method the caller should make sure that a card is present, other-
wise null may be returned.
The CardTerminal openSlotChannel (... ) method creates a SlotChannel
unique SlotChannel object for communication with an inserted
smart card. The CardTerminal makes sure that there is exactly one
SlotChannel for each card. Once one thread has obtained a
SlotChannel, no other thread can obtain a SlotChannel for the
[Link]
Data Transport Classes
CardlD As mentioned previously, the CardID class provides packaging for
methods the A TR response from the card. Methods allow either the entire
ATR or only the historical bytes to be extracted as a byte array. The
ability to extract only the historical bytes is useful since determining
the start of the historical bytes in the ATR requires considerable bit
level work. Also, a comparison method is provided that allows two
ATR responses to be compared with one another and a method is
provided that returns a reference to the slot containing the smart card.
The APDU classes package the data passed to and from the card.
The APDU base class provides a reusable buffer that can be initialized
with a byte array of fixed length. APDU class methods allow data to
be added to the buffer and allow the length of data within the buffer
to be set.
APDU ResponseAPDU
lfrom [Link])
I(from [Link])
+ APDU(buffer : byte[]) + ResponseAPDU(apdu : byte[])
+ APDU(buffer : byte[], length: int)
+ APDU(size : int)
...
A + ResponseAPDU(size : int)
+ dataO : byte[]
+ append(bytes : byte[]) : void + swO: int
+ append(b : byte) : void + sw10: byte
+ getBufferO : byte[] + sw20: byte
+ getByte(index : int) : int
+ getBytesO : byte[]
+ getLengthO : int
P--- CommandAPDU
from [Link]
+ setByte(index : int, value: int) : void + CommandAPDU(buffer : byteO)
+ setLength(length : int) : void + CommandAPDU(buffer : byte[], length: int)
+ toStringO : String + CommandAPDU(size : int)
9.1.3
The Terminal Layer Exceptions
Let's have a look at the terminal layer exception structure. The base
class, CardTerminalException, extends the OCF base exception
class, opencard. core. OpenCardException. The remaining ter-
minallayer exceptions extend CardTerminalException.
--
9.1 Terminal Layer Core Components - 121
Figure 9.6:
CardTerminal
OpenCardExcepllon II CardTerminal
InvalidSlolChannelExceplion
from [Link])
+ InvalidSlotChannelExceptionO
~.-.\ T~ ~
+ InvalidSlotChannelExcepUon(msg : String)
Exceptions + InvalidSlotChanneIException(msg, terminal)
TerminalLockedException
from 0 [Link])
+ TenninalLockedException{msg : String)
+ TenninaILockedException(msg, terminal)
CardTerminalExceplion /
TerminallnitException
from [Link] terminal
(from [Link])
+ CardTenninalExceptionO + TennlnallnitException(msg : String)
+ CardTermlnalExceptlon(s : String) ~ + TermlnallnltException(ms9, terminal)
F------
+ CardTerminalException(msg : String, terminal)
+ CardTermlnaIExceptlon(msg, terminal, slot)
+ getCardTerminalO : CardTerminal TerminalTimeoulExceplion
+ getSlotO : int tfrom o~~[Link])
I
CardNotPresentException
from [Link]
A·'----"~
+ getTimoutvalueO : Int
CommunicationErrorException
(from opencard core terminal
+ CommunicationErrorExceptlon{)
+ CardNotPresentExceptlon(msg, terminal, slot) + CommunicationErrorExceptlon(msg : String)
+ CommunicationErrorExceptlon(msg. terminal)
+ CommunlcationErrorException{msg, terminal,
slot)
1
CardTenninallOControl
CHVControl
from tannln,l)
from tannlnall
+ CHVControl( ... )
+ CardTermlnaIiOControl(blender: CardTermlnaliOBlender)
+ prompt() : String
+ blender() : CardTermlnaliOBlender
+ InputSet() : String IE- + applicatlonlD() : String
+ chvNumber() : Int
+ termlnatorSet() : String
+ passwordEncodlng() : String
+ maxlnputChars() : Int
+ passwordOlfset() : Int
+ timeout() : Int
+ loControl() : CardTerminaliOControl
«Interface»
Verifl8dAPDUlnterface
I(1fomtannlnol)
+ sendVerifiedCommandAPDU(slotChannel, commandAPDU, chvControl) : ResponseAPDU
Looking at the OpenCard Framework globally, we see that the PIN support
CardService layer is responsible for generating the APDUs that are rationale
sent to the card. When card holder verification (CRV) is required, the
PIN or password must be added to the APDU.
The OpenCard Framework is designed to support a wide range of
card acceptance devices. Some of these devices provide only a slot
into which a smart card can be inserted, while others provide ex-
tended functionality.
The most common form of extended functionality consists of a Card reader with
simple display with PIN pad. When a device of this type is used, the PIN pad
intention is to use the display to prompt and the PIN pad to obtain the
PIN from the user. Among devices with a PIN pad and display, there
are considerable differences in how they must be programmed.
Some devices merely allow keystrokes to be retrieved and messages
to be displayed. For these devices, code on the host side must obtain
the PIN keystroke by keystroke and insert the resulting PIN into the
APDU. Other devices are capable of processing a partial APDU re-
ceived from the host. The device can independently obtain the PIN
from the user, insert it at the proper location in the APDU, and pass
the completed APDU to the smart card.
--
9.1 Terminal Layer Core Components - 123
The PIN I Password Support interfaces and classes allow the
CardTerminal programmer to develop support for this type of func-
tionality. These classes are shown in Figure 9.7. We should note that
the classes and interfaces described in this section are only needed to
support a card acceptance device that has PIN pad and display func-
tionality.
9.2
Terminal Layer Optional Components
The optional components relating to the terminal layer are con-
tained in two packages. The opencard. opt. terminal package
contains direct extensions to the core package, while the open-
card. opt. terminal. protocol package contains specialized
classes used for handling the protocol between the host and the
card reader.
I CommandAPDU ,
(from [Link])
I <<Interface»
TerminalCommand
Figure 9.B:
Terminal Layer
I(from _rd.oottermlnal)
~ + sendTerminalCommand(cmd : byte[)) : byteO Optional
Components
«Interface»
ISOCommandAPDU
PowerManagementlnterface
I(from [Link]) from ooencard._termlnal)
+ ISOCommandAPDU - several constructors -(..
+ powerUpCard(slotlD : int, timeout: int) : void
+ getCLAO : byte
+ powerDownCard(slotlD : int, timeout: int) : void
+ geUNSO : byte
+ getP1 () : byte
+ getP2() : byte «Interface»
+ getLCO : int Usertnteraction
from ,,-cord._termlnal)
+ getLEO : int
+ getlsoCaseO : int + display(message : String) : void
+ append(bytes : byteD) void + clearDisplayO : void
+ append(b : byte) : void + keyboardlnput(ioControl) : String
+ toSllingO : String + promptUser(prompt, ioControl) : String
--
9.2 Terminal Layer Optional Components - 125
These components may be useful in special cases, but the pro-
grammer should be aware that the optional components might not be
available in all OpenCard implementations.
When OpenCard is installed on a device with limited resources
such as a Personal Digital Assistant (PDA) device or hand-held
phone, the optional components may not be available. This will usu-
ally be of no consequence for the CardTerminal writer, since such
devices will generally not support the use of arbitrary card readers.
9.2.1
The [Link] Package
Terminal layer The opencard. opt. terminal package contains classes that di-
optional rectly extend the functionality of the terminal layer core components.
components Figure 9.8 shows the optional OpenCard terminal layer components.
The optional components provide two new classes and four new in-
terfaces to the CardTerminal programmer.
ISO command The ISOCommandAPDU class adds extended support for APDUs
support that conform to the ISO 7816 standard. Constants describe the seven
APDU cases defined by the standard. Additional methods are pro-
vided that can be used to extract the APDU case according to the
7816 standard, the class byte, the instruction byte, the parameter
bytes PI and P2, and the expected response length.
Power The PowerManagementlnterface provides functions to ex-
management plicitly power-up and power-down an inserted smart card. When a
card is inserted into a slot, the CardTerminal must always automati-
cally power it up. The methods provided by the PowerManage-
mentInterface can be used in addition to the automatic card
power-up function.
Terminal The TerminalCommand interface provides a type of 'transparent'
command interface to the card acceptance device. An arbitrary device command
contained in a byte array is transmitted to the card acceptance device.
The response returned is passed back to the application.
User interaction The Userlnteraction interface adds methods for directly ac-
cessing display and PIN pad capability of the card acceptance device.
These methods allow text display and allow the application to di-
rectly obtain input from the keyboard. Another method, promp-
tUser (... ) , displays a text string and returns keyboard input with one
simple call.
Terminal locking In addition to the above interfaces, OCF 1.2 introduced the feature
of locking either entire CardTerminal objects or individual slots
within a terminal. This feature is introduced in the Lockable inter-
face without breaking any existing code.
T1Block
from tllnnlnal. toea
+ TfBIock(•••)
+ CIIIcEDCO: Int
+ getBlock() : byta()
+ getBIockTypa() : Int
+ geISourcelll() : int
+ getPCB{) : byte
+ getControlBIts() : Int
+ geISou"'-ess() : Int
+ ge!RequestadSequenceNumberll : Int
+ ••• """ many [Link]
-. -
....Iock
TfProtocol
+ TfP'_lhoatAdd., _.,tlmeout)
+ open() : void
+ cIooIe() : void
+ getBIockWallingTIma() : Int
+ atSendSeq...,.,countar(vod : Int) : void
+ 881RecM1equenceCountllrlval : Int) : void
+ _mill_Data: bytaD) : byteQ
T1 Protocol class The TIProtocol abstract class handles the actual communication
with the card. The single abstract method, exchangeDa ta () , sends
a block of data to the card and receives a block from the card. Since
exchanging data with the card is dependent on the underlying com-
munication mechanism used, this method must be implemented
--
9.2 Terminal Layer Optional Components - 129
9.3
Tracing in the Terminal Layer
The OpenCard terminal layer classes are instrumented with trace
calls. Typically, each method will issue a debug level trace on en-
trance or when something interesting, such as card insertion or re-
moval, happens.
Terminal layer The terminal layer classes will issue critical level traces when run-
traces time exceptions occur.
Tracing can be activated either for a single class or for an entire
package. This is done by setting the OpenCard. trace system pro-
pertyaccordingly.
To activate debug tracing for the CardTerminal class, set the
OpenCard. trace property as follows:
[Link] = [Link]
9.4
Communicating with the Card Reader
The CardTerminal implementation acts as a device driver for the
card reader, so communicating with the physical device is one of its
essential functions. There are two basic possibilities for communica-
tion with the device.
At this point, you might be asking yourself about the PC/SC inter- OCF PC/SC
face. The Personal Computer / Smart Card interface was developed support
by an industry consortium to provide smart card access primarily for
the Windows platform.
The OpenCard Framework reference implementation provides
PC/SC CardTerminal drivers. When running on a Windows plat-
form, all installed PC/SC card acceptance devices can be accessed
through OpenCard if the OpenCard PC/SC CardTerminal is con-
figured.
9.4.1
The Java Communications API
9.5
The Implementation
Figure 9. 10:
CardTerminal T1 Protocol CardTerminalFactory
CardTerminal
(from terminal) (from protocol) (from terminal)
Implementation ~------~------~
Pollable
(from terminal)
-protocol / /
GCR410CardTerminai GemPlusCardTerminalFactory
(from gemplus) (from gemplus)
9.5.1
USing the T=1 Protocol Support
try {
II send block to reader
[Link]([Link]()) ;
return receiveBlock;
II exchangeData
Figure 9. 11:
I CardTerminal I
I I CardTerminal
Pollable
I (from [Link]) I(from [Link])
Implementation
~ I Methods
I
GCR410CardTerminai
(from [Link])
# GCR410CardTerminal(name: String, type String, serial Device String)
+ openO : void
+ closeO : void
+ isCardPresent(slotiD : int) : boolean
+ getCardlD(slotiD : int) : CardlD
+ toStringO : String
+ poliO: void
# internalFeatures(features : Properties) : Properties
# internalReset(slotiD : int, ms : int) : CardlD
# internalSendAPDU(slotlD : int, capdu : CommandAPDU, ms int): ResponseAPDU
# getFirmwareVersionO : String
- powerUpCard(slotlD : int) : byte(j
- powerUpCard(slotlD : int, timeout: int) byte(j
• powerDownCard(slotlD : int): void
- UpdateCardStatus(slotlD : int): void
- getCardStatus(slotiD : int) : int
- getUsedCardProtocol(slotiD : int) : int
[Link]
Initialization and Termination
To start off, the new CardTerminal class must be declared. This
provides the abstract method definitions we must implement.
The final major task for the open () method is adding the Card-
Terminal object to the CardTerminalRegistry polling list. After
this is done, the poll () method will be called periodically by the
CardTerminalRegistry polling thread.
[Link]
Some Private Helper Methods
This section describes a few helper methods contained in our exam-
ple implementation (See Figure 9.10 above). These methods are not
required by the CardTerminal base class or the Pollable inter-
face, but they provide frequently required functionality.
The UpdateCardStatus 0 method sends a command to the Checking card
GCR 410 that returns information about the inserted card. Depending status
on the input parameter, this function is used in two ways. If the input
parameter is 0, UpdateCardSta tus () checks if a card is inserted in
the slot. If it is 1, the method will obtain information about the in-
serted card - most importantly, it will retrieve the communication
protocol (T=O or T=1) being used between the GCR 410 and the in-
serted card.
The getCardStatus 0 method merely retrieves the status in-
formation collected by the UpdateCardSta tus () method.
The getUsedCardProtocol () method evaluates the card status
information and returns a 1 if the protocol between card reader and
card is T=1 and returns 0 if the protocol is T=O.
The powerUpCard () method sends a command to the GCR 410 Power-up card
to power up the card. It uses the T=1 protocol support set up by the
open () method to communicate with the device:
Send power-up
byte[] sendData = new byte[] { (byte)Ox6E, (byte)OxOO, command
(byte) OxOO, (byte) OxOO};
try
rcvData=[Link](HOST_ID,TERMINAL_ID,sendData) ;
catch (TlException tle) {
throw new CardTerminalException([Link]());
UpdateCardStatus(slotID); GettingATR
tmpATR[lenATR++]=rcvData[4]; II TS 3B=direct, 3F indirect
tmpATR[lenATR++]=rcvData[5]; II TO
return ATR;
II powerUpCard
[Link]
First Contact with the Card
Now that we have covered the helper methods, we can turn to de-
tecting a card insertion or removal.
Detecting card The isCardPresent () method returns true if a card is present
insertion and returns false otherwise. It checks for card presence by exam-
ining the status byte retrieved by the GetCardStatus () methods:
PoliO method You will remember that the poll () method is called periodically.
The poll () method must check if a card is present and generate the
card insertion and removal events as appropriate. The method must
else {
if (!isCardPresent(O))
cardInserted = false;
cachedATR = null;
cardRemoved(O) ;
The internalReset () method also makes contact with the card. Reset the card
This method sends a command to the card acceptance device causing
it to perform a warm reset on the card in the specified slot.
[Link]
Data Exchange
The final set of methods to be implemented get data from or ex-
change data with the card.
The getCardID () method retrieves the ATR for an inserted card. Get Card ID
First, the method verifies that a card is present. If no card is present,
the cached ATR string is set to null, and null is returned to the
caller.
When the method is called for the first time, the example imple-
mentation powers up the card and receives the ATR. The ATR string
is cached, as discussed previously.
When called subsequently, the method simply returns the ATR
string packaged in a CardID object.
--
9.S The Implementation - 141
II check if card is powered (==> cachedATR 1= null)
if (cachedATR == null) (
cardID new CardID(getSlot(slotID),
powerUpCard(slotID)) ;
else (
cardID new CardID(getSlot(slotID), cachedATR);
else
II no card inserted - invalidate cached ATR
cachedATR = null;
return cardID;
II getCardID
if (tmpReceiveBuf == null)
throw new CardTerminalException("no response from reader");
if (receiveBuf !; null)
if ([Link] > 0)
rAPDU ; new ResponseAPDU(receiveBuf) ;
else
throw new CardTerminaIException("no response from
smartcard ") ;
9.5.3
Implementing the CardTerminalFactory
Figure 9.12:
CardTerminalFactory
Implementation
GemPlusCardTerminalFactory
(from [Link])
+ createCardTerminals(ctr : CardTerminalRegistry, terminallnfo : String[]) : void
+ openO : void
+ closeO : void
--
9.5 The Implementation - 143
Open, close In our example implementation, the open () and close () meth-
ods are not needed, so they are implemented as empty functions.
The createCardTerminals () method parses the initialization
strings to make sure that the proper number of parameters has been
passed. The example factory implementation requires three parame-
ters - name, device type, and communications port. The method
checks the device type parameter to make sure that a GCR410 Card-
Terminal has been requested. After the parameters have been
checked, the method creates an instance of the CardTerminal and
registers it with the CardTerminalRegistry.
II is it a GCR410?
i f (terminalInfo [1] . equals ("GCR410"))
Figure 10. 1:
Application
OCFService
Layer Structure
CardService Implementation
The OpenCard Framework provides the tools needed for card ac- Defining
cess. These tools are divided into core and optional components. The CardService
CardService implementation uses these components to offer a interfaces
high-level interface to the application. The application uses the
CardService implementation as well as the OCF components to
communicate with the smart card.
The CardService implementation provides a high-level interface
to the application. It takes care of all APDU-Ievel details when com-
municating with the card to implement the functionality defined by
the interface.
Standard interfaces are available (see section 10.3, "Standard
Standard
CardService Interfaces"); however, the application programmer is
interface
free to write his own CardService to encapsulate smart card spe-
cific details. This can be useful if the application is to support multi-
ple smart cards of different types.
Class Diagram
«Inlerface»
PrimaryCardServiceFaclory
(from [Link])
«Inlerface»
CardServicelnlerface CardServiceExceplion
(from [Link]) (from [Link])
CardServiceRunlimeExceplion
(from [Link])
10.1
The CardService Layer Core Components
The core components form the basis of the CardService layer. We
must understand these components well in order to write our own
CardService or to write applications that use a CardService.
These components can be divided into five groups as shown in Fig-
ure 10.3.
Figure 10.3:
Application Access C8rdService Support CardService
PrlmaryCardServlceFacIory
SmartCard
cardRequesl cardServlce Layer Core
cardServiceFactory
CardlOFilter
cardType Components
C8rdAccess
cardChannei
Exceptions
CardServiceExeeption
CardServlcelmpiementaUonException
CHVSupport
CardServk:elnabilltyExcepllon
CHVDlaIog
CardServicelnvaiidCr_i~
CardHoiderVerlflcationGUI
CardServk:elnvaiidParameterExcepllon
DelaullCHVDlalog
CardServiceOper_nFailedExceplion
DelaullCHVDlalogResourceBundle
CardServlceRuntimeException
CardServlceUsageException
InvalidCardChannelException
The application can use the Application Access classes to wait for Service layer
card insertion and obtain a particular CardService for the inserted classes
card.
The Card Access classes provide the base functionality for syn-
chronizing access to the card. They are used by a CardService im-
plementation or by other framework classes.
--
10.1 The CardService Layer Core Components - 147
The CardService Module Support classes form the foundation
used to create new CardService modules. These skeleton classes
analyze the card type when a new card is inserted and handle any
special initialization needed by the card.
The application can use the CHV Support classes to customize
the dialog that obtains the CHV from the user.
Finally, the core components include Exceptions that are thrown
when error conditions arise.
10.1.1
The Application Access Classes
SmartCard class The classes making up this group are shown in Figure 10.4. An ap-
plication generally uses the SmartCard class first when using the
OpenCard Framework. We will first cover the SmartCard class
static methods for framework initialization and shutdown, then the
instance methods that are used when a SmartCard object has been
obtained for an inserted smart card, and finally the ways to obtain a
Smart Card object.
Figure 10.4:
«Interface» Card Request
The Application CardlDFilter (from [Link])
+ isCandidate(CardID): boolean
+ Card Request(behavlor ,term inal,class)
+ getFilterO: CardlDFilter
'------------' ~ + getCardServiceClassO: Class
+ getCardTerminalO: CardYerminal
+ getTimeoutO : int
SmartCard • getWaitBehavlor() : int
(from [Link]) + isTimeoutSetO : boolean
+ SmartCard(CardServiceScheduler, CardlO) + seIFilter(filter: CardlDFilter) : void
+ beginM ul.x() : void + setTimeout(timeout: int) : void
+ claseO : void + toStringO : String
+ endM utexO : void
+ getCardlDO : CardlO
+ getCardService(Class, boolean) : CardService
+ getSmartCard(ctEvent, Card Request) : SmartCard
+ getSmartCard(ctEvent, Card Request, lock) : SmartCard
+ isStartedO : boolean
+ shutdownO : void
+ startn : void
+ waitForCard(req : Card Request) : SmartCard
StartO The two static methods, start () and shutdown () are provided
for bringing up and terminating the framework, respectively. When
start () is called, it flrst examines the system properties to deter-
mine how the framework configuration will be performed.
Configuration The OpenCard .1oaderClassName property specifies the name
loading of a class that implements the OpenCardConfigurationProvider
interface, described in Section 8.2.2, "The Conflguration Provider".
If this property is not present, then the default configuration provider,
••
Access The application uses the getCardService (... ) method to re-
CardService trieve a reference to the CardService that implements the desired
interface.
In the following example, the application wants to prepare a digi-
tal signature using the inserted card. This is done using methods from
the SignatureCardService, which is an interface defined in the
opencard. opt. signa ture package. The application calls get-
CardService (. .. ) to gain access:
This code will wait for any type of card to be inserted into any
reader. It will also detect cards already present. If no card is inserted
after a certain timeout period, wai tForCard (... ) will return a null
reference.
10.1.2
The Card Access Classes
The card access classes shown in Figure 10.5 are primarily of interest
to CardService programmers. The CardServiceRegistry keeps
track of the installed CardServiceFactory objects. It is responsi-
ble for using the factories to create CardService instances. The
CardService instances use the CardServiceScheduler and
CardChannel objects to access the card.
Since the CardServiceRegistry is the central repository for in-
formation about available CardServices, it is important that only
one such object exists in the system. The CardServiceRegistry
uses the singleton design pattern to implement this. Framework ob-
jects can obtain a reference to the single CardServiceRegistry
object by using the getRegistry () method.
Public Card- You will recall that the Smart Card • start () method configures
ServiceRegistry the CardServiceRegistry by instantiating CardServiceFac-
methods tory objects and adding them to the registry list. This is done by us-
ing the registry'S add (... ) method. CardServiceFactory objects
can be deleted from the registry using the remove t .. ) method. The
application can get an enumeration of installed CardServiceFac-
tory objects by calling the getCardServiceFactories ()
method.
i
These are actually the only available public methods. Generally
these methods are not used by the application, since the configuration
of the CardServiceRegistry is done via system properties. How-
ever, if necessary, the application can use these methods to update the
configuration. When an applet is downloaded by a web browser, for
example, registration of any factories downloaded with the applet
could be done directly.
Other framework classes, primarily the Smart Card class, call Protected
protected CardServiceRegistry methods to get SmartCard and registry
CardService objects. The OpenCard Framework was structured in methods
this manner to reduce complexity for the application programmer.
The Smart Card class is a front-end that makes functionality from a
number of OCF classes available to the application programmer.
When a smart card is inserted, OCF uses the protected Card-
ServiceRegistry getSmartCard (... ) method internally to in-
stantiate a Smart Card object. This method sets up the communica-
tion stack and ties the new Smart Card object to the CardServi-
ceScheduler for the inserted card.
The CardServiceRegistry maintains a list of all configured
CardServiceFactory objects. The SmartCard object calls the
registry's getCardServicelnstance (... ) method specifying the
required CardService class. The CardServiceRegistry at-
tempts to create the required CardService instance from each
CardServiceFactory in tum. When the appropriate factory is
found, the CardService is instantiated and returned to the Smart-
Card object.
--
10. 1 The CardService Layer Core Components - 153
Figure 10.6: cardChannel
Channel and frcm [Link])
t
cardServiceScheduler
I (frcm [Link])
+ cardServiceScheduler(slotchannel : SlotChannel)
+ getSlotChannelO : SlotChannel
+ aliocateGardChannel(applicant : Object, block: boolean) : cardChannel
+ releaseGardChannel(channel: cardChannel): void
+ reset(ch : cardChannel, block: boolean) : cardlD
+ cardlnserted(ctEvent : cardTenninalEvent) : void
+ cardRernoved(ctEvent : cardTenninalEvent) : void
+ toStringO : String
+ ... and rnore{)
10.1.3
The CardService Support Classes
[Link]
The CardService
So far, we have dealt with the CardService as though it were a
single entity. Now we need to distinguish between the CardSer-
vice base class, which is provided as part of the opencard.
core. service package, and the CardService subclass that
provides the desired functionality. We will use the terms Card
Service base class to refer to the base class and Card
Service module, or simply CardService, to refer to the
CardService subclass.
CardService As we stated at the beginning of this section, a CardService
reuse provides a high-level interface to the application. In addition, the
CardService layer is designed to allow a CardService to build
upon the functionality provided by other CardService modules.
For example, a CardService for digital signatures might use a file
system CardService to select the key file directory. This aids code
reuse and allows logical structuring of the CardService modules
written for a particular card.
cardServiceFactory
+ cardServiceFactory()
fI getcardServicelnstance(Class, c:ardType, scheduler, smartcard, block) : CardService
fI getClassFor(clazz : Class, type : cardType) : Class
fI newcardServicelnstance(class, cardType, scheduler, smartcard, blocking) : CardService
fI getcardType(c:id : CardlD, scheduler: cardServiceSc:heduler) : cardType
fI getClasses(type : cardType) : Enumeration
Every CardService module must extend the abstract Card- Extending the
Service base class. This class provides methods for use by the ap- base class
plication as well as methods to be used by the CardService mod-
ule. We will begin by discussing the methods intended for use by the
CardService implementation.
As discussed in the preceding section, the CardService allocates
a CardChannel to communicate with the smart card. This allows the
CardService module exclusive access to the card.
When one CardService module calls another, how does the Sharing the
called CardService module obtain a CardChannel? The Card- CardChannel
Service base class achieves this by providing its own methods for
CardChannel handling. In particular, the setCardChannel (...)
method allows an already allocated CardChannel object to be
passed in from an external source. This is a public method, so it could
theoretically be used by the application, but it is actually meant for
use by other CardService modules.
The protected allocateCardChannel () method is used by the CardService
CardService module itself. It makes sure that a CardChannel is methods
available for communication with the card. If a CardChannel has
been provided via setCardChannel (... ) , then allocateCard-
Channel (...) does nothing. Otherwise, it uses the CardServi-
ceScheduler to allocate a new CardChannel object.
After the CardService implementation has called allocate-
CardChannel (), it uses the getCardChannel () method to re-
trieve the CardChannel object.
Allocate a try (
CardChannel allocateCardChannel () ;
response = getCardChannel() .sendCommandAPDU(command);
finally (
releaseCardChannel() ;
The CardService module does not concern itself with the source
of the CardChannel - this is taken care of by the CardService
base class.
Instantiate a CardService modules are instantiated by the CardService-
CardService Factory (which we shall cover shortly) in a two-step process. First
an instance is created using the standard constructor and then the
module is initialized. This two-step process allows CardService
modules to be constructed without use of the Java Reflection API,
which might not be available on embedded systems.
When requested to create a new instance of a CardService
module, the CardServiceFactory will first choose the appropriate
CardService module class from its list of available classes. The
CardServiceFactory will then use the newlnstance () method
of the standard Java class Class to create a new object instance. The
execution of this method causes the default constructor of the Card-
Service module to be called. For this reason, every CardService
module must provide a default constructor that, as a minimum, sim-
ply calls super ( ) .
CardService After it has created a new instance, the CardServiceFactory
initialization will call the CardService module's initialize (... ) method,
passing it three parameters - the associated CardServiceSched-
uler and Smart Card objects, and a blocking flag indicating
whether the application wishes to wait for a CardChannel if one is
not immediately available.
The CardService base class handles the blocking flag and pro-
vides a method for getting the associated Smart Card object. How-
ever, no method is provided for obtaining the CardServiceSched-
uler object. Sometimes the CardService module will need to ac-
cess the scheduler - for example, when customized CardChannel
objects are used. In this case, the CardService module must im-
[Link]
The CardServiceFactory
As explained previously, the CardServiceRegistry holds refer-
ences to all configured CardServiceFactory objects in the sys-
tem. When creating a new CardService module instance, the
CardServiceRegistry goes through its CardServiceFactory
list attempting to create the instance until it is successful.
We will now focus on the CardServiceFactory itself. The CardService
CardServiceFactory creates CardService module objects. The Factory
CardServiceFactory base class contained in opencard.
core. service is an abstract class that must be extended by the im-
plementation in order to produce specific CardService module ob-
jects. If you will, the CardServiceFactory module extends the
CardServiceFactory base class. The CardServiceFactory
module is used to create instances of CardService modules.
The methods provided by the CardServiceFactory base
classes are protected and are not meant for application use.
The CardServiceRegistry calls the factory's getCard-
Type (... ) method passing it a CardID and CardServiceSched-
uler object. The CardServiceFactory analyzes the CardID to
determine whether it recognizes the card. If necessary, the Card-
II constructor
public TestCardServiceFactory() {}
return cardType;
II class TestCardServiceFactory
10.1.4
The CHV Support Classes
The CHV support classes, shown in Figure 10.8, help OCF to obtain CHV support
a card holder verification string from the user. As you recall from
section 10.1.2, "The Card Access Classes", the CardChannel pro-
vides the sendVerifiedAPDU(... ) method, which is used by the
CardService when a CRV value must be sent to the card.
--
10.1 The CardService Layer Core Components - 161
CardChannel The CardChannel is responsible for obtaining the CRV value
either from the CardTerminal if it possesses the necessary capa-
bilities, or through the CHVDialog class. This section discusses the
CHVDialog and related classes.
CHVDialog The CHVDialog is actually an interface having only one method-
getCHV (... ) . Since a smart card may have more than one CRV value
used for different purposes, this method accepts a numeric parameter
specifying the CRV needed.
f:J ------.JI
Figure 10.8 «Interface»
CHVDialog DefaultcHVDialog
CHVSupport I.{from ()[Link]~)
Urom [Link])
1+ getCHV(chvNumber) : String
Classes + getCHV(chvNumber) : String
\
II DefaultCHVDialogResourceBundle
I Urom [Link])
1# getContentsO : ObjectDD
CardHolderVerificationGUI
I (from [Link]
# CardHolderVerificationGUIO
# display(num : intI : void
# clearOisplayO : void
# keyboardlnput(ioControl : CardTerminallOControl, customCHVDialog : CHVDialog) : string
#I promptUserjchvNumber: into CardTerminallOControl, CHVDialog) : string
+ sendVerifiedAPDU(SlotChannel, CommandAPDU, CHVControl, CHVDialog, intI : ResponseAPDU
10.1.5
The Card Service Exceptions
--
10. 1 The CardService Layer Core Components - 165
Table 10.3: CardServiceRuntimeException
CardService Base class for all CardService runtime exceptions.
Runtime CardServiceUsageException
Exceptions Indicates that the application has used the CardService incorrectly.
InvalidCardChannelException
Indicates that a CardChannel is not available. This could happen if
the card is removed before it can be accessed.
CardServicelnvalidCredentialException
Thrown when the credential used with secure messaging is invalid.
This could mean that either the application supplied an invalid cre-
dential to the CardService, or that the smart card responded with
an invalid credential. The latter case could arise if the MAC pro-
tecting a message is wrong, for example.
CardServicelnvalidParameterException
Thrown if the application passes an invalid parameter to the Card-
Service.
10.2
The CardService Optional Components
The opencard. opt. service package extends the CardService
layer core functionality by providing additional classes and excep-
tions. We will begin by explaining the optional classes, which are
shown in Figure 10.10.
CardService- The CardServicelnterface is provided merely as a conven-
Interface ience to the CardService programmer. The two methods defined
are those from the CardService base class that are frequently used
by application programmers.
OCF11 CardServiceFactory
(from [Link])
+ OCF 11 CardServiceF actoryO
# getCardType(cid : CardlD, scheduler: CardServiceScheduler) : CardType
# getClasses(type: CardType) : Enumeration
# knows(cid : CardlD) : boolean
# cardServiceClasses(cid : CardlD) : Enumeration
card5ervleeMisslngCredentialsExceplion
V..m ........_ )
Card5ervlceObjectNotAvallableException
Vrom opencant.opl_)
Card5ervlcelnvalidCommandExceplion Card5ervlcelnsufficlentMemoryException
vrom openo:[Link].-) vrom [Link])
cardServiceMlssingAuthorizationException CardServiceResourceNotFoundExcepllon
vrom ........optservlce) vrom opencord.opt_)
[Link] Exceptions
10.3
Standard CardService Interfaces
Standard The OpenCard Consortium Technical Committee is responsible for,
interfaces among other things, definition of standard CardService interfaces.
Once these interfaces have been defined, they are made available in
the OCF reference implementation. Card manufacturers and on-card
application providers are encouraged to implement these interfaces
for their cards. Off-card application providers are encouraged to base
applications on them.
Application When an off-card application is based on a standard Card-
advantages Service interface, support for a new smart card can be added sim-
ply by implementing the interface for the new card. The OCF factory
mechanism will select and instantiate the appropriate CardService
implementation for the inserted card.
Card provider When the card manufacturer or on-card application provider im-
advantages plements standard CardService interfaces, the cards can automati-
cally be used in existing OCF applications.
The OpenCard Consortium welcomes proposals for new standard
interfaces. Contact the consortium through the OpenCard homepage
10.3.1
The ISO File System Card Service
--
10.3 Standard CardService Interfaces - 169
Figure 10. 12:
ISO File
System
Package
java 10
Figure 10.14:
«Interface» «Interface» «Interface»
Signature CardServicelnterface SecureService JCAStandardNames
1/
CardService (from [Link]) (from [Link]) • (from [Link])
+ setCHVDialogO + provideCredentialsO +SHA1_RSA
+ getCard() +RAW_RSA
\
+SHA1_DSA
+ RAW_DSA
+ SHA1
+MDS
+ ZERO_PADDING
«Interface» + PKCS_PADDING
SignatureCardService + PKCS8_PADDING
(from [Link])
+ ISO_PADDING
+ signDataO + DES_CIPHER
+ signHashO
+ verifySignedDataO
+ verifySignedHashO
«Interface»
f
KeyGenerationCardService
«Interface»
KeylmportCardService
(from [Link])
+ importAndValidatePrivateKeyO
•(from [Link])
+ importAndValidatePublicKeyO
+ generateKeyPairO + importPrivateKeyO
+ readPublicKeyO + importPublicKeyO
Interface split This package provides three interfaces that together provide the
signature capability. The interface was split into three parts to reflect
the view that the complete functionality will often not be needed.
During personalization, the KeyGenerationCardService and
KeylmportCardService functionality will be required. After de-
ployment, the capability provided by the SignatureCardService
will be required. Also, not all smart cards provide key generation ca-
pability. The CardService provider can implement a subset of
these interfaces depending on the capabilities of the smart card being
used.
Signature The SignatureCardService extends the CardServiceln-
generation terface from the opencard. opt. service package and the Se-
cureService interface from the opencard. opt. securi ty package.
10.3.3
The Application Management CardService
Figure 10.15:
«Interface» «Interface» Application
AppletAccessCardService AppletManagerCardService
I(from [Link]!) (from [Link]!) Management
+ listO + instaIiApplet(appletCode)
+ getlnfo(appletlD) + removeApplet(appletlD)
+ exists(appletID) + registerApplet(appletID)
«Interface»
AppletCode
I(from [Link]!.mgm!) EMVTags
(from opt emv mgmt)
+ AppletCodeO
Appletlnfo
(from [Link]!) ~
I
# label : String I
# aid: AppletiD
# domain: SecurityDomain EMVAppletlnfo
# data : Object (from [Link]!)
# discrDatal : byte[]
AppletiD + AppletinfoO
# prefName : byte[]
+ getAppleti DO
(from [Link]!) # priolnd : byteO
+ getDataO
+ RC_O: int
......
+ getDomainO
+ getLabelO
fj--- + EMVAppletlnfo( ... )
+ EMVAppletlnfo(TLV)
+ RC_F: int # setLabelO + getPreferredNameO
# setAl DO + getPriorityO
+ AppletlD(byte OJ # setAppleti DO + getDiscretionaryDataO
+ AppletID(int) # setDataO + fromEMVTLVgetLabelO
+ AppletID(String) + setDomainO +toEMVTLVO
+ getRegistrationCategoryO + toStringO + toStringO
Brooks Atkinson
11 The OCF Security Concepts
Security is a central issue with smart cards. Security protocols protect Security
access to data on the smart card through secure messaging. Addition-
ally, they allow the off-card application to use cryptographic algo-
rithms and keys stored on the smart card for digitally signing data and
signature verification. Implementing a smart card security concept
requires dealing with environmental and legal constraints as well as
with smart card specifics.
Secure messaging protects communication between the applica- Secure
tion and the smart card. A message authentication code (MAC) can messaging
be used to detect changes in the transmitted data, and encryption can
be used to ensure privacy.
This is an area where the standardization process has not pro- Lack of
gressed as much as the application programmer would perhaps wish. standards
Each different card type tends to implement its own mix of algo-
rithms and to use them in its own way. Cards can differ in which
APDU bytes are used to calculate the MAC code, and in the padding
bytes used when encrypting the data, for example.
On a 7816-4 file system-oriented card, the card type determines
the available secure messaging mechanisms. However, with freely
programmable cards such as the Java Card, secure messaging can
also differ from application to application.
The CardService, as a card or application specific component,
could deal with some of these differences, but the application envi-
ronment must also be taken into account. The off-card application
and the environment in which it runs will determine how access to
the cryptographic algorithms and keys needed for secure messaging
can be obtained. Often the keys will not be directly available to the
application, but will instead be stored in a security access module, or Security access
SAM. Some cards may require the use of a key derived from an un- module
protected card characteristic such as the card serial number. A SAM
could also be used to hold the special algorithm and master key used
--
11 The OCF Security Concepts - 175
to generate the derived key for communication with the inserted
smart card. Programming such environment dependencies into the
CardService would reduce its general usefulness.
Internal and ISO 7816-4 specifies two commands for authentication.
External EXTERNAL AUTHENTICATE is used to satisfy access conditions
authentication that may be imposed by the smartcard, it therefore authenticates the
external world to the card. INTERNAL AUTHENTICATE is the re-
verse operation; it authenticates the card to the external world (see
also Section 4.2.1 and 4.2.2).
In both cases, authentication is based on the knowledge of a se-
cret. This can be either a secret key, using a symmetric cryptographic
algorithm, or a private key in the case of an asymmetric algorithm.
The authenticating party (challenger) has to know either the same se-
cret key or the matching public key. The party to be authenticated re-
ceives a random challenge, encrypts it with the secret and sends the
result back to the challenger. The challenger uses the same key (in
the case of a symmetric algorithm) or the matching public key (in the
case of an asymmetric algorithm) to verify that the secret is know to
it's partner.
For external authentication, the smartcard needs information about
the key (secret or public) to be used to verify the outside world's
knowledge of the secret. For internal authentication, the smartcard
needs information about the secret for which to prove the knowledge.
In OCF 1.1 CardService interfaces, only the CardServices in
opencard. opt. signature explicitly reference keys, using inter-
faces defined in opencard. opt. securi ty. The CardServices in
[Link] deal with asymmetric cryptography,
and the key referencing interfaces cover only public and private keys.
OCF 1.2 introduced a new interface SecretKeyRef. To allow the
definition of a single interface for authentication, regardless of the
symmetry of the underlying cryptographic algorithm, a common base
interface for all three kinds of keys has to be introduced, resulting in
the following inheritance tree:
KeyRef
~ PublicKeyRef
C PrivateKeyRef
SecretKeyRef
11.1
Open Card Security Overview
Before getting onto the class description, we will cover the basic
ideas behind the OpenCard security concept.
Since the CardService is the OpenCard component that deals
with card and card application specifics, it must also implement the
appropriate security mechanisms. The application using the Card-
Service is written to run in a particular environment. In particular,
the application must be able to obtain access to the cryptographic al-
gorithms needed for secure messaging. The environment can provide
these algorithms either directly in software or through use of a SAM.
The application also has access, directly or indirectly, to the required
keys.
The exportable version of the OpenCard Framework does not im- Exportable OCF
plement any cryptographic algorithms; this is to avoid conflict with version
U.S. export control regulations. Since the CardService, and not the
framework itself, implements data security mechanisms, the Card-
Service provider must observe the appropriate export rules.
The application must provide the CardService with the algo- Credentials
rithms and keys. This is done through use of credentials, which are
objects encapsulating key information and the corresponding algo-
rithms. The credential implements an interface that allows the cryp-
[Link] Package
Java security For the most part, the Java security interfaces used by OCF are
classes containers for cryptographic key information. The Key class provides
simple methods describing the key information it contains. Pri-
va teKey and PublicKey each extend Key merely to provide type
safety when dealing with public key algorithms. The interfaces
DSAPrivateKey, DSAPublicKey, and DSAParams provide acces-
11.2
OpenCard Security Classes
To begin with, we should note that the OpenCard Framework distri-
bution conforms to U.S. export restrictions. Extreme care was taken
to structure OCF so that cryptographic code must be provided by the
application or by the specific CardService implementation.
The OpenCard developers divided the actual framework code con-
sisting of the opencard. core and opencard. opt packages into a
freely exportable deliverable and an export-restricted deliverable
package. The freely exportable OCF package contains no code that
can be used for data encryption. The export-restricted deliverable
package contains exactly one class l - RSASignCredential from
the opencard. opt. securi ty package. Since this class directly
implements the RSA public key algorithm for arbitrary data with an
arbitrary key length, it cannot be freely exported from North Amer-
Ica.
Figure 11.2 shows the OpenCard security classes separated into
categories according to their use. The Cryptographic Key Classes
define wrappers for cryptographic key material. The Smart Card
Key Classes provide a means for specifying which key on the smart
card is to be used for a secure messaging operation. The Card-
Service Interface Classes influence the CardService interface
directly. The Credentials provide interfaces to cryptographic algo-
rithms and data definitions.
We will cover each of these categories in detail in the following
sections.
1 The actual export-restricted deliverable package contains one OCF class and ad-
«Interface»
SymmelricCredentlal f------H---t:s!
(from security)
11.2.1
Cryptographic Key Classes
Key classes Figure 11.3 shows the cryptographic key classes with their methods.
The classes whose methods are not displayed belong to the
java. securi ty and java. securi ty . interface packages. Re-
lationships among the java. securi ty classes are not displayed.
In general, these classes can store key information. All key classes
implement the base class methods inherited from java. se-
curi ty . key. The getAlgori thm () method retrieves the name of
the algorithm with which this key is to be used. The getEncoded ()
method retrieves the key in a standard format. The final common
method, getFormat () , returns the name of the format returned by
getEncoded () . Additional methods allow access to the key material
appropriately for the involved algorithm.
-"
DSAPublicKey
.""'m ..................", ;'
'" OSAParams
DSAPublicKey 1 Cryptographic
"",m_"d._ (ft'Om jaVU4lCUrtty.
+ DSAPublicKey(p, q, g, y)
+ DSAParams(p, q, g)
+ opname(argname) : return """HI Key Classes
--
+ opname(argname) : return
+ getAlgcrithm() : StrIng
+ getG() : [Link]
+ getEncoded() : by1e{)
+ getPO: [Link]
+ getFormat() : string
+ getParams() : java ... DSAParams ~ + geIQ(): [Link] - - - -~I DSAParams .1
+ opname2(argname) . return (ftOm1~~_
yo :
~~I
+ get Biglnteger
.lI!Om ......DSAPriyateKey
__
DESKey + DSAPrivateKey(p, q. g, x)
l""'m ........_ .....1M -I
+ getAlgcr~hmO : StrIng
+ getAlgcrithm(): StrIng + getEncoded() : bytell
+ getFormat() : string + getFormat() : String
- -- --- --
+ getEncoded() : by1e{) + getParamsO : Java ... DSAParams
+ getBytes() : by1e{J + getXO . Biglnteger
I
+ DESKey(da1a : by1e{D
+ bodyO : byte()
RSACRTKey
---------------_-1>\ Key
RSAPubllcKey(ftOmjavL·......,
i (ftOm . . . . . .- - .. .urIM I....m.....................
+ RSACRTKey(p. q. qm, dp. dq, Ilen, olen, keylen) + RSAPublIcKey(elen, e, m. keylen)
+ RSACRTKey(p, q. qm, dp. dq) + RSAPublIcKey(e. m)
+ coelflclent() : Biglnleger
+ exponent10 : Biglnteger
+ exponent20 : Biglnteger
+ getAlgcrithm() : StrIng
+ getEncoded() : by1e{)
+ getFormat() : string
PubllcKey
""'mjaWo_
, I
+ getAlgor~mO : StrIng + maxlnputlengthO: int
+ getEncoded() : by1e{] + maxOUtputlength() . Int
+ getFormat() : String + modulus() : Bigln1eger
+ getlnputlength() : int + publicExponent() : Biglnteger
+ maxoutputLength() : int
.... ....
' . . ---------
+ primel() : Bigln1eger
+ prime20 : Biglnteger
--- :BI=~~I
-- -----
RSAPriyaleKey
....m.....................
+ RSAPrlvateKey(m, e, inputLength, oulputLength, keyLength)
+ getAlgortthm() : StrIng
+ getEncoded() : by1e{)
+ getFormat() : String
+ getlnputlength() : int
+ maxOulputlength() : int
+ modulus() : Biglnteger
+ privateExponent() : Blglnteger
11.2.2
The Smart Card Key Classes
Different types of smart cards store keys in different ways. File sys- Smart card keys
tem oriented cards generally store keys in files, while a Java Card
stores key information in objects.
When performing a cryptographic operation such as signing with
the card, the key to be used must be specified. The different ways
keys are stored on a card are reflected in the methods for key selec-
tion. Some cards require the key to be specified using a file path,
while others require a key index or number.
The smart card key classes shown in Figure 11.4 provide a general
mechanism for key identification and also a specific implementation
for cards that require a key to be identified by file path.
opencard,[Link] Package
•
11.2.3
CardService Interface Classes
The classes discussed in this section are primarily used for secure
messaging. Their goal is to allow the application to communicate
with smart cards implementing diverse types of secure messaging.
The classes discussed in this section are shown in Figure 11.5.
Figure 11.5:
«Interface» CredentialStore
CardService
Credential I (from [Link]
(from security) # CredentialStoreO Interface
+ supports(cardlD : CardlD) : boolean Classes
+ getlnstance(className : String) : CredentialStore
«Interface» # storeCredential(credlD : Object, cred : Credential) : void
SecurityDomain # fetchCredential(credlD : Object) : Credential
(from security) # getCredentialiDsO : Enumeration
CredentialBag
(from [Link])
+ CredentialBagO
+ addCredentialStore(credstore : CredentialStore) : void
+ getCredentialStore(cardlD : CardlD, clazz : Class) : CredentialStore
+ getCredentialStores(cardlD : CardlD, clazz : Class) : CredentialStore(j
«Interface» «Interface»
SecureService AutCardService
(from [Link]) (from [Link])
+ closeApplicationO : void
+ provideCredentials(
+ externalAuthenticateO : boolean
domain: SecurityDomain,
+ getChallengeLengthO : int
creds : CredentialSag) : void
+ internalAuthenticateO : byte[]
--
11.2 OpenCard Security Classes - 183
CredentialStore Credentials for a specific smart card type are collected in aCre-
dentialStore object. CredentialStore is an abstract class that
must be implemented to support a particular type of card. The Card-
Service provider generally implements the CredentialStore
since it must match the CardService.
CredentialStore The fetchCredential (... ) and storeCredential (. .. ) meth-
methods ods access the credentials with the help of an identifier whose type is
defined appropriately for the smart card.
CredentialBag Support for different types of smart cards is provided through the
CredentialBag, which is a container for CredentialStore ob-
jects.
Setting up The application creates Credential objects for all cards to be
credentials supported. The Credential objects are placed in the appropriate
CredentialStore objects. Finally, the CredentialStore objects
for all supported cards are placed into a CredentialBag.
The application passes the CredentialBag to an instantiated
CardService, which then picks out the corresponding Creden-
tialStore and Credential objects. Since the application always
passes all credentials to the CardService, the application does not
need to be card specific.
Secure A CardService that implements secure messaging must imple-
CardService ment the SecureService interface. The provideCreden-
tials (...) method allows the CredentialBag to be passed to the
CardService.
Security Along with the CredentialBag, the provideCreden-
domain tials (...) method accepts a Securi tyDomain object defining the
area on the card for which the CredentialBag is valid. For a file
system oriented card, the Securi tyDomain interface is imple-
mented by the opencard. opt. iso. fs. CardFilePath class,
which designates a specific dedicated file on the smart card.
The following code fragments illustrate how the application uses
the credential mechanism.
First the application creates credentials for the cards to be sup-
ported and sets up the CredentialStore and CredentialBag
objects. This can be done during initialization if the user operation is
clear from the beginning.
[Link](O,
new DESSecureCredential("Ox6b258f15d07c43ea"»;
[Link](l,
new DESSecureCredential("Ox31323437383b3d3e"»;
[Link](5,
new DESSecureCredential("Ox70737576797a7c7f"»;
[Link](store) ;
This fragment sets up a key bag for the root security domain. The
MFCCredentialStore class extends the CredentialStore ab-
stract class for the IBM MFC smart cards. It can be found in the
com. ibm. opencard. access package in the OCF reference im-
plementation.
The DESSecureCredential class implements the DES algo-
rithm in software. For this reason it is in the export restricted OCF
package. The UML diagram shown in Figure 11.6 gives an idea of
the functionality provided by a typical credential.
Figure 11.6:
The DESSecure
Credential
DESSlgnCredentlal «Interface»
fromacctsl SecureCredentla1
+ DEsslgnCredenllal(key : DESKey)
+ sign(data : byteO) : byte{] + getstrongRandomO : byteD
.. getlnputLengthO : Inl .. setlCV(lcv : byteU) : void
+ encryptChalned(deta : byteD, offset Inl, length: Inl) : void
.. decrypiChalned(data : byteO, offset Int, length: Int) : void
.. updaleMAC(dala : byteU) : void
+ finlshMAC(data : byteDJ : byteo
DESSecureCredentlal
fromaccea:t
+ DESSecureCredentlal(key : string)
+ getstrongRandomO : byteo
.. selICV(lcv : bytelJ) : void
+ encrypiChained(deta : byteO, offsel : int, lenglh Inl) void
+ decryptChained(data : byteO. offset : inl, length Int) void
+ updateMAC(dala : byteO) : void
+ finlshMAC(deta : byteO) : byteO
+ tostrlngO : String
+ parseDESKey(dala : string) : byteD
.. loHexOump(data : byteO) : string
--
11.2 Open Card Security Classes - 185
implement secure messaging, the key provided to the constructor is
used.
The previous code fragment sets up the credentials for only a sin-
gle card. To support additional cards, CredentialStore objects of
the appropriate type must be instantiated and filled with Creden-
tial objects. The application then adds the CredentialStore ob-
jects for the additional cards to the existing CredentialBag.
After setting up the CredentialBag, the next code fragment
waits for a card to be inserted, obtains a CardService, passes the
CredentialBag to the CardService, and then reads some data.
After obtaining a FileAccessCardService, the application
calls provideCredentials (... ) to pass the credentials and key
domain to it. The application then goes on to read some data from
the card. If secure messaging is required, the CardService will
protect the APDU packets appropriately. From the application point
of view, this happens transparently.
Using
credentials SmartCard sc = [Link] (cr);
i f (sc != null) {
FileAccessCardService fs = (FileAccessCardService)
[Link] ([Link], true);
[Link](rootKeyDomain, rootKeyBag);
CardFilePath file = new CardFilePath(":3fOO:b010:bb04");
byte[] data = [Link](file, 0, 20);
Card From this example we also see that the application contains no
independent code specific to a particular CardService. The application will
programming work with any card as long as a FileAccessCardService and cor-
responding credentials are available.
«Interface»
SymmetricCredential t------[>I
(trom security)
11.3
Running OCF in Browsers
OCF in a One especially interesting application of the OpenCard Framework is
browser access to smart cards from Java applets running in a web browser. In
this section, we explain how OCF adapts to the security models used
by different browsers and how signed applets can use the OpenCard
Framework.
In Section 11.3.1, we give an overview of browser security models
and point out their impact on the framework. In Section 11.3.2, we
11.3.1
Browser Security Models
The OpenCard Framework encapsulates access to smart card readers System and
and therefore needs to access system resources not accessible from shared library
the Java sandbox. Communication with the card reader requires access
hardware access and configuration of the framework requires access
to the system properties. For example, when using the Java Commu-
nication API or the OCF Pc/SC support to access the card reader, a
shared library must be loaded.
The JDK 1.1 already provided an extension to the sandbox that JDK 1. 1 security
allowed Java classes contained in a signed JAR-file to access all sys- model
tem resources. However, the security model was very primitive: un-
signed applets were limited to the Java sandbox while signed applets
were allowed unlimited system access.
Users soon realized that a security model with finer granularity
was needed, but before Sun responded to that need with the improved
Java 2 security model, Microsoft and Netscape had introduced their
own security models (see [NET01], [MIC01]). These models are
based on signed archives that must be created with proprietary pack-
ing and signing tools.
In contrast to the JDK 1.1 security policy, signed applets cannot Browser
access system resources by default. An applet that needs to perform a security models
privileged action must explicitly request the required privilege from
the web browser's PrivilegeManager before actually performing
the action. This introduces a dependency of the applet's code on
browser-specific privilege manager classes.
The task was to make the OpenCard Framework work together OCF concept is
with the predominant browsers on the market without introducing a browser
direct dependency on browser-specific behavior - and doing this independent
without weakening security.
--
11.3 Running OCF in Browsers - 189
11.3.2
Invocation of Privileged Methods
SystemAccess sys
[Link]() ;
[Link](sys) ;
File System
Serial Port
System Properties
11.3.3
Security Implications
JVM
File System
Serial Port
System Properties
12.1
Preparing Your System
Prior to developing an application that accesses a smart card through
OCF, you need to take care of a few prerequisites:
1. First you need to have Sun's JDK (Java Developer's Kit) installed
- preferably version 1.1.6 or later. Sun provides the JDK on
[Link] Alternatively, you can get the
JDK with one of the commercially available integrated develop-
ment environments for Java.
2. Download OCF from [Link] (the web site of
the OpenCard Consortium) and install it. Before you can start
working with OCF, you need to bring the executable class files
into the Java class path. If you are using native code together with
OCF, like the bridge from OCF to PC/SC on Windows, you need
to put this executable code into the path for native binary code.
3. Obtain a smart card reader with support for the OpenCard Frame-
work. The OpenCard Consortium maintains a list of supported
readers on [Link] .[Link]/.
4. Take the smart card provided in this book.
12.2.1
Setting the OCF Configuration Properties
1. [[Link]]/lib/[Link]
2. [[Link]]/.[Link]
3. [[Link]]/[Link]
4. [[Link]]/.[Link]
You can determine the locations where OCF will look for the
[Link] file using the following short application:
"\\.[Link]\n\t" +
props. get Property ("user. dir") +
"\\[Link]\n\t" +
props. get Property ("user. dir") +
"\\.[Link]\n") ;
12.3
The First Simple Application
After you have set up your system with both hardware and software,
you are now ready to develop the first simple smart card application.
Let us develop a little program that reads the information on the
cardholder from the smart card provided with this book (for a de-
scription of this card's layout see Appendix A ''The Card"). This data
is stored in the file EF_CARD_HOLDER_DATA, which has the file ID
OxC009. The operations to read or update this file are protected with
the password "password".
We start our file ReadFile. java with some import statements, a
class definition, and a main (... ) :
import [Link];
import [Link];
import [Link];
import [Link];
12.3.1
Starting OCF and Shutting it Down Again
A block of code that you will find in every program using OCF are
the calls to start the framework before using it and to close down the
framework when it is no longer used. The designers of OCF decided
to make you start the framework explicitly instead of having it started
implicitly during the first usage. The explicit starting was chosen, be-
cause during framework startup all configuration work and initializa-
tion of attached card terminals must be done. This could add unex-
pected delays when done implicitly during an access. In addition, er-
rors might occur during the initialization phase. We need to provide
exception-handling code for the framework startup as well as for the
shutdown.
We need to make sure that the Smart Card . shutdown () com-
mand is executed no matter what, even if the program ends with an
exception. The application must always release all system resources
allocated by OCF. Therefore we place the SmartCard. shut-
down () call into the finally block.
try {
[Link]() ;
catch (Exception e) {
[Link]() ;
At first glance, it may seem strange that shutting down OCF could
raise another exception. However, the shutdown may cause dynamic
12.3.2
Obtaining a SmartCard Object via
waitForCard( ... )
[Link]) ;
Smart Card sc ; [Link](cr);
i f (sc ;; null) {
II A smart card was inserted that does not match
II Handle how it would be appropriate in your app
else {
II Here we need to add code to work with the card
12.3.3
Obtaining a CardService Object
12.3.4
Using this Sample Program with Other Cards
If you want to use another smart card instead of the card that is pro-
vided in this book, you need to make sure that a FileAccessCard-
Service is available for this card. The smart card should have a fIle
with the ID OxC009 and the access conditions for that fIle should be
set to ALWAYS or CHV for read and write access.
Usually, the manufacturers of smart cards support the creation of
new card layouts with appropriate tools. Of course, you might want
to modify the program to read other existing fIles instead of the fIle
with the ID OxC009.
12.4
Smart Card Access of a Digital Signature
Application
12.4.1
Attributes
--
12.4 Smart Card Access of a Digital Signature Application - 203
We let the attribute i Tracer refer to a Tracer object that we
want to use for OpenCard-style tracing.
12.4.2
Constructor
catch (OpenCardException e)
iTracer. critical ("cardInserted", e);
earlierException = e;
catch (ClassNotFoundException e)
[Link]("cardInserted", e);
earlierException = e;
12.4.4
allocateServices(SmartCard, int)
try {
signatureService (SignatureCardService)
[Link](
[Link], true);
[Link](dialog);
II Special handling of failure to allocate
II a signature service:
catch (ClassNotFoundException e)
[Link] ("allocateServices" , e);
12.4.5
cardRemovedO
return fileSystemCardPresent()
&& (signatureService !; null);
12.4.7
getCardHolderData(}
try {
propagateAnEarlierException() ;
catch ( ...
catch (OpenCardException e) {
[Link]("getCardHolderData", e);
throw new SignatureCardException(
"Exception from getting cardholder data", e);
SignatureCardException signCardExcp
new SignatureCardException("Exception of "
+ [Link]() .toString()
+ " from earlier method execution:",
earlierException) ;
earlierException = null;
throw signCardExcp;
12.4.9
setCardHolderData(String)
12.4.10
sign(int, byte[])
The method sign (... ) lets the smart card generate a digital signature
for given data using a given key and returns it as a byte array.
After the same error handling and checking code that you have
seen before, we create a private-key file object for the private key
with the key number given by the parameter keyNumber. Then we
let the card generate the signature by calling signData (... ) of the
signatureService instance, in this example using the RSA algo-
rithm in combination with SHA-l and Zero-Padding. If this is suc-
cessful, we return the obtained signature as a byte array, otherwise
we return null:
catch ...
--
12.4 Smart Card Access of a Digital Signature Application - 211
Note that the sign (... ) method will not work with the card pro-
vided in this book, because this card is not capable of performing
public key cryptography.
12.4.11
close()
catch (OpenCardException e)
[Link]("close", e);
throw new SignatureCardException(
"Exception from closing OCF" , e);
12.4.12
Class SignatureCardException
super (message) ;
primaryException = null;
return primaryException;
12.4.13
The Complete Sample Source Code
Now we have examined the smart card access part of the Internet
Stockbroker demo application.
The next steps you might want to take are downloading the
complete sample code from htlp://[Link]/,
13.1
Internet Stock Brokerage
In this section, we present an example that shows how smart cards
can be used for securing stock brokerage over the Internet. We start
by discussing the topics of data integrity and non-repudiation, which
are very important in this scenario. Further, we describe a 3-tier ar-
chitecture the stockbroker may choose for the implementation of his
brokerage solution. We conclude this chapter by showing how the
smart card related part of the client software might be implemented
using the OpenCard Framework.
13.1.1
Security Considerations
--
13.1 Internet Stock Brokerage - 215
repudiation means that once the broker received an order, he can be
sure that the customer cannot later deny that he gave the order.
Data integrity can be assured by using digital signatures: Each or-
der is signed before it is sent to the broker, so that any change would
be detected. Non-repudiation is harder to achieve. If all customers
have unique key pairs, the broker can prove the owner of the key pair
that has been used to sign a particular order. However, the customer
could claim that somehow somebody obtained his key pair and was
thus able to abuse it for fraud.
Legal non-repudiation can only be achieved if it is infeasible to
obtain a customer's private key. This can only be guaranteed, if the
private key is stored in a secure token, which it never leaves. Modern
smart cards that support public-key cryptography are the ideal tokens
for this purpose. They are low-cost, can generate and securely store
several key pairs and they can generate digital signatures using the
stored private keys. Usually, signature generation is only possible af-
ter the cardholder proved his identity to the card by providing a per-
sonal identification number (PIN). As private keys are generated,
stored, and used on card only, they are not accessible for an attacker.
The only way to fake a signature is to steal a smart card as well as the
PIN for that card.
13.1.2
Secure Stock Brokerage Architecture
Application
Tier-2
Server
Tier-1
I L
13.1.3
Protocols
Smart Application
Client
Database Transaction Figure 13.2
Card Server Server Server
Simplified
Get HTML-page with app~ Representation
of the Purchase
HTML-page with applet
Process
Create Order
Log Order .
Place Order
Confirmation
og Confirma1jp
- Confirmation
--
13.1 Internet Stock Brokerage - 217
I. The customer navigates to the broker's homepage. Along with
HTML-content, an applet for conducting stock orders is down-
loaded from the web server and displayed in his browser.
2. Using this applet, the customer creates an order and submits it.
3. The applet requests the customer's smart card.
4. The customer inserts the card and enters the PIN for activating
the card's signature function.
5. The signature is generated (see Chapter 3).
6. The applet connects to the server and sends the signed order to
the brokerage servlet.
7. The brokerage servlet receives the signed stock order and ar-
chives it.
8. The brokerage servlet retrieves the customer's certificate from a
certificate directory and uses it to verify integrity of the received
data and the identity of the sender.
9. If the validation of the signature is successful, the servlet accesses
the transaction system on Tier-3 to conduct the order.
10. The servlet sends a confirmation back to the applet on the cus-
tomer's computer, indicating that the order was successfully
placed.
II. The applet receives the confirmation and informs the customer.
13.2
Distributed Payment Systems
...
-
Card Info
Payment
Scheme Card Info Get Challenge (1) ...
- .
Begin Debit (3) Challenge (2)
When the terminal is switched on, it reads certain data from the
merchant card. This data is needed whenever a payment shall be con-
ducted. The merchant enters the amount to be paid on the counter to
initiate the payment. The payment terminal displays the amount and
asks the customer to insert his card. The customer inserts her purse
card and the terminal reads the current amount and some other infor-
mation like the card identification number. If the information read
from the purse card is consistent and the amount of money stored on
the purse card is greater than the amount to be paid, the terminal con-
ducts the card-to-card payment protocol:
13.2.2
Card-to-Card Payments via Internet
--
13.2 Distributed Payment Systems - 221
exactly know when and where a customer buys something with his
credit card.
Using a prepaid and anonymous electronic purse scheme over-
comes these problems. Customers can load a certain amount on their
purse cards and spend it anonymously. The charges for payments
from a prepaid purse are much smaller than charges for credit card
transactions, typically about 1 % or less. As purses are prepaid, the
payment is a simple debit operation, which requires no online
checking. A certain amount is moved from the purse card to the mer-
chant card for each payment. Thus, a large number of payments can
be accumulated by the merchant card and can be cleared in one burst.
This feature of card-to-card payment schemes is especially useful in
the Internet environment, because it allows merchants to offer cheap
goods or information via the Internet, e.g. a record company could
sell individual music titles and a newspaper could sell individual arti-
cles with additional background.
In the rest of this section, we describe a Distributed Acceptance
Terminal for payments via the Internet using the GeldKarte.
[Link]
Protocol
When a customer wants to buy goods offered on a web site, he puts
his purse card into the reader connected to his PC, his Network Com-
puter or a self-service terminal. On the merchant's side, a merchant
card or a secure token simulating several merchant cards is required.
The payment via the Internet basically works as follows:
[Link]
Scenarios
Depending on the system setup, the payment server involved in the
payment protocol needs not be identical with the merchant's server.
The following figures show some of the possible scenarios.
Merchant WebServer
Database
with Merchant Cards
Server
or Token
Cards
Figure 13.6:
PaymentServer with A Service
Merchant Cards Provider Accepts
or Token Payments on
8ehalfofa
........................."!~~~~.~~.........,~~:....................
Merchant
Merchant
Database
WebServer
Server
Customer
Appliances
with Purse
Cards
r------...
Protocol Page with Pa mentApplet
Payment Protocol
-
.-----
Request Delivi ry
Delivery
The user navigates to a web page that contains offers. When she
decides to buy something, she selects the desired items and gets a
new page with the Payment Applet. The Payment Applet asks her to
confirm the payment and conducts the payment protocol with the
Payment Server.
13.2.3
Architecture Overview
Figure 13.9:
Architecture for a
Web-based
Distributed
Payment
System,
Modified for Use
of an Intelligent
Terminal
Internet
Customer
Term i nal
.,
"
, Purse Merchant
Card Card
13.2.4
Implementation
I
Web
Browser OCF OCF [Link] Server
Java Java
Virtual Virtual
Machine Machine
[Link]
The Standard Software
On the client, we need a web browser that supports the relevant sub-
set of Java 1.1 that is required for running the payment applet. We
decided to use Netscape Communicator 4.5 or higher, but it would
also be possible to use Microsoft Internet Explorer or any other Java
1.1 compliant Web browser as well.
On the server, we need a servlet engine that provides a Java 1.2
compliant runtime environment and the Java Servlet 2.2 API (see
[SER99]). We decided to use IBM WebSphere Application Server
4.01 or higher, but it would also be possible to use other application
servers supporting the Java Servlet API.
[Link]
The Payment Servlet
WebSphere Application Server provides a framework for servlets ac-
cording to the Java Servlet API v2.2 (see [SER99]) - that supplies
base classes for writing own servlets. For example, there is a class
named HTTPServlet, from which we derived our payment servlet.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link] . terminal.*;
public class PaymentServlet extends HttpServlet
SmartCard card_ = null;
CardRequest cr =
new CardRequest([Link]);
card_ = [Link](cr);
serverAdapter_=
new PaymentServerAdapter(merchantProtocol);
card_.beginMutex() ;
catch (Exception e)
throw new UnavailableException(
"Initialization failed: " + [Link]());
14.1
Developing a Card Applet
The process for developing a card applet is shown in Figure 14.1.
There are variations in the tools and in the development environment
provided for the Java Cards of the various suppliers. Therefore, your
environment might differ in details from what we describe.
Figure 14.1:
The Process for
Developing a
Card Applet
............ p ..;:.~~--I
- - ' ' - - - - - ......
--
14.1 Developing a Card Applet - 233
The code development starts with the creation of a Java source
code file. You compile this source file with a standard Java compiler,
using in place of the JDK the class libraries of the Java Card Frame-
work. You can test the resulting class file in the Java Card simulation
environment on your computer.
In the next step, the byte code converter verifies the class file and
optimizes it for the limited resources of a smart card. You can test the
resulting cap file in the Java Card emulator on your computer.
Finally, all cap files comprising your on-card application are
downloaded into the card. This download can be secured by signing
the code and letting the card verify the signatures.
14.2
Inside the Java Card
14.2.1
The Java Card Framework
14.2.2
Lifetimes of On-card Programs and Objects
14.3
A Sample Java Card Applet
In the following, we want to examine a Java Card applet in detail.
This applet will later be called through OCF.
Our simple sample applet is maintaining business card informa-
tion. It provides methods to read and write this information.
One of the features of the Java language, which many of us can
hardly imagine to do without, is the class String. Not having this
class on a Java Card, we store all business card information in byte
arrays of fixed length, which we call fields. Corresponding to one
business card, we make up a record from five fields containing the
name, title, address, telephone, and e-mail address.
The applet provides methods to set and get the individual fields.
To protect the fields from unauthorized access, the applet does not
grant any access until the correct PIN was entered. After the PIN has
been verified, it remains valid until the applet is deselected or until
the card is powered down.
The card we develop this applet for is the IBM "JCOPlO" Java
Card, which reflects the Java Card 2.1.1 specification. This card also
contains the support for the Open Platform 2.0.1 specification.
Now we start creating the applet. We call it BizCardApplet. To
make it a Java Card applet, we derive it from the class Applet in the
Java Card framework:
Selection Remember that before we can communicate with our applet to use
processing its services, we need to select it. The off-card part of the application
must send a SELECT APDU to the Java Card runtime environment,
which then calls the card applet's select () method and subse-
quently its process (APDU) method with the SELECT APDU
passed to it.
Here we encounter another class from the Java Card framework,
the class APDU. The APDU was passed to the applet from the off-
card part of the application.
Our sample applet has four methods, which can be called from the
off-card application through the appropriate APDU: per-
formCHV (APDU), getField (APDU), setField (APDU), and se-
lectFile (APDU) .
deselect() We want to accept the PIN as valid only as long as our applet is
active. Therefore we use the method deselect (), which is called
by the Java Card runtime environment before our applet loses its ac-
tive status. In this way, we can reset the PIN when our applet is de-
selected:
1**
* Actions to be performed if this applet is deselected.
*1
public void deselect() II switching the applet
pin_.reset () ; II .. resets PIN-validated flag
To feed the user's PIN input to the applet and have the applet
check it against its value of the PIN we provide a method of its own,
which we call performCHV (... ) :
After we have carefully checked all parts of the APDU, we let the
OwnerPIN object check the input passed in the APDU's body. On
switch (buffer[IS078l6.0FFSET_Pl])
case OxOO : bcRecord = bizCardRecordO break;
case OxOl : bcRecord = bizCardRecordl_; break;
default: II Index is out of bounds
[Link](IS078l6.SW_INCORRECT_P1P2) ;
II Le currently
short le = [Link]();
apdu. setOutgoingLength ([Link]) ;
Now we have seen all run-time functions of our applet. The bit instal/(.. .)
that remains to be done is the initial installation of our applet. We
provide a method install (... ). It invokes the constructor of our
applet (which we made protected) and then registers the applet to the
Java Card runtime:
1**
* Install the applet on the Java Card.
*
* @param All parameters are currently ignored.
*
*1
public static void install ( byte[] bArray,
short bOffset, byte bLength) {
BizCardApplet me = new BizCardApplet();
[Link]() ;
/**
* Create a new BizCardApplet.
*/
protected BizCardApplet() {
super () ;
bizCardRecordO_ = new BizCardRecord() ;
bizCardRecordl_ = new BizCardRecord();
14.4
Using OCF to Work with Card Applets
The applets on the Java Card are Java objects, in the same way as the
objects of OCF and of the Java code using OCF are Java objects. The
major difference between these Java objects is that the card applets
are on a computer of its own. Conceptually we have to treat the ob-
jects on the Java Card as objects on a server.
Using the services of objects on a remote computer is a common
situation. Known mechanisms to call the services of remote Java ob-
jects are Remote Method Invocation [RMI99] or the Common Object
Request Broker Architecture [CORBA99].
Both RMI and CORBA require additional code on the client side
as well as on the server side. With the limitations of today's smart
cards, we can not afford additional code on this tiny server. There-
fore, both mechanisms cannot reasonably be used for the Java Card
today. For accessing and using the applets on Java Cards, we need a
new concept that minimizes the work to be done by the card.
The mechanism for using objects from a Java Card involves proxy
objects, a standard object-oriented design pattern also applied in RMI
and CORBA. We let card applet proxies represent the applets on the
card. An application uses the services of a card applet through the
corresponding card applet proxy.
Each proxy class has to know the application identifier (AID) of
the card applet to communicate with and the protocol for interaction
with that card applet. Whenever the application invokes a proxy
method, the proxy starts communicating with the card applet on the
card and generates some result, which it returns to the application.
Figure 14.2:
AooletEroxv ..n All
AnnletP..mxv.2 Communication
ApplelProxy 1 between OCF
and the Java
DIU. Card is through
I.e D.U1 ISO 7816
ISO 7816
..,
P2
SW,
APDU's APDUs.
INS
V
SW2
Java Card
OS Kemel
The communication layer between the proxy and the card is stan-
dard ISO 7816 APDUs (see Figure 14.2). This has the advantage that
Java Cards can have a high compatibility to other non-Java cards.
Because applet proxies need to communicate with the card and Applet proxies
hold knowledge about the card, we can best make them subclasses of are special
the OCF CardService. As specialized card services, before sending CardServices
APDUs, card applet proxies must allocate a card channel for com-
munication with the Java Card from the card service scheduler -like
any other card service.
Figure 14.3:
Card Applets
with their Asso-
ciated Proxies
and States
Ch::lnlnAI~.. Card
State
J We can assume that most card services for a Java Card are applet proxies, but not
all. For example can a generic VisaCashCardService operate on the card, if the
card has a compatible applet installed.
14.4.2
Controlling Our Sample Card Applet through OCF
Let us come back to the card applet that we have developed in 14.3.
For this applet, BizCardApplet. java, we now create a proxy that
we call BusinessCardProxy . java.
Before we dive down into an individual class, let us take an over-
view of the classes involved (see Figure 14.4).
BusinessCardProxy extends the class AppletProxy. Every
Appletproxy has an AppletID, which uniquely identifies its appli-
cation. Appletproxy does all handling of that applet AID including
passing it to the methods communicating with the card. Applet-
Proxy and AppletID are both found in the package open-
[Link].
AppletProxy extends BasicAppletCardService. The main BasicApplet-
responsibility that we give this base class is to actually send and re- CardService
ceive the APDUs. Here we also make sure that the correct receiving
BaslcAppletC..clServlce
et
# getCardState()
# Inlaallze()
- selectApplet() ca-d
AppIetlD # sendConnandAPDU()
(from appIet) + sendConnandAPDU()
# sendVeritiedAPDU()
+ ca-clnserted()
+ ca-dRemoved()
BuslnessCwd()
+ ca-dlnserted()
+ ca-dRernoved()
+ getAd*essO
# getBuslnessC..dState()
+ dose()
buslnessCardPrmcy
+ get••••• o + getBUSlnesslnfa()
#getReld() + setBuslnesslnfa()
# Initialize()
# performCHVO
# setRelcI()
+ set..... ()
[Link]
Class BusinessCardProxy
Class BusinessCardProxy is responsible for acting as a proxy to
the card applet BizCardApplet.
First we define several constants for BusinessCardProxy ob-
jects, like return codes and the numbers of the business card entries
name, title, and so forth. We also define a command and response
APDU as instance data that we can reuse to avoid object creation
overhead.
II Return codes.
protected final static int OK = Ox9000;
II Field identifiers.
protected final static int NAME = 0;
protected final static int TITLE = 1;
Next, we create public methods to get and set the business card
data fields, like getAddress (), setAddress (String), and so
forth. These public get/set-methods internally use the protected
methods getField () and set Field (... ) :
CardServiceException {
try {
allocateCardChannel() ;
Next, we set all parts of the command APDU. First, we empty our
reusable APDU by setting the length to O. Then we add the class and
instruction bytes. Next, we append PI containing the index what
business card entry to set. Then, P2 contains the info, what field of
that entry to set.
ResponseAPDU response
sendCommandAPDU(cc,
BUSINESS CARD_AID, setFieldAPDU);
finally
releaseCardChannel() ;
--
14.4 Using OCF to Work with Card Applets - 249
accessed by their application identifier as the key (see Figure 14.3).
The search key for our applet is BUSINESS _CARD_AID.
In getBusinessCardState (CardChannel) we assume that
the applet state has already been set up during the initialization of this
proxy and that the card state has been set up during the initialization
of its base classes.
try {
II Allocate the card channel. This gives us exclusive
II access to the card until we release the channel.
allocateCardChannel() ;
II Get the card state.
Hashtable cardState = (Hashtable)
getCardChannel() .getState();
Next, we retrieve the state for our applet and applet proxy from the
card state. If this applet state is not yet set, we create a new Bus i-
nessCardState object. We set it to reflect that the PIN verification
(or cardholder verification, CRY) has not been successfully done yet.
finally (
releaseCardChannel() ;
Now we have discussed the main parts of our business card applet
proxy. You might want to review the entire source, which you find in
samples. business. BusinessCardProxy. j ava, which you get
from [Link]
Our proxy's base class AppletProxy is so straightforward that
we will not cover it here. Of course, you can find it in the OCF distri-
bution in package opencard. opt. applet.
Moving upwards in the inheritance tree one more time, we find a
class that has a few details that we should look at in the following.
[Link]
Class BasicAppletCardService
The main purpose of the BasicAppletCardService is to offer to
its derived proxy classes a convenient method to send APDUs to their
corresponding card applets. It is a service of this class to determine if
a selection command must be issued first, or if the receiving card
applet is the currently selected applet. In this way the overhead of un-
necessary selection commands is avoided.
All instances of the class BasicAppletCardService associated
with the same physical card share a common object of type Card-
State to ensure a consistent view including keeping the information
on the active applet. BasicAppletCardService uses an applica-
tion identifier for this CardState that can not collide with an appli-
cation identifier of a real applet and applet proxy:
Using the proxy state mechanism also for the state of the Basic
AppletCardService we access the same state object for the same
card, no matter how many instances of proxies exist.
The card state object is correctly set up in initialize (... ) with
the same logic that we have used in class BusinessCardProxy.
send- The method sendCommandAPDU (... ) is for the derived classes the
Command- primary method to call. We have seen it being called in the method
APDU(.. .) set Field (... ) of BusinessCardProxy2. Despite of its importance
it is short:
selectApplet(channel, appletID);
return [Link](commandAPDU);
if (([Link]() == null)
I I (![Link]() .equals(appletID)))
AppletInfo info =
selector_.selectApplet(channel, appletID);
AppletID previouslySelectedAID
= state. setSelectedAppletID (AppletID) ;
if (previouslySelectedAID != null) {
Hashtable cardState = (Hashtable) [Link]();
AppletState appState = (AppletState) ([Link](
previouslySelectedAID)) ;
[Link]() ;
[Link]
Class BusinessCardState
For our business card applet we are interested only in one state in-
formation. We need to know whether a valid PIN has been entered
after this applet became active. This information is stored in the boo-
lean variable chvPerformed_. The variable is set to false in
method appletDeselected () .
Class BusinessCardState is short enough that we can show the
pure code (with all commentary removed) as a whole:
[Link]
Class BusinessCard
Class BusinessCard is responsible for storing business card infor-
mation on the card and retrieving it from there. It takes responsibility
for all necessary subtasks, such as starting and closing OCF, reacting
on card insertion and card removal events, and working with the card
applet using a BusinessCardProxy.
The techniques used in class BusinessCard are not Java Card
specific, but standard OCF application programming as we have
shown it in Chapter 12. Therefore we do not discuss the source code
here. You can find it in BusinessCard. java. This file is con-
tained in the complete source code for the business card sample pro-
gram, which we provide as package samples. business in the
sample code archive on [Link]
As a historical note, the code has been originally developed and
tested with OCF version 1.1.1 as demonstration for the first edition of
this book. For OCF version 1.2 several of the classes were promoted
into the new OCF package opencard. opt. applet. For the second
edition of this book the code was tested with OCF 1.2 and with the
IBM Java Card "JCOPlO" [IBMJCOI], which implements the Java
Card 2.1.1 specification.
15.1
Introduction
The tasks related to the management of smart cards and card applica-
tions can be categorized in three different domains: management of
cards, management of applications, and management of keys. The
term card management refers to the functions that are required to al-
low for management of multi-application smart cards in a multi-
enterprise environment. Application management refers to the func-
tions required for management of applications for multi-application
smart cards. Key management refers to management of cryptographic
keys, key distribution, and security policies.
In a complex smart card system, there are usually three kinds of man-
agement systems: Card Management Systems (CMS), Application
Management Systems (AMS), and Key Management Systems
(KMS). The different management systems within a smart card sys-
tem may be owned by a single entity in simple systems. In more
complex smart card systems, there are several cooperating entities
running their own systems: The card issuer owns the card manage-
ment system and each application provider owns his own application
--
15. 1 Introduction - 255
management system. The key management system is usually run in a
trust center by a trusted third party. In the following sections we will
explain card, application, and key management systems in more de-
tail.
15.1.1
Card Management Systems
15.1.2
Application Management Systems
--
15. 1 Introduction - 257
15.1.3
Key Management Systems
15.2
Using OCF for Card and Application
Management
In this section we describe how the OpenCard Framework can be
used to perform administrative tasks required for card and application
management. The card life cycle can be subdivided into three major
phases: The card issuance phase, the card usage phase, and finally the
disposal of the card. Usage of OCF in the card issuance phase would
be possible, but usually card initialization and personalization is done
in closed factories using proprietary hardware and software. Usage of
OCF is particularly advantageous when performing card or applica-
tion management tasks during the usage phase in a smart card's life
cycle.
While traditional smart cards did not allow for adding or removing
applications in the usage phase, today's advanced smart cards offer
this possibility. They provide the technical prerequisites that are
needed on the card side - now there is a need for an infrastructure that
allows for usage of these features and makes download of applica-
tions via the network possible. In this chapter, we describe an archi-
tecture that can be used to implement card and application manage-
ment functions and we present two concrete examples - post-
issuance application download and decentralized personalization of
an application.
15.2.2
Security
--
Java Card - Security Domain Install Script
--
Sucess Notification
Request Application
-- -.. ..
-
Get Application
--
Application Install Script
Application Install Script
-...
Sucess Notification
---
--
Sucess Notification
--
First, the client needs to check whether the application provider's
security domain is already present on the card. If this is not the case,
the client requests the download of the appropriate security domain
and obtains an install script from the card management system, i.e. a
sequence of card commands that must be exchanged with the card to
install the security domain. After successful installation of the new
security domain on the card, the client notifies the card management
system.
After installation of the security domain, the card is ready for
download of the application itself. The client requests the application
download from the application management system. As a response,
the client receives an application install script, i.e. a sequence of card
commands that need to be exchanged with the card to install the ap-
plication on the card. After successful download of the application,
the client notifies the application management system and the card
management system.
Figure 15.2:
Infrastructure for
Tier-3 Decentralized Card
Administration and
Personalization
Tier-2
Tier-1
--
15.2 Using OCF for Card and Application Management - 261
Figure 15.3:
A Possible
Software Setup
for Web Based
Card and
Application
Management
Enterprise
Java Beans
WebServer
[Link]
15.2.4
Post-Issuance Application Download
[Link]
Post-Issuance Application Download
to File System Cards
Applications on file system cards, as defined in ISO 7816 and EMV,
usually consist of an application directory (ADF) that contains sev-
eral application files (AEFs) and - if required - key files and pass-
word files. If there is a directory file (EF_DIR) on a file system card,
applications may have entries in that file. Thus, downloading an ap-
plication to a file system card in general consists of the following
steps:
15.2.5
Post-Issuance Application Personalization
Logon ..Check
Figure 15.4:
The Simplest
Response Credential
Get Input, Case of
Card Type Post-Issuance
and Challenge
Input, Data and Card Type, ChallengL
Generate
Application
Personalization.
~
APDU 1-n,
Pers. Script Build Script
Send APDU
1-n to Card
-
Confirmation
Update
Database
Challenge ..Generate
Send APDU n APDU APDU n
Confirmation
to Card. Update
Database
16.1
Device Profiles
Table 16.1:
Big Devices Medium Small Devices
Device
Devices
Categories
RAM > 1024KB 256-1024 KB < 256 KB
ROM > 1024KB 256-1024 KB < 256 KB
Java Subset Personal Java Embedded Java Embedded Java
Threads Yes Yes No
Comm. TCPIIP, SSL TCPIIP, SSL WAP or similar
Examples Screen Phones, Intelligent Card Small Payment
Kiosks, Wear- Terminals, Terminals,
able Computers, Set Top Boxes Mobile Phones
Telematics
units
Figure 16. 1:
The Subsets of
Medium the OpenCard
Subset Framework for
Embedded
Devices
Small
Subset
[ [Link]
Card Reader
--
16.2 OCF for Embedded Devices - 271
16.2.2
Footprint Statistics
A.1
The IBM MultiFunction Card
The mM MultiFunction Card belongs to the kind of smart cards that
are most widely used today - file system oriented cards. The data on
file system cards is organized in directories and files. For each direc-
tory and for each file, access conditions can be specified for several
access modes like READ, UPDATE, INCREASE, DECREASE,
CREATE, DELETE etc. In addition to unsecured access to a file, a
file system smart card can allow access to files and directories only if
the specified access conditions like card holder verification, external
authentication, secure messaging or encryption are satisfied by the
application.
The card that comes with this book is an mM MFC 4.1, which is
the entry-level version within the mM MFC card family. It is a file
system card with additional increase and decrease commands that can
be used to implement counters on the card. It uses the DES or Triple
DES algorithm for protecting data. The MFC 4.1 has an improved
file system, an extended command buffer and is available with 2, 4, 8
or 16 kb of EEPROM.
The flagship of the mM MFC family is the MFC 4.3. This card
has a cryptographic coprocessor and does not only support the DES
algorithm, it also supports RSA and DSA for generating and verify-
ing digital signatures. A special feature of this card is that it can even
generate key pairs on the card.
Figure A. 1: MF
The File Structure
of the Card that H EF CHV1
EF CHV2
Comes with this
EF_KEY
Book
EF_AUT
EF DIR
The files EF_ CHV t and EF_ CHV2 hold passwords and unblock
passwords for these passwords along with initial and current retry
counters. These passwords are used to protect files on the card
against access without authorization by the cardholder. The file
EF_KEY holds cryptographic keys and related retry counters for use
for external authentication (see Section 4.2.1), secure messaging, and
encryption (see Section 4.2.3). In our example, EF_KEY holds a sin-
gle key that is used as a global administration key. The file EF_AUT
holds a key to be used for internal authentication (see Section 4.2.2).
_ Always
The access condition Always means that access is possible by
simply sending the appropriate command APDU.
_ Cardholder Verification lICardholder Verification 2
Cardholder Verification 1 and Cardholder Verification 2 mean
that the first password or the second password respectively must
be provided to the card with the VERIFY command before
sending the access command to the card.
_ Protected with Key 0
Protected with Key 0 for CREATE, DELETE and UPDATE
means that a Message Authentication Code (MAC) must be ap-
pended to the appropriate Command APDU before sending it to
the card. For READ, Protected with Key 0 means that the card
will return the data with an appended MAC that is calculated
with key O.
_ Enciphered with Key 0
The access condition Enciphered with Key 0 for CREATE,
DELETE and UPDATE means that a MAC must be appended
to the appropriate Command APDU and that the resulting
APDU must be enciphered with Key 0 before sending it to the
card. For READ, it means that the card returns data appended
by a MAC and in enciphered fonn.
_ Never
The access condition Never means that access is possible under
no circumstances.
--
A.2 The File Structure on the Card - 277
When reading the listing below, please keep in mind that it is only
intended as a simple example to be used by demos and sample pro-
grams and should not be taken as a template for designing real-life
file system layouts.
Directory MF (Ox3FOO)
AC Create: Protected with Key 0
AC Delete: Protected with Key 0
A.3
Accessing the Card
As mentioned above, the card that comes with this book is an IBM
MultiFunction Card Version 4.1 with 8 kb EEPROM size. This card
is supported by the reference implementation of the OpenCard
Framework that is available on [Link] To access
this book's card, you need to make the following entry in the open-
card. properties file:
[Link] =
com. ibm. opencard. factory. MFCCardServiceFactory ...
This entry specifies the factory that can provide the appropriate
card service for the IBM MFC cards (including MFC 3.5, MFC 4.1
and later) known to the OpenCard Framework.
--
A.3 Accessing the Card - 283
B Useful Web Sites
Gemplus
[Link]
Gemplus is one of the leading providers of smart cards and smart
card readers.
This web site contains information about smart cards in general
and about products from Gemplus of course. You can also order
smart cards like Gemplus' GemXpresso online.
Gemplus Developers
[Link]
This web site contains the latest information for developers, like a fo-
rum, latest trends, and current drivers. It also provides access to
OpenCard CardTerminals and CardServices for hardware from
Gemplus.
IBM
[Link]
IDM Pervasive Computing provides a wide range of technology and
solutions for pervasive computing and smart cards. IDM is commit-
ted to open standards and has developed the OpenCard Framework
reference implementation in close coordination with other members
of the OpenCard Consortium.
On this web site, you can find an overview of the technology and
solutions IDM offers in the area of pervasive computing and smart
cards.
Mondex
[Link]
This is the web site of Mondex, the organization behind the Mondex
electronic purse. Here, you can find information how Mondex works,
which devices are available to be used with Mondex and how it can
be used for payments over the Internet.
OpenCard
[Link]
OpenCard Framework provides a Java application-programming in-
terface to smart cards. It is supported by the OpenCard Consortium,
which was founded by members from the IT industry, smart card in-
dustry, and payment systems industry. The OpenCard Framework
reference implementation is publicly available free of charge.
On this web site, you can find the current version of OpenCard
Framework with source code, binaries, documentation, and samples.
The OpenCard Consortium also maintains a discussion list for inter-
ested parties.
PKI Survey
[Link]
On this web page you can find excellent links to infonnation on pub-
lic key infrastructure (PKI) and cryptography.
PC/SC
[Link]
The PC/SC workgroup specified an interface to smart cards in a
Windows environment. Microsoft offers an implementation of this
interface for the current versions of the Windows operating system.
On this web site, you can find the PC/SC specifications.
Schlumberger
[Link]
Schlumberger is a leading smart card provider.
On this web site, you can find information about Schlumberger
products and solutions.
Visa
[Link]
Visa International is the leading credit card organization with over
21.000 member financial institutions. Visa has founded the Open-
Card Consortium and other industry organizations. Visa developed
VisaCash and the Visa Open Platform specification.
In the 'Media Center' section of Visa's web site, you can find and
download information about Open Platform, VisaCash, and other
Visa technologies.
[Booch97] Grady Booch, Jim Rumbaugh, and Ivar Jacobson, Unified Modeling
Language User Guide, Addison Wesley, December 1997,
[Link]
[ChenOO] Zhiqun Chen, Java Card ™for Smart Cards: Architecture and Pro-
grammer's Guide, Addison-Wesley 2000
[DIE99] The Internet Society The TLS Protocol Version 1.0, 1999,
[Link]
C Bibliography - 289
•
-
[DIF76] W. Diffie and M.E. Hellmann, Multiuser Cryptographic Techniques,
Proceedings of AFIPS National Computer Conference, 1976, pp. 109-
112.
[GAM95] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design
Patterns - Elements of Reusable Object Oriented Software, Addison-
Wesley Publishing Company, 1995
[Jain99] Anil K. Jain, Ruud Bolle and Sharath Pankanti, Biometrics - Personal
Identification in a Networked Society, luwer Academic Publishers 1999
290 • C Bibliography
••
[MIL86] [Link], Use of Elliptic Curves in Cryptography, Advances in Cryp-
tology - Crypto '85 Proceedings, Springer-Verlag, 1986, pp. 417--426
[NIS94] National Institute of Standards and Technology, NIST FIPS PUB 186,
Digital Signature Standard, U.S. Department of Commerce, May 1994
[RANOO] W. Rank!, W. Effing, Smart Card Handbook, 2nd edition, John Wiley
and Sons, 2000
[RlV78] RL. Rivest, A. Sharnir, and L.M. Adleman, A Method for Obtaining
Digital Signatures and Public-Key Cryptosystems, Communications of
the ACM, v. 21, n. 2, Feb 1978, pp. 120--126
[RlV79] RL. Rivest, A. Sharnir, and L.M. Adleman, On Digital Signatures and
Public-Key Cryptosystems, MIT Laboratory for Computer Science,
Technical Report, MITILCSITR-212, Jan 1979
--
C Bibliography - 291
[Smith97] Richard E. Smith, Internet Cryptography, Addison Wesley 1997
[TOW02] Towend, Robin c., Smart Card News: Finance: History, Development
& Market Overview, 2002,
[Link] .[Link]/articles/[Link]
292 . C Bibliography
••
D Glossary
D Glossary • 293
•
•
• Digital Signature - encrypted digital fingerprints of data, ensur-
ing data integrity and authenticity
• DSA - Digital Signature Algorithm, a public-key algorithm that -
unlike RSA - is only intended for digital signatures, standardized
in the Digital Signature Standard (DSS).
• EEPROM - Electrically Erasable Programmable Memory. This is
the typical persistent storage medium used in smart card chips.
• EMV - This acronym from the three initial letters for Europay,
MasterCard International, and Visa International is often used in
the smart card industry to refer to "EMV'96: ICC Specifications
for Payment Systems".
• External Authentication - cryptographic protocol proving the
authenticity of an external entity to the smart card.
• Hash - a digital fingerprint of data. Hash algorithms are often
used in conjunction with Digital Signatures.
• ICC - Integrated Circuit Card, a synonym for chip card.
• Initialization of smart cards - in mass production of smart cards,
this is the first step where data common for all cards of a lot is
written to the cards.
• Internal Authentication - cryptographic protocol proving the
authenticity of a smart card to an external entity.
• ISO 7816 - The International Standard Organization's standard
relevant for smart cards.
• Java Card - a smart card that has the capability of running Java
programs using a restricted command set and library on-card.
• Java Card Framework - Applets on a Java Card use the Java
Card Framework as standard programming interface.
• Java Card Runtime Environment (JCRE) - The execution en-
vironment for Java Card applets.
• JVM - Java Virtual Machine. The execution environment for Java
programs. The JVM interprets the Java byte code. The JVM also
enforces security restrictions for the executed code.
• Memory Card - a credit card sized plastic card with a memory
chip.
• Off-Card Code - Code outside of running in card terminals or
computers.
• On-card Code - Code running in a smart cards processor. See
also Off-Card Code.
294 • 0 Glossary
••
• OpenCard - standard for smart card access on Java platforms.
• PC/SC - standard for smart card access on Windows platforms.
• Personalization of Smart Cards - in mass production of smart
cards, this is the step where card individual data is written to the
cards.
• PKCS - The Public-Key Cryptography Standards are a series of
standards initiated by RSA to foster interoperability of crypto-
graphic systems. Especially PKCS#11 and PKCS#15 are relevant
for smart cards.
• Privacy - the property of not being readable by an enemy.
• Private-Key - Private-Keys are used in public-key cryptosystems
to generate digital signatures or decrypt messages. Private-keys
must be kept in secret to assure that only the owner can use them.
• Public-Key Algorithm - asymmetric cryptographic algorithm,
where one key is revealed to the public and one key is kept in pri-
vate. Public keys are used for encryption of data or validation of
digital signatures while private keys are used for decryption of data
or generation of digital signatures.
• Public-Key - Public-Keys are used in public-key cryptosystems to
verify digital signatures or to encrypt messages. Public-keys are
usually published so that anybody can use them.
• RAM - Random Access Memory
• Response APDU - An APDU sent back by a smart card after re-
ceiving a command APDU.
• ROM - Read Only Memory
• RSA - Most important asymmetric cryptographic algorithm. The
acronym stands for the inventors Rivest, Sharnir and Adlemen.
• Secret Key - A key for a symmetric algorithm, that needs to be
kept in secret to assure security of the system in which it is used.
• Servlet - A small java program that can be deployed and run on
an Java-based application server.
• Smart Card - a credit card sized plastic card with a computer
chip.
• Symmetric Cryptographic Algorithm - cryptographic algo-
rithm, where the same key is used for encryption and decryption.
Examples are DES and IDEA.
• Tamper Proof - Tamper proof devices are built so that they loose
all stored information when somebody tries to tamper with the de-
vice.
o Glossary • 295
•
•
Elndex
3 application selection 79
ApplicationManagement-
3-tier architecture 215 CardService 97
approval of cards and terminals
78
A Architecture Overview 93-100
AAM 33 ARPAnet 35
Abstract Syntax Notation (ASN) asset protection 90
27 association 92
acceptance device 69 asymmetrical key 44, 46
access condition 30, 244 ATR 26,76,77,79,95, 120
access conditions 277 attacks 21
access control 17 authentication 15, 36, 43-46
access modes 275
addCTListener (... ) 204
address line 21
B
Administration System 42 Bank of America 42
Advanced Encryption Standard 55 beginMutexO 150
AES 55 benefits 13, 15-16
AID 31,76,234,243 biometric identification 72-73
anonymity 39,40 BizCardApplet 247
answer to reset (ATR) 26,76,77, BizCardRecord 240
79,95 Booch 92
APDU 24--26,87, 120,234 browser security 188
applet 233-34, 236-42 building access 15
applet proxy 243-45 bulk encryption services 80
appletDeselected() 253 BusinessCard 247,254
AppletProxy 245 BusinessCardProxy 245,
Application Abstract Machine 247-51
(AAM) 33 BusinessCardState 253-54
Application Access 148 byte array 236
application identifier (AID) 31, byte code converter 234
76,234,243
application management 94
Application Protocol Data Unit
c
(APDU) 24--26, 87, 234 cap file 234
application provider 93 card acceptance device (CAD) 69
E Index • 297
••
card applet 233-34 CardServiceRegistry 96,
card applet proxy 243-45 149, 152, 196
card channel 243, 248 CardServiceRuntime-
Card Executive 32 Exception 165, 166
card holder verification 123 CardServiceScheduler 95,
card issuer 90, 93 96, 154, 158
Card Manager 83 CardServiceUsage-
card operating system provider Exception 166
89,93 CardTechiSecurTech 87
card service scheduler 243 CardTerminal 95,96, 115,
card state object 244 118,132,135,196
card terminal 89 CardTerminalEvent 97,
CardChannel 99, 154, 158 117, 150,201
CardExecutiveCardSer- CardTerminalException
vice 245,251-53 122
CardExecutiveCardState CardTerminalFactory 96,
250 115,118,143
CardFile 97,170,199,201 CardTerminalIOBlender
CardFileInfo 169 125
CardFileOutputStream CardTerminalIOControl
210 124
CardFilePath 171,182 CardTerminalRegistry 96,
cardholder 13, 14, 16, 17,22 117,149,196,204
CardHolderVerification card-to-card payment 220
GUI 162 card-to-card payment schemes
CardID 95,119,149 218
CardIDFilter 151 CardType 160
cardInserted () 117,141, Carte Bancaire 14
203,205--6 cash handling 15
CardNotPresent- CBC 54
Exception 122 CEPS 38,43
cardRemovedO 117,141,207 certificate 46
CardRequest 151,199 certification 71, 72
CardService 94,95, 112, 145, challenge-response 44
156,175,243 challenge-response protocol 59
CardServiceException Chipknip 38
165 CHVControl 124
CardServiceFactory 96, CHVDialog 155, 159, 162
112,158,159-61,196 CHVEncoder 125
CardServiceImplemen- chvPerformed 253
tationException 165 Cipher 235
CardServiceInability- Cipher Block Chaining (CBC) 53
Exception 165 CLA 25
CardServiceInterface class byte (CLA) 25
166 class libraries 234
CardServiceInvalidCre- Clearing System 42
dentialException 166 clock signal 19
CardServiceInvalidPa- close () 201
rameterException 166 cold reset 19
CardServiceOperation- Command APDU 24
FailedException 165 CommandAPDU 121
298 • Elndex
••
Common Electronic Purse development process 23-24
Specification (CEPS) 38, 43 device driver 115
Common Object Request Broker DF 28
Architecture (CORBA) 242 digital money 13
CommunicationError- digital signature 35,36,46-47,
Exception 122 80,95,172,202-14
compiler 234 Digital Signature Algorithm
Concentration Point 42 (DSA) 57
configuration 148 digital signatures 216
configuring 195 digital token 37
contact card 17, 69 direct card-to-card transfer 40
contact unit 69 display 70
contactless card 16, 17 distributed payment system 227
CORBA 242 Distributed Payment System 229
CPU 17 DSAParams 178
createEventsForPresent DSAPrivateKey 178
Cards () 204 DSAPublicKey 178
Credential 176, 183 dynamic class loading 31
CredentialBag 184
CredentialStore 184
credit card 13, 15
E
Crypto Service Provider 80 e-business 35-49
crypto token 47 ECB 53
cryptographic algorithms 51 e-commerce 36
cryptographic coprocessor 18,70 EEPROM 17
cryptographic protocols 59 EF 28
cryptography 51 electrical characteristics 78
CT/ST 87 electromagnetic radiation 75
CTListener 97,150,203,204, electromagnetic wave 17
247 Electronic Code Book (ECB) 53
Cyclic Record 29 electronic commerce (e-
commerce) 36
D electronic contract 35
electronic purse 13, 15, 35,43,
Danmont 38 37-43, 71
data integrity 215 electronic signal 76, 77
DataOutputStream 210 electronic ticket 35,48
debugging 105 elementary file (EF) 28
decrypt 14, 24 elliptic curve algorithms 58
decryption 45 e-mail 46
dedicated file (DF) 28 embossed printing 14
DefaultCHVDialog 162 EMV 43,77-79,94
denotes inheritance 92 encrypt 14, 24
DES 52 encryption 35, 36
DES modes 53 endMutex () 150
deselect () 236 error detection code (EDC) 128
DESSecureCredential 185 Euro 38
destroy () 232 expiration date 46
development cost reduction 90 export restrictions 177
development kit 24 external authentication 30, 59
--
E Index - 299
F iButton 20
ICC 79
fabrication 21 ICC Resource Manager 80
file identifier 28 ICC Service Provider 80
file structure 276 ID-OOO 20
file system 24 ID-1 20
file system smart cards 28-30 identification card 14
FileAccessCardService IFD Handler 80
169,199,203 imprint 14
FileSystemCardService industry initiative 75-83
95, 169 init () 230
Fixed Record 29 initialization 22, 93
fraud 14,48 initialize (... ) 250
INS 25
install (... ) 235,241
G installing 195
garbage collection 31 instruction byte (INS) 25, 237
GCR410 137 integrated circuit 14
GCR410CardTerminal 136 Integrated Circuit Card (ICC) 79
GCR410TIProtocol 133 interface device (IFD) 69,79
GeldKarte 15,38,39-40,219 Inter-industry commands for
getAddress () 247 interchange 76
getBusinessCardState(C inter-industry security
ardChannel) 249 architecture 77
getCardService (... ) 201, internal authentication 60
206 International Organization for
getField(APDU) 241 Standardization (ISO) 75
get Length () 209 Internet 35
getpath () 202 internet brokerage 215
GlobalPlatform 82-84 internet customer terminal 227
ground connection 19 Internet Stockbroker demo 214
GSM 15,26 interoperability 78
Interoperability Specification for
ICCs and Personal Computer
H Systems 1.0 (PC/SC) 79
handshake protocol 67 InvalidCardChannel-
hardware 13,16-22 Exception 166
hardware security 21 InvalidSlotChannel-
hashing 80 Exception 122
HexString 102 ISO 7816 75,78
history 87 ISO 7816-1 75
home-banking 15 ISO 7816-10 77
hybrid algorithms 59 ISO 7816-2 19,76
hybrid smart card 17 ISO 7816-3 26,76
ISO 7816-3 Amendment 1 76
ISO 7816-3 Amendment 2 76
ISO 7816-4 24,26,76
ISO 7816-5 76
IBM 87
ISO 7816-6 77
IBM JCOPlO 254
ISO 7816-7 77
IBM MFC family 275
ISO 7816-8 77
300 • Elndex
•
•
ISO 8824 27 KeylmportCardService
ISO 8825 27 172
ISO file system CardService KeyRef 177
169
ISO standards 77
IS07816 (interface) 234
L
ISOCommandAPDU 126,127 Lc 25
ISOException 239 Le 25
issuing 93 length byte 25
life cycle 234
J lifetime of the applet 235
Linux 105
Jacobson 92 loadProperties() 196
Java Card 24,31-32,233-54 login 44-45
Java Card 2.1 236 loyalty 48
Java Card applet 31 loyalty scheme 15
Java Card emulator 234
Java Card Forum 31
Java Card Framework 234-35
M
Java Card Runtime Environment MAC 30,54
31,32 magnetic stripe 14, 15,20,72
Java Card security framework makeTransient 235
235 management board 89
Java Card simulation environment manufacturing process 22
234 Maosco 32
Java Card specification 31 mask 24
Java Communications API 131 mass-transit 15, 17
JavaNativeInterface 131 master file (MF) 28
Java sandbox 189 mechanical characteristics 78
java. home 110 mechanical contacts 19
java. lang 234 MEL 32
java. securi ty 178 memory 17
[Link] 234 memory card 16-17
[Link] 235 merchant card 219
j avacardx. crypto 235 message authentication code
j avax. comm 131 (MAC) 30,54,61
JCSystem 234,235 method 92
JDK 195,234 MF 28
MFC 30
K MFCCredentialStore 185
MFCSignatureService 182
Key 178 microcomputer 13
key generation 80 micropayment 37
key handling 172 microprocessor 17
key management 80 microprocessor card 16-17
KeyEncryption 235 MicrosoftSystemAccess
KeyFile 177 108, 190
KeyGenerationCard- mobile phone 20
Service 172 module 21
module insertion 22
--
E Index - 301
Mondex 38, 40 OpenCard. terminals 149,
Multi-Function Card (MFC) 30 196
multiplicity 92 [Link] 107
Multos 24,32-33,40 [Link]-
Multos Executable Language Only 107
(MEL) 32 OpenCardConfiguration-
Provider 104, 196
OpenCardConstants 101
N OpenCardException 101
native code 195 OpenCardPropertyFile-
NC 87 Loader 110, 149, 197
NetscapeSystemAccess OpenCardProperty-
108, 190 LoadingException 104
Network Computer (NC) 87 OpenCardRuntime-
network login 44-45 Exception 101
non-repudiation 36,216 Optional CardService exceptions
167
302 • Elndex
•
•
plastic card 13, 21 Remote Method Invocation
poll () 138, 141 (RMI) 242
Pollable 117 reset signal 19
portability 15 Response APDU 25
portable terminal 72 ResponseAPDU 121
post-issuance 83 RID 76
power 19 Rijndael 55
power consumption 17 ROM 17,24
PowerManagement- root certificate 46
Interface 126 RSA 56
prepaid phone card 16 RSASignCredential 179
preparing your system 195 Rumbaugh 92
PrimaryCardService- RuntimeException 234
Factory 161
privacy 36, 39,46
private key 18,45,46,56
s
Pri vateKey 178 SAM 37,175
PrivilegeManager 189 sample application 195
process (APDU) 236 secret 14
production 18 secret keys 15
properties 196--98 secure 14
protocol layer 24 secure access 35,43--46
protocol type selection 76 secure authentication 35
Proton 38,41 secure channel 83
Proton WorId 41 secure messaging 27,61, 175
Provider Security Domains 83 secure session 45
proxy 243--45 secure storage 15
public key 36,43, 45, 46, 56 secure token 15,216
public key algorithms 56 SecureService 184, 187
public network 15 security 15, 83, 175
public transport 17 Security Access Module (SAM)
PublicKey 178 37
purse card 219,220 security issue 35
PurseCardService 95 security requirements 16
SecurityDomain 184
Q SecurityManager class
31
Quick 38 SELECT APDU 236
select () 236
selectApplet (... ) 252
R sendBytesLong (... ) 241
RAM 18 server login 44--45
Ravensburg 39 service layer 145
reader 23, 26, 195 Service Payment Terminal 42
reference implementation 93 service () 231
register () 235 servlet 218,229,230
registered application provider session key 45, 66
identifier (RID) 76 setAddress(String) 247
registry 95 setCHVDialog (... ) 207
relationship 92 setField (... ) 239,247
--
E Index - 303
setOutgoingAndSend (... ) T
239
setOutgoingLength T=O 24,26-27,76
(short) 241 T=1 24, 26-27
setSystemAccess (... ) 109 T=14 76
SHA-l 58 TIBlock 128
shutdown () 149, 199 TlException 129
signature 18,38 TIProtocol 128, 133
Signature 179 Tag 114
signature verification 172 Tag-Length-Value (TLV) 27,
SignatureCard 203 113
SignatureCardService tamper-resistant 14, 15
172,182 technical committee 89
signatureService 203 terminal 23,71-72,69-73
SignCredential 187 terminal vendor 89
singleton 152 TerminalCommand 126
slot 70, 96, 119 TerminallnitException
SlotChannel 98, 119, 154 122
Smart Card for Windows 24, TerminalTimeoutExcep-
33-34 tion 122
smart card key classes 181 testing of cards and terminals 78
Smart Card Toolkit for Visual tier 216
Basic 34 time-to-market reduction 90
Smart Card 95,148,199,203, TLS 45,67
247 TLV 27,113,114
SSL 45 toolkit 24
standard CardService trace 130
interfaces 168 TraceLevels 105
standards 75-83 Tracer 97, 105
start () 103, 148,204 Tracer. critical (String,
static electricity 75 Throwable) 205
status word 26 Tracer. info (String,
String 236 String) 205
structured card query language TracerEvent 106
(SCQL) 77 TracerListener 97, 106
supply voltage 19 trading protocol 226
SWI 26 transient array 235
SW2 26 transmission protocol 76
Swindon 40 Transparent 29
symbolic name 28 transport protocol 79
symmetric cryptographic triple DES 53
algorithms 52 trusted authority 46
symmetrical key 45 trusted channel 46
SymmetricCredential 187
synchronize 146
syslogO 105
u
system properties 196 UML notation 91
system property 107, 148 Unified Modeling Language
system resources 189 (UML) 92
SystemAccess 108, 190 URLClassLoader III
304 • Elndex
•
•
USB 69 web browser 108,188,229
user. dir 110 web server 218
user. home 110 WebSphere 229
Userlnteraction 126 white card 39
Windows 2000 82
v Windows XP 82
World Wide Web (WWW) 35
Variable Record 29 WWW 35
vendor independence 90
VerifiedAPDUlnterface
125, 155
x
Visa Cash 38,40,41-43 X-rays 21
voltage 76
w z
ZentraIer KreditausschuB (ZKA)
waitForCard( ... ) 150, 39
200-201 ZKA 39
warm reset 19
E Index • 305
•
•