Smart
Smart
Smart
Springer
Uwe Hansmann
Martin S. Nicklous
Thomas Schck
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.
http://www.springer.de
Springer-Verlag Berlin Heidelberg 2000, 2002
Originally published by Springer-Verlag Berlin Heidelberg in 2002
Softcover reprint of the hardcover 2nd edition 2002
Any references in this publication to Web sites are provided for convenience only and
do not in any manner serve as an endorsement of these sites. Springer-Verlag accepts
no responsibility for the content or use of non-Springer-Verlag Web sites specifically
mentioned in this publication or accessed through a Springer-Verlag Web site mentioned in this publication.
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.
Cover design: KiinkelLopka , Heidelberg
Typesetting: Camera-ready by the authors
Printed on acid-free paper - SPIN: 10866335
33/3142 GF 543210
Foreword
Foreword
--
The unfortunate incidents on September 11 th, 2001 have reminded 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
--
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", meaning in weeks instead of months. It shows us the merits of using open,
inclusive, proven standards developed by industry consortia to advance the state of the technology. It is about crossing the chasm
between the early adopters of smart card technology (mostly European and Asian telecommunication operators and banks) and the incumbent 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 because of the very principles guiding the authors in their development
work. However, this book goes beyond the basic technology foundations: 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 indispensable that the OpenCardsM and Java technologies explained
here, be preceded and integrated with a detailed explanation of existing smart card hardware and software platforms, as well as existing 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 implementations of smart card capable products.
Patrice Peyret
Director, Sun Microsystems Inc.
Consumer & Embedded Platforms
August 1999
V/II
IX
The key characteristics for smart cards in today's world are security, ease of use, mobility, and multi-functionality.
They are thus geared/predestined to become the next major IT
platform. And they are going to revolutionize the business world
over the next few years. Many smart-card applications are today
being implemented - from citizen ID cards to health cards, electronic purse cards, and network access cards. It is widely accepted
that nearly all organizations will sooner or later need to assimilate
smart cards into their routine business processes.
This book is the first to describe - besides the pure smart card
technology - the complete end-to-end system approach. The complete scenario, from the standards involved to the programming capabilities required, is dealt with, and in a way that is easy to understand.
This book complements the smart-card application suite. It was
written to enable readers to take over an active role in the software
development of smart-card applications without the necessity of
having to go into the bits and bytes of the card itself.
I'd like to thank the authors for this new approach in addressing
smart-card-related technology, and I wish all the readers much fun in
developing their first application!
Sabine Schilg
Business Line Manager
IBM Pervasive Computing Solutions
August 1999
Table of Contents
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
Table of Contents
--
XI
XII
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
Table of Contents
Part II
OpenCard Framework .................................................................... 85
7
7.2
7.3
7.4
7.5
8.2
8.3
Table of Contents
XIII
10
11
11.3
Part III
Smart Card Application Development Using OCF .................. 193
12
XIV
Table of Contents
Table of Contents
--
XV
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
B Useful Web Sites ............................................................. 285
C Bibliography ....................................................... 289
D Glossary ........................................................................... 293
E Index ............................................................................. 297
xv,-
,--
Taible,ai Contents
Preface
Java. This second edition now covers the currently latest version of
the Open Card Framework: Version 1.2.
You can find all the material that you need to get started with the
OpenCard Framework on http://www.opencard.org/. The samples of
source code presented in this book are available for downloading on
http://www.opencard.org/SCJavaBooki. The smart card provided
with this book will help you to quickly get your first hands-on experience.
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.
Marginal notes
aid navigation
Index
Most of us no longer have the time to read an application development book cover to cover. Therefore, we have broken this book into
chunks that may be read in almost any sequence. In the following,
we give an overview of this book.
To allow for fast access to sections of interest or to sections that
you have already read and would like to review, we have included
eye-catchers at the margins. You can think of the marginal notes as
subheadings, which together with the headings form the fine-grained
structure of the book.
The index at the back should help you to quickly find the related
text using standard smart card terms.
Preface
Are you interested in smart card technology in general? To concentrate on the technology of smart cards, we suggest you to read
Part I in detail.
Are you interested in developing an application that uses smart
cards? To concentrate on smart card application development, we
suggest you to read Parts II and III in detail and to use Part I as a reference to look up the questions that might arise.
Part I
Chapter 1
Chapter 2
Chapter 3
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 different standards, algorithms, and protocols used.
Chapter 5
Chapter 6
Part II
OpenCard Framework
Parts II and m concentrate on the development of applications
that use smart cards. We base the development on Java and on the
OpenCard Framework (or "OCF' for short), the industry standard
for smart card access in a Java environment. In Part II, we cover the
OpenCard Framework's goals, concepts, architecture, and components in depth.
Preface
Introduction to OpenCard
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.
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
cuss these classes, which are relevant for smart card developers and
application programmers.
Part III
Chapter 12
Using OCF
First, we explain how to setup and configure OCF. Then we develop two sample applications, starting very simple and moving on
to the more complex.
You will learn what steps are necessary to enable an application
for the use of smart cards. You will appreciate how Java and OCF
make the programming task easy. The complete source code of our
example applications is available on the web.
Chapter 13
Chapter 14
Chapter 15
Preface
Chapter 16
For embedded devices and for computers with very limited resources, such as PDAs, screen phones or smart card tenninals, some
of the flexibility and complexity of OCF is not needed. For these environments, a trimmed-down version of OCF is a better fit. We describe this version of OCF in-depth in this chapter.
Appendixes
Part IV
The Card
Appendix A
Along with the book, you received a smart card that enables you
to immediately start practicing what you read. The examples that we
present in Chapter 12 "Using OCF", and which you can download
from http://www.opencard.org/SCJavaBookl, work with this card.
We give basic information about the card, an IBM Multi-Function
Card, and describe the data layout that we gave this card.
Appendix B
The OpenCard Framework documentation and reference implementation, the Java development kit, Java extension packages, smart
card reader drivers, and the Java Card specification are examples of
helpful material that you can immediately download from the web.
In this appendix, we share with you references to web sites,
which we found relevant to developing smart card applications in
Java. Of course, we cannot guarantee that all of the links will correctly work for as long as this book is available.
Bibliography
Appendix C
In this appendix, we reference the sources that we used. In addition, 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
Index
Appendix E
The index helps you locate terms used and explained in this book.
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 personalization support for customer projects.
Frank Seliger is currently security architect in IBM's Pervasive
Computing Division. In this role, he has worked on the architecture
of the OpenCard Framework. In 1978, Frank joined IBM, where he
has been active in various areas of software and firmware development. Since 1990, his focus has been on Object-Oriented software.
He worked on the IBM C++ collection class library that is shipped
with all IBM C++ compilers. As consultant in the IBM Object Oriented Technology Center, he coached Object-Oriented development
projects inside and outside of IBM. Together with his technology
center colleagues he captured his experience in "Developing ObjectOriented Software - An Experience-Based Approach", Prentice Hall
1997.
--
Acknowledgements
To work on the OpenCard Framework was a unique opportunity that
helped us gain and broaden our experience in smart card technology,
security technology, and object-oriented framework design. Without
that opportunity we could not have written this book. We would like
to thank the International Business Machines Corporation and, in
particular, its Pervasive Computing Division for having provided us
with that opportunity.
Numerous people furnished us with in-depth reviews of the book,
supported us, or provided us with their invaluable expertise. We are
indebted to Peter Bendel, Alexander Busek, A. J. Cave, Fernand De
Decker, Hermann Engesser, Gabi Fischer, Dorothea Glaunsinger,
Yolanda Gu, Klaus Gungl, Mike Hamann, Horst Henn, Stefan
Hepper, Reto Hermann, Dirk Husemann, Kyle Ingols, Thomas
Kohn, Christophe Muller, Ute Niedermeier, Silke Niemann, Patrice
Peyret, Gregor Reichle, Mike Rhodin, Sabine Schilg, Michael
Schilling, Jo Stark, Peter Trommler, and Dirk Wittkopp.
10
Preface
Part I
Smart Card Introduction
and Overview
In this chapter, we describe the different types of smart cards, explain their features and benefits, and give some recommendations on
when to use which type. We also introduce the smart card hardware
in this chapter. Since the focus of this book is on the software side,
we will provide only a basic introduction to hardware terminology
and concepts. If you have worked with smart cards before, you will
probably want to skip this chapter.
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
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 organization that issued the card had enough confidence in the cardholder 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.
13
Later, cards with embossed printing were introduced. The embossing made it possible to take an imprint of the cardholder information instead of copying it down manually. A few years later, the
magnetic stripe, which carries the account information and the name
of the ,cardholder, was introduced. This made the card machinereadable so the information could be electronically processed. Still,
one problem remained: Everybody with the necessary equipment
can read and write the data on the magnetic stripe. This led to a
fraud problem.
In 1968, a patent for an identification card with an integrated circuit was filed, and the smart card was born [RANOO]. The smart
card is a secure, tamper-resistant device. The data stored on the card
can be secured with a secret (usually a password), which is shared
between the cardholder and the smart card. Only the person knowing
the secret can use the card and the information stored on it.
Furthermore, with the ability to execute programs and commands,
the smart card became able to encrypt and decrypt information.
Figure 1.1:
Magnetic Stripe
Card and
Smart Card
14
1.1.1
The Benefits of Smart Cards
A smart card is a portable computer. Usually it has the shape and
size of a credit card. A smart card can be made physically tamperresistant. 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
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
PhYSical
improvements
Usage examples
I We will explain the advantage of smart cards for securing network and server access in Section 3.2.2 "Network- and Server-Login".
--
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
1.2.1
In the early days of the smart card, the card was not really smart, because 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 MicroprocessorCards
"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.
16
1.2.2
Contactless Cards
The host computer has to communicate with the processor on the
smart card to exchange information and commands. Communication
can take place either through the contacts on the card or via wireless
("contactless") transmission. A hybrid smart card combines both
technologies and is able to communicate with the host system using
either method.
Contactless smart cards are often used in situations requiring fast
transactions or where only a limited amount of data has to be exchanged. Examples are public transport systems or access control for
bUildings.
Contact cards are more difficult to use than contactless cards.
With a contact smart card, the cardholder has to take care that he inserts the smart card into the reader in the right way and with the right
orientation. Also, the contacts are occasionally the cause of failures
if they are damaged, worn, or just not sufficiently clean.
On the other hand, contactless cards also have some disadvantages. The power for the processor must be transmitted as an electromagnetic wave, which limits the maximum power consumption
of the processor and therefore the processor capabilities. Also, the
combination of analog and digital technologies makes contactless
smart cards more expensive than comparable contact smart cards.
Though today several mass-transit and access control systems
work with contactless smart cards [AmpeI98], [Chamb99], the technology is not as widely used as contact smart cards. In the near future this may change. Contactless cards may also be used for payment systems.
Advantages of
contactless
cards
Disadvantages
of con tactless
cards
1.2.3
The Computer on the Smart Card
As we explained earlier, the most important characteristic of a smart
card is that it contains a computer with CPU and memory. Today's
smart cards have approximately the same computing power as the
firstffiMPC.
The chip of a smart card (see Figure 1.3) consists of a microprocessor, ROM (Read Only Memory), EEPROM (Electrical Erasable
--
17
CPU
. 8 bit
EEPROM (16
Filesystem
Program files
Keys
Passwords
Applications
RAM
4kb
5 MHz, 5 V
optional:
crypto-coprocessor
CPU
Cryptographic
coprocessor
ROM
EEPROM
RAM
18
Today, most smart cards have an inexpensive 8-bit microprocessor, but in high-end cards we can find a 16-bit or 32-bit processor.
An optional cryptographic coprocessor increases the performance
of cryptographic operations. By performing signature operations on
the card itself, the user's private key never needs to leave the card.
The information stored in the ROM is written during production.
It is the same for all chips of a series. It contains the card operating
system and maybe also some applications.
The EEPROM is used for permanent storage of data. Even if the
smart card is unpowered, the EEPROM still keeps the data. Some
smart cards also allow storing additional application code or application specific commands in the EEPROM.
The RAM is the transient memory of the card and keeps the data
only as long as the card is powered.
1.2.4
Mechanical Contacts
A contact smart card has up to eight mechanical contacts, which are
used to supply power and a clock signal to the card and to transmit
data. The ISO standard 7816-2 [IS002] specifies the position, the
minimal size, and the usage of the contacts.
Vee
RST
elK
RFU
GND
Vpp
lID
Figure 1.4:
Mechanical
Contacts of a
Smart Card
RFU
Two out of the eight contacts are reserved for future use (RFU)
and six are actually used3 The six active contacts are:
_
is between 4.5 V and 5.5 V. In the future we will see lower voltage rates around 3 V.
_
RST is used for the reset signal to reset the address counter and
the microprocessor. A reset without removing power is called
"warm reset". A "cold reset" takes place if the power is removed and reapplied.
GND
The vpp connector is used for the high voltage signal, which is
necessary to program the EEPROM. Newer smart cards have
the capability to generate this high voltage themselves, so that
they do not use the Vpp contact.
I/O is used to transfer data between the smart card and the
reader device in a half-duplex mode. The protocols for this
communication are also specified in ISO 7816.
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.
--
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, centered 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.
Figure 1.5: The
Size of the
Smart Cards
/0-000 and 10-1
(~~ID-OO' {mm
54mm
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 applications 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 attachable to the universal serial bus (for example Aladdin's eToken
[Ala02]).
20
1.2.6
Hardware Security
The objective of smart card chip design is to provide high physical
security for the data stored in the card. The processor and the memory are combined in the same chip. This makes it difficult to tap the
signals exchanged between the processor and the memory.
The design of a smart card chip considers many more possible
threats [RANOO]. These include slicing off layers of the chip to optically read out data, manipulating the voltage or clock to make the
processor fail, attacks using high temperature or X-rays, and several
others.
Sophisticated counter measures are applied to guard the chip
against the various attacks. For example, passivation layers are
added to prevent analysis in combination with slicing off layers of
the chip. Address lines and the memory cells of the chip are arranged in unusual patterns to make the physical examination harder.
Furthermore, some chips have the capability to detect if the layer
above the chip was removed, as it would occur if somebody were to
examine the chip. Chips can detect unusual variations in the clock or
in the voltage and react with shutdown of the operation.
Some newer techniques to spy on the information stored on the
card try to do this by manipulating or observing the power supplied
to the card. Newer versions of smart cards have been made resistant
to these types of attacks.
1.2.7
Making a module. The chips on the wafer are tested and the
good ones are marked. The wafer is sawn into individual chips.
The single chip is connected to the golden contact plate to make
a module.
Fabrication ofthe plastic card. PVC is often used as the material for the card. All text and graphics, which are common for a
series of cards, are printed on the front and back of the card
during this step.
21
Module insertion. A hole is made into the plastic and the module is inserted.
22
Initialization. The data files and programs that are common for
a series of cards are loaded into the EEPROM of the smart card.
Personalization. During this step, the cardholder-specific information is loaded into the smart card's EEPROM and printed
on the front and/or back of the card. Data that is typically loaded
into the card during personalization include the name of the
cardholder, the number of his bank account, or his private key.
The printing during personalization usually includes the name of
the cardholder and sometimes also his picture.
In this chapter, we introduce the concepts of smart card software development. We assume that you are familiar with application software development and that we need to cover here only the smart
card specifics. We explain the distinction between the on-card and
the off-card part of an application and we cover the interaction between both parts. We give an overview ofthe software development
for both parts.
This chapter serves as a foundation for Part II of this book, where
we will cover the development of smart card software in Java.
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
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
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.
Off-card
On-card
23
File system
cards
Most manufacturers of smart cards offer toolkits or software development kits that support the development of the on-card part of
the application.
Most smart cards provide functions to encrypt and decrypt data.
These functions can be used to make the smart card and the communication with the smart card notably secure.
The majority of current smart cards have a file system integrated
into the operating system. A file system on a smart card supports the
storage and retrieval of all kinds of data and is useful for many types
of applications.
For most types of current smart cards, development of on-card
executable code is not in the hands of the application developers.
The development of such code can only be done by the card operating system developers. The code must be integrated into the mask
for the ROM of the smart card before the smart card is manufactured.
Recently developed card operating systems enable application
developers to create and download on-card application code on their
own. The most important ones of these operating systems are Java
Card, Multos, and Smart Card for Windows.
2.2
2.2.1
APDUs
Application Protocol Data Units are used to exchange data between
the host and the smart card. ISO 7816-4 [IS002] defines two types
of APDUs: Command APDUs, which are sent from the off-card ap-
24
plication to the smart card, and Response APDUs, which are sent
from the smart card to reply to commands.
There are several variants of Command APDUs. Each Command
APDU contains:
_
Two parameter bytes PI and P2. These are used to pass command specific parameters to the command.
Optional data.
Command
APDU
Command APDU
CLA INS
P1
P2
Lc
Optional Data
Le
Figure 2. 1:
Command
APDUand
Response APDU
Body
-Header-
Response APDU
Optional Data
SW1 SW2
1 Here
and in the following, we use Java syntax for expressions like this one.
--
25
Response
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
ATR
T=0
26
The protocols T=O and T=1 are the two most-used variants of halfduplex asynchronous protocols defined in ISO 7816-3.
With T=O, each character is transmitted separately, while with
T=I, blocks of characters are transmitted.
Most modem smart card readers (see Chapter 5 "Smart Card
Readers") are capable of transmitting with either one of these protocols. 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.
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 implementations. 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 second (GETRESPONSE), the host asks for the expected number of response bytes and the card returns these.
The T=l protocol can send a command and receive the response
in the same exchange. It cleanly separates the application layer from
the transport layer and is suitable for secure messaging between the
host and the card.
One of the details that increase the complexity of asynchronous
transfers is the error handling, especially the prevention of endless
waiting. For this reason, a block waiting time (BWT) is specified,
which indicates how long it is reasonable to wait for a response
block. The BWT appropriate for a card is among the protocol information that the card returns in the ATR.
For some commands, the smart card needs more time than typical, for example for complex cryptographic computations. To prevent the host from giving up waiting for the response too early, the
card sends a preliminary response asking for a wait time extension.
The card and the host communicate on a wait time extension using
so called "S-blocks", while the standard command and response exchange is made with "I-blocks".
You will encounter the BWT, I-blocks, and S-blocks again in
Section 9.2.2 "The opencard.optterrninal.protocol Package". For a
complete and excellent coverage of these protocols please see
[RANOO].
T=1
Block waiting
time
Waiting time
extension
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 Notation 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-LengthValue" with a tag that identifies the type of the object, a length of the
contents, and the contents (value) itself.
Tag
Ox92
Airport
Length
Value
Ox03
"XWY"
3 Bytes
Figure 2.2:
Example ofa
Simple TLV
II
TLVs allow for adding of new object types without breaking existing programs. TLVs can be nested: The value can be a TLV.
27
2.3
Smart Card Operating Systems
In this section we first cover the well-established file system cards
and then concentrate on the new operating systems, which support
independent development and download of custom application code.
The new operating systems, Java Card, Multos, and Smart Card for
Windows, are the primary candidates for multi-application scenarios.
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
Elementary file
(EF)
Dedicated file
(OF)
28
The master file (MF) is the root of the file system. Like a DF, it
contains EFs and DFs. There is only one MF per smart card. Elementary files in the MF are normally used to store data and keys,
which are accessed by different applications on the card. According
to ISO 7816-4 the identifier of the MF is Ox3FOO on every ISOcompliant file system smart card.
The file system of a smart card has the following specific file
types:
Transparent
Fixed Record
Variable Record
Cyclic Record
Transparent
Fixed
Records
Variable
Records
Cyclic
With a transparent file, reading and writing is done as when accessing 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
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 record 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
write operation always writes to the next record; a read operation
always reads the last written record. If all allocated memory is filled,
Figure 2.4:
Smart Card File
Types
Transparent file
Record file
Cyclic file
29
the cyclic file automatically wraps and overwrites the record that
was written first. Such a file is often used for logs.
ISO 7816-4 specifies a number of commands for a file system,
like:
Read Binary
Write Binary
Append Record
Access
conditions
Select File
Update Binary
Always: The specified operation can be performed on the specified file without satisfying any access condition.
The use of message authentication codes and external authentication are typical patterns that you will often encounter in smart card
software. You will learn more about these patterns and others in
Chapter 4 "Cryptography".
30
2.3.2
Java Card
Limitations of
Ja va Card
31
Java Card
Framework
Q)
:Ell>
--_.....
0-0
(Q
:?!u
2.3.3
Multos
Multos is one of the mUlti-application smart card operating systems
that allow the download or update of an application on the card after
it was issued. Multos is currently available in Version 5, which was
released in October 2000. The industry consortium Maosco owns the
Multos specification [MUL02].
A Multos smart card provides an ISO compliant file system interface and in addition an execution environment for custom applications. Application developers can create these custom applications
using a new language called MEL (Multos Executable Language).
32
MEL-API
Mullos -AAM
Silicon (Hardware)
Multos for example is in use as one of the operating systems carrying the Mondex purse system, which we explain in Section 3.l.2
"Mondex". For more information on MUltos, please see Maosco's
homepage: http://www.multos.com/.
Figure 2.6:
The Multos
Operating
System
2.3.4
2000.
The card is a combination of a traditional ISO 7816-4 compliant
operating system and a programmable platform. The core provides a
file system, access control, 110, cryptographic services, an API, and
a selection of ISO commands. An optional runtime environment allows the addition of custom-developed applications.
33
r----I Applications I
I (unverified ) I
ISO 7816
Commands
r-----
(verified )
I
I
Runtime
Environment
_ _ -.J
Internal API
I--
Access Control
(Authorization/Authentication)
G
/O
34
~ Crypt:graphy
@
le g i
System
~---
35
Non-repudiation
It is often necessary to assert that a particular person sent an order 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
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 replacement for cash is desirable in these cases.
I The term "e-business" is more general than e-commerce. It includes also applications like supply chain management and other business-to-business flows.
36
--
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 announced 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 establishing a connection for every payment transaction involves costs
that can be too expensive for the payment of small amounts (sometimes referred to as "micropayment"). For the payment of small
amounts, purse systems based on a smart card provide a secure, reliable, and inexpensive solution. Electronic purse cards are also an attractive alternative to cash in areas where cash handling is an expensive 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 decreasing 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 usually 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 permanently 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 implementing digital money. This concept does not require a smart
card as a secure purse carrier, but it has the disadvantage that the
payment needs an on-line connection.
3. 1 Electronic Purses
Digital tokens
versus smart
card based
purses
--
37
Many
electronic
purses - all
incompatible to
each other
Table 3.1:
Electronic Purse
Systems
Worldwide
[EPS002]
38
Digital tokens can be held on computer hard disks and manipulated with the standard mechanisms provided by the operating system. These tokens provide some resistance to simple fraud attempts.
Every token has a unique number and is digitally signed by the issuer. 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 require that a merchant is connected to the issuer's system while accepting a payment.
Currently there are more than 40 different electronic purse systems in use or in trial operations. Some of the more widely known
systems are listed in Table 3.1. Cards are valid for one system only
and cannot be used to pay in any other system. Money cannot be directly 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 compatible individual electronic purse systems [CEPSOO].
Name of
Purse
Country
Chipknip
Netherlands
Dutch banks
Danmont
Denmark
PBS Danmont
GeldKarte
Germany
ZKA
Million
Cards
Issued
14.0
0.6
52.0
Mondex
49 countries
Mondex
Moneo
France
10.0
Proton
25 countries
Proton World
35.0
Quick
Austria
Austria Card
4.8
Visa Cash
19 countries
Visa
8.0
1.0
3.1.1
GeldKarte
In 1993, the "Zentraler KreditausschuB (ZKA)", the organization of
German banks regulating payment systems, chose a proposal from
Deutsche Telekom, GAD, and IBM for a multifunction chip card
with a payment function. Later, the ZKA bought the rights for this
specification, which is the base for today's GeldKarte.
In 1996, the first GeldKarte trial started in the town of Ravensburg in southern Germany with 60,000 smart cards and 600 merchants. Within 6 months 6.2 million DM (about 3.1 million dollars)
were spent.
At the end of this trial in Ravensburg, the ZKA decided to introduce the GeldKarte in all parts of Germany. So far, about 52 million
GeldKarte cards have been issued to customers. The customer is not
charged for GeldKarte payment transactions. Nevertheless, only two
to three percent of the issued cards are actually in use 2
A GeldKarte stores the following information: Card serial number, identification number of the issuing bank, bank account number,
activation date, expiration date, balance, maximum amount to credit,
maximum amount to debit, sequence number of credit transaction,
sequence number of debit transaction, log of the latest 15 debit
transactions, log of the latest 3 load transactions.
There are two types of GeldKarte: Cards associated with a bank
account can be loaded in an ATM-like loading station. During this
load process the amount is transferred from the customer's bank account into the purse.
Cards that are not associated with a bank account are sometimes
called "white cards". The advantage of the white GeldKarte is its
anonymity. Although we do not expect this to happen with the
GeldKarte today, it would be feasible to build a relationship between
the amount paid with the card, the owner of the card, and the goods
or services the owner paid for. This would not at all be feasible with
a "white" GeldKarte. Privacy versus recording of personal data and
preferences is in many countries an important issue for the wide acceptance of a system.
At the CeBIT '99 fair in Hanover several companies already
showed solutions in which a GeldKarte was used to pay over the
Data on a
GeldKarte
Cards
associated with
an account
White cards
2 The ZKA counts as active and in use every card which has been used for payment 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 GeldKarte 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
Card-to-card
Loading and
unloading at
payphones
An alternative
to cash
40
3.1.3
Proton
Proton is an electronic purse system developed in Belgium by Banksys, a Belgium organization specializing in electronic fund handling
and security. Today 4,000,000 Proton electronic cash cards are in
use by customers in Belgium with 23,000 terminals installed.
Worldwide, Proton systems are in use or in trial in 25 countries with
a total number of 35 million issued cards.
American Express, Banksys, ERG (a public transport smart card
systems company in Hong Kong), Interpay Nederland (the issuer of
14 million Dutch Chipknip banking cards), and Visa International
created Proton World in 1998 to further promote Proton. In October
of 2001 ERG acquired the shares owned by the other members of
the consortium and is now the solely owner of Proton World International.
The Proton system platform cannot only be used for payment, but
also for security controls, loyalty schemes, or social security cards.
For example, a health care system will be based on Proton:
"Mutuelle", a Belgian state-held health insurance company issued
during 1999 a health card that uses the Proton platform and also includes a Proton purse. In summer of 2001 a government multipurpose card was rolled out in Malaysia, which included Proton
[PR002].
Proton World provides a complete solution for an electronic purse
including host-systems, terminals, cards, and implementation and
support services. The purse cards can be loaded at ATM's, public
pay phones, and smart phones [PR002].
The first Proton cards based on CEPS were demonstrated in October of 2001 during "Cartes" trade show in Paris.
3.1.4
Visa Cash
In 1995, Visa International introduced an electronic purse system
called Visa Cash. Today Visa Cash is used in several trials and implementations around the world. It is also being used for electronic
payments on the Internet.
Visa International has about 20,700 member banks and is the
world's largest credit card organization. These member banks have
issued around 561 million Visa credit cards that are accepted at approximately 13 million places around the world. This credit/debit
3. 1 Electronic Purses
--
41
Trials
Components
Service
Payment
Terminal
Concentration
Point
Clearing and
Administration
System
42
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 Eurocard), Visa International, Visa Spain, and the ZKA (the owner of
Germany's GeldKarte specification) founded the Common Electronic Purse Specification (CEPS) Group. Mondex is notably not a
member of this group. The CEPS group works on defining a common standard for electronic purse systems, which can be used and
are compatible worldwide. Organizations from 22 countries, representing 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 specifications 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-ofsale and load-transactions, and the data elements and recommended
message formats for transaction processing. It also provides functional requirements for the various electronic purse scheme participants. 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 capabilities.
43
An alternative to
passwords ...
3.2.1
Workstation Access
The most common way of securing the access to a workstation is
user authentication before starting a user session. Some systems do
not even start loading the operating system without authentication.
Both variants can be combined with an additional function that
locks the session after a specified time without activity and then requires authentication before the session can be resumed.
For standard workstation operating systems like UNIX variants or
Windows 2000, there are numerous products on the market to provide secure workstation access based on smart cards. In most of
these products, smart card authentication uses standard cryptographic mechanisms. The cryptographic computations are performed
by the smart card, which also holds the secrets needed for the
authentication. We describe these cryptographic mechanisms in detail in Section 4.2 "Smart Card Cryptographic Protocols".
3.2.2
Network- and Server-Login
Authentication is required to work with a remote server, to access
data on a server, or to use a private network. It is obvious that the
more secure the authentication mechanisms are, the better protected
the servers, the data, and the private networks are. In all of these
cases the authentication is usually based on a challenge-response
protocol with asymmetrical keys, as we describe in Section 4.2.
The authentication can go in two directions. Either the server
needs to prove its authenticity to the client, or the client needs to
44
3.2.3
Secure Communication
A common way to protect the communication between client and
server is by establishing a secure session, where all communication
is encrypted using a symmetrical key. This symmetrical key, often
called "session key", is exchanged between the session partners by
using public key cryptography. This exchange is typically combined
with authentication of the partners. An example of such a scheme is
SSL and its successor TLS (see Section 4.3 "TLS and Smart
Cards"). A smart card is ideal to host the private key for authenticating the client to the server in a SSL connection.
As we have seen, in a secure session the data is encrypted immediately before it is transmitted and decrypted directly after it is received. Alternatively, the data can be permanently stored in an encrypted form, and sent and received unchanged. In this case, decryption takes place before the data is used.
In all of these schemes the key that is required for the decryption
can be stored in a smart card. Because a smart card usually is not
powerful enough to efficiently decrypt large amounts of data, the
smart card passes the decryption key to the host computer, which
then performs the decryption.
A more secure variant is to use a changing decryption key, which
itself is kept in encrypted form. The smart card then decrypts the decryption key. In this way the smart card only decrypts a few bytes
and yet its decryption key is not exposed.
So far we have looked at communication between a client and a
server. For communication between two clients we need a different
form of protection. One type of client-client communication that we
all use is e-mail. An individual e-mail is stored and forwarded across
--
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 receiver, 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
Certificates
46
For digital signatures it is crucial that the private key remains absolutely private. If any person could copy another person's private
key, the digital signature would no longer be unique to the owner.
Therefore the private key has to be stored in a very secure place
where nobody could possibly copy it and where nobody but the
owner can use it.
The most secure place to store such a private key is a cryptographic hardware unit, often called "crypto token". A smart card can
be considered the most convenient and most portable cryptographic
hardware unit. Modem smart cards are able to perform the signing
operation inside the card. At the same time they do not provide any
function to export the private signature key to the outside. Legislation in some European countries requires that the signature key must
be generated on the smart card. In combination with the requirement
that there must be no way to export the signature key, this makes it
highly unlikely that any additional copies of a signature key could
exist.
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
Electronic Ticketing is a typical application where the card receives
data from the net for later use. Consumers can put a ticket for a
flight, a bus ride, or an event onto their smart cards. These transactions can take place at ticket vending machines, at kiosks, or at the
consumers' PCs or Internet screen phones. In the latter case, an obvious path for the transaction is a web browser running a Java applet
that communicates with the ticketing server through the Internet and
--
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 connected 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 secure 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 expensive 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
48
3.4.3
Growth Expected
In this chapter we have discussed several ways in which smart cards
help to protect or enable e-business solutions. E-business itself and
the use of smart cards for e-business are expected to grow at enormous rates over the next years. We would not be surprised if you
read this book because you are up to developing a new type of solution not discussed here. The goal of this book is to provide you with
concepts and patterns that support working with smart cards in Java,
the premium language for development of e-business solutions.
--
49
4 Cryptography
In this chapter, we will give a brief introduction to cryptography, focusing on aspects that are important in conjunction with smart cards.
We start by a short overview of the predominant cryptographic algorithms. Then we present commonly used cryptographic protocols for
authentication and secure transmission of data and give some examples on how these protocols are used in the smart card area. Finally,
we give an example for usage of smart cards to support cryptographic software on a Pc. It shows how to use smart cards for private-key operations required by TLS (Transport Layer Security, the
successor of SSL 3.0).
This will give you a reasonable understanding of cryptographic
algorithms and protocols relevant in the smart card domain. If you
are seeking more comprehensive and detailed information, we recommend the excellent book "Applied Cryptography" by Bruce
Schneier [SCH96].
4.1
Cryptographic Algorithms
In this section we give an overview on the most relevant cryptographic algorithms in the smart card environment.
There are two important classes of cryptographic algorithms that
we want to present - symmetric algorithms and asymmetric algorithms. 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.
--
51
4.1.1
Symmetric Cryptographic Algorithms
Symmetric cryptographic algorithms are fast and can be used to encrypt and decrypt large amounts of data. However, the fact that the
same key has to be used for encryption and decryption causes a
problem when symmetric algorithms are to be used to ensure privacy of communication. The sender and receiver of a message must
use the same key i.e. the receiver and only the receiver must know
the key of the sender to ensure privacy of the transmission. Each receiver must know the keys of all potential senders to be able to decrypt all incoming messages. Evidently, the geometrically growing
number of required keys is impractical if the number of entities in
the network is big. The solution for this problem is a combination of
asymmetric and symmetric algorithms, as described in section 4.1.3.
As this is a smrut card book, we only present symmetric algorithms that are ndevant for smart cards. For information on algorithms not describlid here or for more details, you may refer to
[SCH96].
4.1.1.1
DES
The Data Encryption:Standard was developed in a program to protect 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 divides 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 significant 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 substitutions 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.
4.1.1.2
Trip/eDES
Triple DES is based on DES, but uses 112-bit keys. The key is divided 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-decryptencrypt (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 attacks 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.
4.1.1.3
DES Encryption Modes
There are several different DES modes that are often used in conjunction with smart cards. The simplest mode is the Electronic Code
Book (ECB) mode. ECB mode encryption means that the encryptoperation is applied to each single 64-bit block of plaintext, as
shown in the following Figure 4.1:
Figure 4.1:
DES ECBMode
- Each 64-bit
Block is
Separately
Encrypted
Plaintext 1
64 bit
DES Encrypt
64 bit
Ciphertext 1
64 bit
Ciphertext 2
The decrypt-operation is applied to each single 64-bit block separately, obtaining the original plain text block.
The Cipher Block Chaining (CBC) mode chains the result of each
DES operation to the subsequent operation, as shown in Figure 4.2.
The first operation is chained to an Initial Chaining Value (ICV), in
most cases a random 64-bit block or a block of 64 zero bits. The first
4. 1 CryptographiC Algorithms
--
53
block of plaintext is XORed with the ICV and the result is encrypted, 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
4.1.1.4
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.
4.1.1.5
AES
4. 1 Cryptographic Algorithms
--
55
4.1.1.6
Other Symmetric Algorithms
There are many other symmetric algorithms besides DES, like RC4,
RC5, IDEA, Skipjack etc., but these algorithms are virtually irrelevant in the smart card area. You can find information on these algorithms 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 independently 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 encrypt the same amount of data. However, public-key algorithms
have a big advantage when used for ensuring privacy of communication: 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 signatures or for decrypting private information encrypted under the
public key. The public key may be used for verifying digital signatures or for encrypting information. It needs not to be kept secret,
because it is infeasible to compute the private key from a given public 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.
4.1.2.1
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
Next, an encryption key e is chosen so that e and (p-l)(q-l) are
relatively prime. The decryption key d is chosen so that
ed = 1 (mod (p-l)( q-l)) or d = e-1 mod ((p-l)( q-l))
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
More details on the mathematical background of the RSA algorithm
can be found in [COR89].
As the problem of factoring two large prime numbers is very hard
to solve, it is infeasible to compute the private key from the public
key if the primes multiplied to obtain the modulus are big enough.
Today's smart cards usually offer key sizes between 512 and 1024
bits. A modulus size of 512 bits is not considered very secure. A
modulus size of 1024 bits is considered to offer a reasonable level of
security for applications like digital signatures and encryption for
documents.
4.1.2.2
DSA
The National Institute of Standards and Technology (NIST) proposed the Digital Signature Algorithm (DSA) in 1991 for use in the
Digital Signature Standard (DSS). The security of the algorithm relies 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 issued with a variable key length from 512 to 1024. The DSA algorithm works as follows:
4. 1 Cryptographic Algorithms
--
57
h(p-J)/q
h(p-J)/q
x<q.
y = g'modp.
p, q and g are public and can be common across a community of
users. x is the private key and y is the public key. H is a one-way
hash function. The Digital Signature Standard specifies the Secure
Hash Algorithm (SHA-l), see [SCH96]. The sender of a message m
performs the following operations:
r and s are the signature and are sent along with the message. The
receiver verifies the signature by performing the following calculations:
w=s-J mod q
uJ = (H(m) * w) mod q
u2 = (rw) mod q
v = ((gUJ * yU2) mod p) mod q
The signature is verified if v = r. We will not present the proofs
here, they can be found in [NIST94].
4.1.2.3
Elliptic Curve
Elliptic curves were first proposed for use in public-key cryptosysterns 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 implementations.
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 libraries, SSL implementations etc., already support RSA and DSA, so
that smart cards must support these algorithms to be usable in exist-
58
4 Cryptography
4.1.3
Hybrid Algorithms
As mentioned above, symmetric algorithms are fast but have the disadvantage of being impractical in networks connecting many entities. Asymmetric Public Key Algorithms on the other hand are practical 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 session keys for symmetric algorithms used for the symmetric bulk encryption. Then, the session key is encrypted using an asymmetric algorithm. 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
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 important protocols are external authentication, internal authentication and
secure messaging.
4.2.1
External Authentication
External authentication means the authentication of an external entity to the smart card. The smart card and the external entity conduct
a challenge-response protocol like the one shown in Figure 4.5.
The external entity obtains a challenge - typically a random
number - from the smart card and encrypts it with a key shared between the card and authentic external entities.
1. The external entity requests a random number r from the smart
card by sending an appropriate command to the smart card.
--
59
Figure 4.5:
Authentication of
an External
Entity to a Smart
Card
Smart Card
Get Random
Generate and store
random number r
External Authenticate(ek_ext(r)t
Result
4.2.2
Internal Authentication
Internal authentication means the authentication of a smart card to an
external entity. The smart card and the external entity conduct a
protocol like shown in the Figure 4.6.
60
4 Cryptography
External Entity
Smart Card
'.!!.
n to be used
Figure 4.6:
Authentication of
a Smart Card to
an External
Entity
4.2.3
Secure Messaging
There are several different concepts of secure messaging which are
employed in smart cards. Messages can be protected by a Message
Authentication Code (MAC) or protected by a MAC and also encrypted. For calculation of the MACs or encryption of the transferred data, secret keys shared by the external entity and the smart
card can be used directly or session keys can be established. There is
a broad spectrum of possible schemes. In this book, we will only
present some examples, without claiming full coverage of schemes.
4.2.3.1
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 common key, which is used for calculating a Message Authentication
Code (MAC) over the transmitted data. The purpose of a MAC is to
--
61
External Entity
Smart Card
Generate and
store random
Give Random(r)
number r
I-----.:....:...----~
Store random
~---------~ numberr
I-----~--.:.--...:....-...
Calculate MAC'
~
MAC
________________
~MAC
data + MAC
=MAC'?
5. The external entity receives the data read and the MAC from the
smart card. It calculates a MAC over the received data, using the
key kex, - that must match the key kfile - and the random number r
generated in step 1. Only if both MACs are equal, the data is accepted.
A similar method can protect data sent to the card, as shown in
Figure 4.8.
62
4 Cryptography
External Entity
Smart Card
Get Random
Figure 4.8:
Secure
Messaging
in WriteOperations
data + MAC
=MAC'
4.2.3.2
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:
--
63
Figure 4.9:
Secure
Messaging and
Encryption of
Data Read from
a Smart Card
External Entity
Smart Card
Generate and
Give Random(r)
store random
numberr
Store random
numberr
Decrypt data+MA,C
Calculate MAC'
over data using
rand k..t
MAC MAC'?
eldlle{data + MAC)
64
4 Cryptography
Smart Card
Get Random
Generate and store
number r
~_ _ _ _ _ _ _ _ _-Irandom
Figure 4. 10:
Secure
MessagingData Written to a
Smart Card is
Protected by a
MAC and
Enciphered
f 4 - - - - - - - - - - I MAC = MAC'
65
Figure 4. 11:
Secure
MessagingEstablishing a
Session Key
Using Key
Derivation
External Entity
Smart Card
DeriveSessionKey
Generate and
store random
number r, derive
Figure 4. 12:
Secure
MessagingEstablishing a
Session Key
Using a Public
External Entity
Generate
Session Key k.,
UnwrapKey(ekPub(k.
encrypt under kpub
Kev
Smart Card
..
~----------~
Decrypt cipher
using kpriv
OK?
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 similar 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 communicating parties.
The TLS protocol consists of several layers. The lowest layer is
the TLS Record Protocol that assures privacy and reliability of connections and is used for encapsulating higher-level protocols, like
the TLS Handshake Protocol. This protocol provides connection security 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 authentication is often required to ensure that only authorized people can access 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 authenticate the client by validating the obtained certificate and using the
public key from that certificate to verify the client's signature contained in the Certificate Verify message.
Client authentication in TLS requires a private key and a certificate 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.
67
Readers and
Terminals.
Readers and
Terminals
What we call a
reader has
many other
names
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. Another reader type has the size of a 3.5" diskette and is inserted into a
diskette drive to be connected to the computer.
--
69
Readers can
have a display
and a PIN-pad
Figure 5.1:
Smart Card
Readers
(TOWITOKO)
Readers come
with different
application
programming
interfaces
OpenCard
Framework, the
Java API
70
thing in this book. When developing with Java, you should look for
a smart card reader with support for the OpenCard Framework.
The OpenCard Consortium maintains a list of readers that
can be directly plugged into the OpenCard Framework on
http://www .opencard.org/index-devices. shtmll.
5.2
The advantage of a smart card terminal over a smart card reader attached 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)
Merchant cards
Terminals can
have several
card slots
71
Magnetic stripe
technology
Terminal form
factors
Self service
terminals
more slots for the merchant's cards. With such a terminal, the merchant can accept several different electronic purses with a single device.
A terminal is a computer on its own, with a processor and memory. Today a high-end payment terminal typically has a 32-bit processor and up to several megabytes of memory. Some terminals can
even be programmed in Java.
For maintenance or to add new features to a terminal, it is often
necessary to download software or software updates to these devices. Such a download will change the system after it was certified.
Therefore additional security mechanisms in combination with certification of the downloaded software must be established.
Most of the payment terminals are not only capable of executing
smart card transactions, they can also perform credit and debit transactions based on data read from a magnetic stripe.
Terminals are available in different enclosures. The most common kind is a tabletop device, which you might have seen at your
gas station or local grocery store. A tabletop device is mainly used
for payment or credit transactions made while the customer visits the
merchant. When the merchant visits the customer, e.g. to deliver a
pizza, the merchant preferably uses a portable payment terminal.
Portable terminals can perform off-line transactions. Some are also
capable of using mobile data networks for on-line transactions.
Many terminals can also be extended with additional features like
ticket printers.
In the same way we can draw cash from an ATM, we can load an
electronic purse at an unattended load device. Using this kind of unattended terminal is very similar to using a traditional ATM. In addition to loading an electronic purse, this type of terminal can often
be used to change passwords, to check the card balance, to print
statements, to lock or unlock the purse card, to pay bills, and more.
5.3
Biometric Identification
72
cation techniques ("something that you are") are increasingly applied instead of passwords and PINs. You can find an excellent
overview of the current state of biometrics in the book from Jain,
Bolle, and Pankanti [Jain99].
--
73
Part II
OpenCard Framework
Standards like ISO 7816 and industry initiatives like EMV or OpenCard 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 manufactured 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 application.
6.1
ISO Standards
The International Organization for Standardization (ISO) also develops and maintains standards for smart cards. Of these, ISO 7816
"Identification cards - Integrated circuit cards with contacts" is the
most important for working with chip cards that have electrical
contacts.
Today ISO 7816 has nine parts:
Physical characteristics:
Part 1 defines the physical dimensions of contact smart cards and
their resistance to static electricity, electromagnetic radiation, and
mechanical stress.
ISO 7816-1
6. 1 ISO Standards
75
ISO 7816-2
ISO 7816-3
ISO 7816-3
Amendment 1
ISO 7816-3
Amendment 2
ISO 7816-4
ISO 7816-5
76
Registration of identifiers:
Amendment 1 to Part 5 defines the process for obtaining an RID.
The purpose of RIDs is to uniquely identify the provider of an application on the smart card.
Inter-industry data elements:
Part 6 defines the data elements and the TLV tags (see Section
2.2.3 "TLV Structures") for industry applications. It also defines the
appropriate TLV structure and the procedures to read these structures.
Registration of IC Manufacturers:
Amendment 1 to Part 6 defines the process for registering IC
Manufacturers.
ISO 7816-5
Amendment 1
ISO 7816-6
ISO 7816-6
Amendment 1
ISO 7816-7
ISO 7816-8
ISO 7816-9
ISO 7816-10
6.2
EMV ICC Specifications for Payment
Systems
In June of 1996, Europay, MasterCard International, and Visa International (EMV) published EMV'96: ICC Specifications for Payment
77
EMV2000
Card Part 2
78
Additionally Part 2 defines the way in which an off-card application can select the appropriate on-card application in the case of a
multi-application card. It defines the logical structure of data and
files within the card that is required for this application selection. In
addition, it specifies how the terminal has to process this data.
6.3
PC/SC
PC/sC 1.0
Part 1
PC/SC 1.0
Part 2
6.3 PC/SC
79
PC/SC 1.0
Part 3
PC/SC 1.0
Part 4
PC/SC 1.0
PartS
PC/SC 1.0
Part 6
Part 6 specifies the ICC Service Provider and the Crypto Service
Provider interfaces. These two interfaces are the primary interfaces
the application developer will use.
The ICC Service Provider (ICCSP) must maintain the context
of the communication with the card. Optionally, the ICCSP may offer classes for access to the files on the card and for the authorization
functions needed to access the card.
The Crypto Service Provider (CSP) is optional. If cryptographic
functions are needed for the access to the card, these functions are
localized in the Crypto Service Provider. Such functions often fall
under export restrictions for cryptography components. Keeping it
localized allows for better control. For the CSP the interfaces are
specified for key generation, key management, key import/export,
digital signature, hashing, and bulk encryption services.
The ICC Service Providers need to be registered together with the
card and interfaces they support. This enables the system to identify
80
and fetch the appropriate ICCSPs for a particular card. For the identification of the card, the ATR or parts of it are used.
PC/SC 1.0
Part 7
PC/SC 1.0
Part 8
PART 7
Figure 6.1:
Layers of the
PC/SC
Architecture and
the Eight Parts
of the
Specification
Applicalion~
I' RT
0\
PARI 3
1m
lIandler
1..0
ICC
110
lIandl ..
ltD
lI.ndler
11'0
6.3 PC/SC
81
Implementations
ofPC/SC
Microsoft has provided implementations of the PC/SC 1.0 specifications on the Windows 95 and Windows NT 4.0 platfonns and
has released this implementation to the World Wide Web. For Windows 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 http://www.pcscworkgroup.com.This 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 management level.
GlobalPlatfonn was founded in 1999 by Visa together with several 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, STMicroelectronics, Sun, Toshiba, and of course Visa International. The Open
Platfonn specifications have been renamed to GlobalPlatfonn specifications.
The GlobalPlatfonn Specifications consists of three parts: A card
specification, a device specification, and a system specification.
The device specification, also called terminal specification, focuses 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 GlobalPlatfonn family of specifications. It covers at a high level the infrastructure, processes, and systems required to manage a multiapplication card and its content.
82
The GlobalPlatform API - It provides services for increased security, like the ability to open a secure channel for communication with the off-card part of the application. Additionally it
provides card management functions, allows the card to verify
the cardholder, and can be used to personalize the card.
CVM implements a global PIN to support cardholder verification that all applications can use. It implements the CVM
interface.
6.4 G/oba/P/atform
--
83
84
Card Content - The applications, which are loaded onto the card
with an Executable Load File.
7 Introduction to OpenCard
7.1
The History of the Open Card Framework
The history of the OpenCard Framework begins in 1997 with the
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 Network Computers, the idea of a Java framework for smart card access
was born.
Until recently, writing a smart card application was quite a difficult job mastered by a few specialists only. These specialists knew
the APDUs and the protocols needed to drive smart cards as specified 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 developers from Bull, Gemplus, Schlumberger, and Sun.
In September 1997, version 0.9 of OCF was published on the
newly created OpenCard homepage http://www.opencard.org/.
During the spring 1998 CardTechiSecurTech conference and
trade show, OCF version 1.0 was released to the public. The six industry leaders Bull, Gemplus, IBM, Schlumberger, SCM Microsysterns, and Sun demonstrated the interoperability achieved by using
the OpenCard Framework: The same application was shown on different hardware platforms, with different operating systems accessing the data on a smart card using readers from different manufac-
The beginning
OCF 0.9
OCF 1.0
87
OCF 1. 1
OCF 1. 1. 1
OCF 1.2
turers. All this was accomplished without having to change the application.
During the second half of 1998, the OCF reference implementation was improved with respect to code size and performance. It became available as OCF version 1.1 in October.
In May 1999, version 1.1.1 of OCF was published. In addition to
a few minor corrections, this version contains support to run OCF in
the newer versions of the web browsers from Netscape and Microsoft without using the Java Plugin technique.
In December 1999, OCF version 1.2 was published. This version
incorporates many changes in response to Requests for Comments
(RFC) from OpenCard Consortium members. Major enhancements
include an easy to use installer package, improvements in various
component packages, and Java Card support. In this book we work
with OCF version 1.2.
Although the idea of the framework started in 1997 with Network
Computers in mind, today the OpenCard Framework is used in all
kinds of computers. Its range goes from large computers and network computers all the way down to small and embedded devices,
like for example a Screen Phone or a payment terminal.
7.2
~~--:
==-=.=
88
----
rei TOWITOKO
7 Introduction to OpenCard
un
C
tJi
"'.
Purpose
of the
consortium
Founding
members
Organization
7.3
Card terminal
vendors
Card OS
providers
89
Card Issuers: These are the actual entities which issue smart
cards to customers. The card issuers decide if and where to
place what card-resident applications on the cards they issue.
Card issuers
Objectives 01
OCF
7.4
Benefits for
application and
service
developers
90
The architectural model of OCF makes a distinction between application and service developers on one hand and card and terminal
providers on the other, offering significant advantages to all.
Application- and service developers benefit from the OpenCard
Framework as follows:
Vendor independence: Developers can choose cards and terminals from different suppliers.
Asset protection: Extensibility of the architecture enables developers to participate in future developments in smart card technology at low cost by migrating at the level of the API.
Improved time-to-market: Developers profit from shorter development cycles by programming against a high-level API.
Increased clientele: Providers gain access to new market segments reaching many customers.
Improved competition: Providers can compete in terms of functionality and are less vulnerable to the predominance of a single
vendor.
Less development effort: Providers inherit functionality provided by the framework. This improves their productivity.
Thus, using the OpenCard Framework becomes mutually beneficial for both developers and providers. Application- and service
implementers writing to these interfaces can deploy their solutions in
many different settings without having to change a single line of
code. Providers adhering to these interfaces make their components
directly usable for application- and service developers, thus gaining
easy access to a rapidly growing market.
7.5
7.5.1
A Note on Notation
For explaining OCF, we make heavy use of class diagrams in UML
notation. Therefore, let us now recap the UML notation for those
notational elements that we use in this book.
91
Figure 7.2:
Exampleofa
Static Class
Diagram in UML
Notation
\WIce()
+ pU:IIo;Melhod()
f....fold( )
+ lertold()
pt'oIededMelhod()
- p<MlleMell>Od()
,,
Classes
Visibility
Methods
Associations
MultipliCity
92
Figure 7.3:
Example Class
Another in
UML Notation
and Source
Code
String
Another
(from miooteS)
- privateAttribute : int
pub11cAttribut.;
publicStaticAttribute;
protected
pr! vate
prot.atec:lAttribute;
pr11" ...teAttribute;
String
int
I;
7.5.2
Architecture Overview
Involved
Parties
--
93
.I
Application
PrOVider
Card
Il _____
Issuer _
~~:ider
Card Service
Registry
1- ---.--l~=4F=~:::::::::~
;
Traditional &
programmable
cards
94
Reader
Device
PrOVider
The card developer provides the general-use, card-specific services. The on-card layer offers the basic infrastructure for accessing
data on the card and using services provided by the card. Accessing
these basic services often requires use of vendor specific data packets.
For traditional smart cards, the developer of the card operating
system usually provides the application-specific executable code on
the card. With modem, easily programmable cards such as Java
Card and Smart Card for Windows, the application provider as well
7 Introduction to OpenCard
as the card operating system provider can develop the on-card application. Activating on-card executable code requires use of application specific data packets, regardless of the application provider.
The OCF CardService encapsulates the card operating system
and on-card application dependencies, shielding the application from
changes in those components.
A CardService that provides a standard way to access files on
an ISO file system card is an example of a general-purpose component. Internally, this component would use basic services provided
by the smart card vendor. A digital signature CardService is another 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 previous layer, also consist of CardService modules. Since the card issuer 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 application. 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 cornrnunication protocol. The terminal layer encapsulates these device differences. In this framework layer, the card reader provider can supply 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 CardServiceScheduler, Smart Card, CardID and the two registry
classes.
The class SmartCard is the central abstraction. A Smart Card
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
application or function it supports and of the card operating system
on which it can run. CardServices can draw on other CardServices. For example, a PurseCardService, which needs to
access card files, can use the FileSystemCardService available
for the card.
CardService
CardService
examples
CardTerminal
SmartCard
CardService
95
CardServiceFactory
CardService
Registry
All knowledge about the availability of CardServices is encapsulated 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.
The system-wide CardServiceRegistry keeps track of the installed CardServiceFactory objects. When a CardService
with a particular interface is requested from OCF, the CardServiceRegistry 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 CardServiceFactory objects in a system, there is always only a single CardServiceRegistry.
The CardService calls any cryptographic functions needed to
access the card. Again, the CardService knows the most about the
CardServiceScheduler
CardTerminal
CardTerminaJ
Factory and
CardTerminal
Registry
security mechanisms and protocols needed for the specific card operating system.
A CardService object communicates with the smart card
through the CardServiceScheduler, which is also a class provided by the OpenCard Framework core. The CardServiceScheduler synchronizes concurrent accesses to one card from
different applications. Consequently, there is exactly one CardServiceScheduler object for every Smart Card.
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 several 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 designated 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 patient data card and the authorization card of the doctor to be inserted
at the same time.
As we have previously discussed, a CardServiceFactory creates a CardService. The CardServiceRegistry administers all
CardService and CardServiceFactory objects. Looking at
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 CardTerminalRegistry.
96
7 Introduction to OpenCard
Application
Management
CardServices
FileAccess- and
FileSystemCardServices
Events
--
97
Figure 7.6:
CardChannel,
SlotChannel and
Related Objects
Ca-d Cha"lnel
om",,"')
om"""')
+ isOpenO
+ goiC .,dTe,min.{)
+ .etSllteO
+ goiState()
+ .endC omm.ndAPD UO
+ openO
+ olo.eO
+ fin.lizeO
+ toSt'ingO
0 .."
+ getV@liionO
- mutexCardChannel
0 ..1
-free_channel
~nCoh.nnel
.Iot_ hannll
1
Sial Chan nel
- s martcard_refs: : int = 0
- is_aliv'e : boole an = false
/h:nnel
0 .. 1
IoID : inl
. Iotc h.nneISt.te: boole.n = f.1s e
+ SlotCh.nneO
+ goiScheduleo()
+ .etSohedule,O
+ .endAPD UO
+ g015 10tN umbeo()
+ golC.,dTe,minO
+ goiLockH .ndleO
-terminal
0 .."
+ resetO
+ isOpenO
+ olo.eO
+ goiC .,dIDO
+ toSt'ingO
SmartCard and
CardChannel
CardTerminal
98
+ Sm.,tc .,dO
+ beginMute>)
+ olo.eO
1 + end Mute>()
+ goiC .,dIDO
+ goiC .,dServioe()
+ golSm.rtC.,<I:)
+ isSt.rtedO
1 .."
+ .hutdo...nO
+ .t.rI()
+ .... ~Fo'C.'dO
. 0:::<:
om .... "')
om", .. D
SmartCard
CoO'
om", ....
D "'
. Iotc ounl : int= 0
+ featu,eO
+ getAdd,e.O
+ goiC .,dIDO
+ goiN.meO
+ golTl'peO
+ goiSlolsO
1
+ isC .,dP,e.en1()
+ isSlotC h.nnelAv.il.bleO
+ openO
+ olo.eO
+ openSlotCh.nnelO
+ olo.eSlotCh.nneIO
+ ,e.e1()
+ .endAPD UO
7 Introduction to OpenCard
After a card has been inserted and OCF has prepared the communication path, we have for that card exactly one SlotChannel and
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 channel supported by the card).
Maybe you wonder why we need a CardChannel at all, and why
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 mechanism, 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.
SlotChannel,
SmartCard
CardChannel
99
This chapter covers some support classes that are used throughout
the OpenCard Framework. These classes define constants and exceptions 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
constant and exception definitions, opencard. core. uti 1, which
contains standard utility classes, and opencard. opt. util, which
contains optional utility classes.
OpenCard
utilities
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 methods. It defines constants such as the names of the properties that are
used for configuring the framework.
The OpenCardException class is the base for all checked
OpenCard exceptions. The base exceptions in the OpenCard service
and terminal sub-packages - CardServiceException and CardTerminalException - are derived from this base class.
The OpenCardRuntimeException is the base class for all unchecked OpenCard exceptions. When a runtime exception is thrown
it indicates a possible programming error in the application.
Constants and
base
exceptions
--
101
Figure 8.1:
The OpenCard
Core Classes
II~I
SIring
,)
1....
_Iong)
+SOPENCARD_PROPERTY
+$OPENCARO_PROPERTIES
+$OPENCARD_DOTPROPERTIES
+$DEFAULT_OPENCARD_LOADER_CLASSNAME
...................
OponCa'dException
+$CARD_SERVlCE_REGISTRY_TAG
+$CARDJERMINAL_REGiSTRYJAG
+WPID_ENCODING
+$CARD_SERVICE_URL
+ OpenCardExc:eptlon()
+ OpenCardExc:eptlon("""""'II": Siring}
RunllmaExcoptlon
--",no)
+$CARD_SERVICE_LiSTER_CLASS
+$CARD_SERVICE_CHECK
+$CARD_SERVICE_CACHEPATH
--.-
+$CARD_SERVICE_CACHETIME
Interface
OpanCardCons_
8.2
The core utility classes are essential for tracing, accessing system resources, 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
102
The HexString class provides a number of static methods that manipulate 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.
SystemAccess
HexString
(from opencard.core.utll)
(from ...core.util)
+ dumpO
+ hexifyO
+ hexifyShortO
+ parseHexStringO
+ parseLittleEndianHexStringO
OpenCardPropertyLoadingException
(from opencard.core.util)
+ OpenCardPropertyLoadingExceptionO
Interface
OpenCardConfigurationProvider
Figure 8.2:
The OpenCard
Core Utility and
Trace Support
Classes
Interface
TraceLevels
(from opencard.core.utll
Tracer
(from opencard.core.utll)
, (from opencard.core.utll)
+ loadPropertiesO
The dump (... ) and hexify (... ) methods are frequently used
within toString (...) methods of OpenCard classes and when preparing 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
The configuration provider classes shown in Figure 8.2 provide the
basic support for automatic configuration of the OpenCard Framework.
The simplest way to bring up the framework is through use of the
SmartCard. start ( ) method. Smart Card is a class from the
opencard. core. service package, which will be covered in Section 10.1, "The CardService Layer Components". The start ()
method uses the properties settings along with a configuration provider to set up the CardTerminal and CardService support.
Configuring
OCF
103
Loading
properties
8.2.3
The Tracer
FigureB.3:
Trace Support
Classes
Tracer
Interface
TraceLevels
(from opencard.core.utll)
(from opencan:J.core.utll)
+$ EMERGENCY: int = 0
+$ ALERT: int = 1
+$ CRITICAL: int = 2
+$ ERROR: int = 3
+$ WARNING: int = 4
+$ NOTICE: int = 5
+$ INFO: int = 6
+$ DEBUG: int = 7
+$ LO\I\IEST : int = 8
Interface
TracerListener
I(from opencan:J.core.event)
104
l}
\
\
\
\
,,
\
TracerEvent
Tracer
8.2.3.1
Definition
EMERGENCY
ALERT
CRITICAL
Error
0; System is unus-
1;
=
3;
Method
2;
emergency ( )
able.
Action must be
alert ()
taken immediately
Critical condition critical()
Error condition
Trace Level
Table B.1:
Trace Level
Definitions
error ()
105
WARNING = 4;
Warning condition
NOTICE = 5;
INFO = 6;
DEBUG = 7;
Trace method
definitions
Debugging
information
warning()
debug()
There are two methods defined for each trace method name. Both
methods require a parameter that specifies the name of method being
instrumented and a parameter that specifies the message to be inserted into the trace stream.
public void debug(java.lang.String method,
java.lang.String message)
public void debug (java. lang. String method,
java.lang.Throwable throwable)
The methods differ in their specification of the message parameter. The first method requires a simple string parameter, while the
second requires a Throwable object as parameter. In the latter
case, the trace text is extracted from the Throwable object.
In addition to the trace methods, the Tracer provides a method
that allows the application to query the active trace level. Sometimes
a considerable amount of data manipulation must be performed to
prepare a string of trace data. The programmer can use the getTraceLevel () method to avoid this data manipulation when tracing is
not activated.
8.2.3.2
Trace Output
TracerEvent,
TracerListener
106
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.
The Tracer posts this record as a TracerEvent to all registered
TracerListener classes (see Figure 8.3). The TracerEvent
class from the opencard. core. event package provides accessors 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.
Tracing to
output stream
8.2.3.3
Activating Trace Output
The OpenCard. trace system property governs the behavior of the
Tracer. This property specifies a list of tokens specifying packages
Trace system
properties
8.2.4
System Access
107
Figure 8.4:
System Access
Classes
SystemAccess
(from opencard.core.utll)
+
+
+
+
+
+
+
getBoolean(}
getProperties(}
getProperty(}
getSystemAccess(}
loadLibraryO
loadPropertiesO
setSystemAccess(}
! \
/[I.
NetscapeSystemAccess
(from opencard.optnetscape)
OCFwithin a
browser
SystemAccess
class
Microsoft policy
engine
108
MicrosoftSystemAccess
(from opencard.optms)
The static SystemAccess. setSystemAccess C.. ) method allows an applet to provide a specialized version of SystemAccess
for the current environment. This is best done in the applet's
init () method. The SystemAccess object set in this manner is
valid only for the current thread. This prevents concurrent threads
from obtaining unauthorized access.
The component requiring access does not instantiate a SystemAccess object directly. Instead, it obtains a reference to the
SystemAccess object valid for the current thread by calling the
static getSystemAccess () method. If a specialized SystemAccess object has been set by the applet, it will be retrieved rather
than the default object.
The following code fragment illustrates the use of the SystemAccess class by an OCF component.
Netscape
privilege
manager
8.3
Optional
utilities
109
8.3.1
Figure 8.5:
Loader Classes
URLClassLoader
(from opencard.opt.util)
OpenCardPropertyFileLoader
(from opencard.opt.uti~
+ URLClassLoader(uri : URL)
+ URLClassLoader(uri : URL, archive: String)
# loadClass(name : Siring, resolve: boolean) : Class
# loadClassData(name : Siring) : byteO
# loadArchive(url : URL, archive: Siring) : void
# inpulStreamToByteArray(is : InpulSlream) : byte(]
Property file
locations
1. [java.home]/lib/opencard.properties
2. [user.home]/.opencard.properties
3. [user.dir]/opencard.properties
4. [user.dir]/.opencard.properties
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 precedence. This allows a general set of properties to be placed in a central 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.
110
OpenCard.services
Specifies fully qualified class names for available
CardServiceFactory modules. Multiple entries are separated by white space.
Example: OpenCard.services =
com.ibm.opencard.factory.MFCCardServiceFactory
OpenCard.ter.minals
Specifies factory class name, friendly name, device
type, and address information for each available CardTerminal. Vertical bars separate this information. Multiple entries are separated by blanks.
Example: OpenCard.terminals =
com.ibm.opencard.terminal.ibm5948.IBMCardTerminalFactory
Table 8.2:
OpenCard
Properties
I
ReaderAjIBM5948-B0211
OpenCard.trace
Specifies trace levels for OCF classes and packages.
Multiple entries are separated by blanks.
Example: OpenCard.trace = opencard.core:3
OpenCard.trace.eventsOnly
Boolean property set to true to suppress trace output on
the System. out output stream.
Example: OpenCard.trace.eventsOnly = true
Loading classes
from the
Internet
8.3.2
The PassThruCardService
The PassThruCardService shown in Figure 8.6 fulfills two
functions - it provides a quick and easy way to exchange information with a smart card and it provides the simplest imaginable example for CardService programming.
111
Figure 8.6:
PassThruCardService
PassThruCardService
(from opencard.optutil)
+ PassThruCardServiceO
+ sendCommandAPDU(command : CommandAPDU) : ResponseAPDU
11
PassThruCardServiceF actory
(from opencard.opt.util)
+ PassThruCardServiceFactoryO
+ knows(cardlD : CardlD) : boolean
+ cardServiceClasses(cardlD : CardlD) : Enumeration
An application can use this class's single method, sendCommanto send an application protocol data unit (APDU) to the
smart card and receive an APDU from the card in reply.
Naturally, this means that the application must generate the
command APDUs and must interpret those returned by the card.
This goes somewhat against the grain of OpenCard, since the purpose of the OCF CardService layer is to shield the application
programmer from generating and interpreting APDUs. However, it
is sometimes convenient to be able to do this.
Every CardService requires a factory that can create new instances of it. Such is also the case here. The PassThruCardServiceFactory instantiates the PassThruCardService.
The usual CardServiceFactory will construct a CardService only for the particular smart card it was written to support. Since the PassThruCardService can be used with any smart
card, the PassThruCardServiceFactory will create an instance
for any card whatsoever.
The OpenCard Framework must be configured properly to use
the PassThruCardService. This entails setting up the system
properties for OCF. In particular, the opencard. services property must include a reference to the PassThruCardServiceFactory. In the opencard.properties file on a Windows system,
this could appear as follows:
dAPDU ( ... )
Pass Thru
configurauon
OpenCard.services =
opencard.opt.util.PassThruCardServiceFactory
The following code fragment initializes the OpenCard Framework, obtains a PassThruCardService object, and sends a command to a card. Don't expect to understand all of the classes used
here - this is just to give you a first taste of OpenCard programming.
112
i f (sc ! = null)
8.3.3
Tags and TL V
structures
Tag field
113
Figure 8.7:
TagandTLV
Classes
Creating and
interpreting tags
TLV
Interpreting
binary TLV
data
114
TLV
.... opencaul.optu",}
Tag
from openeard.optutil
oTagl)
o Tag(t : Tag)
o Tag(tag : int, tagClass : byte. constructed: boolean)
+ Tag(binary: byteD, offset : intO)
+ Tag(binary : byteO)
+ size() : inl
+ fromSinary(binary : byteD, offset : intO) : void
+ get8ytesO : byteD
+ toBinary(b"ary : byte{J, offset : intO) : void
+ set(tag : int, tagclass byte, constructed) : yoid
+ setConstructed(constructed : boolean) : void
codaO: int
+ isConstructedO : boolean
+ hashCode() : inl
+ equals(o : Object) : boolean
+ toStringO : String
,tag
oTLVO
o TLV(binary : byte{J)
o TLV(tag : Tag, value: byleD)
o TLV(tag : Tag, number: in!)
o TLV(tag : Tag, Uv : TLV)
o add(tlv: TLY): TLV
+ findTag(tag : Tag, cursor: TLY) : TLV
+ fromBinary(binary, offset, Uv, parent)
opname(argname) : return
+ IenBytes(length : inl) : inl
+ Iength() : int
+ IengthToBinary(length: ..I): byteD
+ setValue(newValue : byteO) : void
tagO: Tag
+ tDBinaryO : byte{J
+ tDBinaryContent() : byieD
+ toStringl) : String
toString(ht : Hashtable, level : in!) : String
valueAsByteArray{) : byteD
valueAsNumbelt) : inl
One of the main issues addressed by the OpenCard Framework is device support for card readers. The mechanism provided allows support for a new card reader l to be easily added by implementing a
CardTerminal.
The CardTerminal is a type of device driver for the card reader.
It contains all required device-specific code.
The CardTerminalFactory is used by the OpenCard Framework to create an instance of the CardTerminal. The CardTerminalFactory must also be provided when adding support for a new
card reader.
The OpenCard Framework provides a number of constructs to
minimize the effort required for adding device support. These constructs consist of classes that provide functionality used directly or
indirectly by the CardTerminal, interfaces that can be implemented
by the CardTerminal, and exceptions to be thrown when problems
occur.
The interfaces and classes can be divided into core and optional
components. The core components provide base functionality that is
required in all OCF installations. The optional components provide
specialized interfaces for extended device support.
Figure 9.1 shows an overview of all OCF terminal layer components. The optional components are shown with shaded boxes. We
will be covering the terminal layer components in detail in the following sections.
Card reader
device support
Core and
optional
components
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.
115
Figure 9.1:
Terminal Layer
Core and
Optional
Components
Interface:>:>
VerlfiedAPDUlnter1llc:e
1..... - . . .,1
Im.rface
Interface
PowerManage<MnUnterf.c:e
r erm lnalCommond
~(""'---~------------~I""'~
9.1
116
9.1.1
Terminal Registry and Event Mechanism
The CardTerminalRegistry is a singleton object that keeps track
of all card readers known to the OpenCard Framework and provides
methods that allow devices to be added and removed from the system. You can use CardTerminalRegistry methods to obtain the
number of registered devices or references to the installed CardTer-
CardTerminal
Registry
minals.
I, CardTerminal I
Interface
CTListener
(from terminal)
poliO void
l(CardTerminalEvent
from terminal)
(from event)
l'
(from opencard.core.event)
Interface
Pollable
l,opencardEvent
from opencard.core.event)
+$ CARDJNSERTED: int
+$ CARD_REMOVED: int
Interface
Observer
=Ox01
=Ox02
(from tenninal)
+ updateCards(CT,slot,cardins): void
+ updateTerminals(Poliable,
tenninaladded) : boolean
+ getCardTerminalO : CardTerminal
Figure 9.2:
CardTerminal
Events and
Related Classes
+ toStringO : String
CardTerminalRegistry
from opencard.core.terminal
EventGenerator
\
- CardTerminalRegistryO
+ getRegistryO : CardTerminalRegistry
+ add(terminal : CardTerminal) : void
+ addPoliable(p : Pollable): void
+ countCardTerminalsO : int
+ getCardTerminalsO : Enumeration
+ remove(terminal : CardTerminal) : boolean
+ runO: void
+ removePoliable(p : Pollable) : boolean
+ setPolllnterval(duration : int) : void
+ ... and others ... 0
-$reglstry
from opencard.core.event
- EventGeneratorO
getGeneratorO : EventGenerator
addCTListener(ctl : CTListener) : void
createEventsForPresentCards( ... ) : void
getPolllntervalO : int
updateCards(term,slot,inserted) : void
removeCTListener(cti : CTListener): void
runO: void
+ updateTerminals( p : Pollable,
term_add: boolean): boolean
\ +
+
+
+
+
+
+
-$theGenerator
Card insertion
and removal
events
Polling
mechanism
117
Figure 9.3
Card Inserted
Event
C.,dTermlnal
User
Implement.Uon
C.rdT.rm noll
e Clan
e .... nIG.n.r.cor
Regl.ter,d
CTLlaten'r(a)
I~)
po l~)
..
,~)
ulfdlnurtedO
urdln rted(C.,c
...; ::::::::
'' ~I
..""
After a CardTerminal implementing Pollable has set up
communication with the physical device, it uses the CardTerminalRegistry addPollable (. .. ) method to add itself to the device
list serviced by the background polling thread.
9.1.2
Device Abstractions
Factory
CardTerminal
118
SlolChannel
CardTerminal
from opencard.core.tarminal)
from opencard.core.tenninal}
+ getAddres.O : String
+ gelCardlO(slollO : int) : CardlO
+ getNameO : String
+ gelTypeO : Siring
+ isCardPresent(slotiD : int) : boolean
+ isSlotChannelAvaiiable(slotlD : int) : boolean
+ openO : void
+ close() : void
+ openSlotChannel(slotlD : int) : SlotChannel
+ closeSlotChannel(sc : SlotChannel) : void
+ sendAPDU(SlotChannel, cmd) : resp
+ and more ... {)
r--
+ SlolChannel(lerminal, slollO)
+ gelSchedulerO : Objecl
+ selScheduler(scheduler : Objecl) : void
+ sendAPOU( ... )
+ gelSlolNumberO : inl
+ getCardTerminalO : CardTerminal
+ reselO : CardlO
+ isOpenO : boolean
+ closeO : void
+ gelCardlOO : CardlO
+ 10SIringO : Siring
Figure 9.4:
The DeviceOriented
Classes
Inlerface
CardTerminalFaclory
(from opencard.core.termlnal)
+ 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 implementation 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
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, otherwise null may be returned.
The CardTerminal openSlotChannel (... ) method creates a
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
CardlD
SlotChannel
119
SlotChannel and
session concept
SlotChannel
methods
same slot until the first thread releases it. A SlotChannel can only
be obtained when a card is present in the specified slot. The
SlotChannel is invalidated when the card is removed.
In a sense, the SlotChannel is a session object that is valid for
communication with exactly one smart card. This session concept
was introduced to prevent a card from being accessed using a stale
driver stack, and also to prevent unauthorized access to the card from
separate application threads.
The SlotChannel and related CardTerminal methods are
mainly for use by the OCF CardService layer. However, the OCF
terminal layer can also be used separately from the CardService
layer. The application would directly use the SlotChannel in this
situation.
The sendAPDU () method of the SlotChannel provides the actual mechanism for communicating with the smart card. This synchronous method allows a Command APDU to be sent to the smart
card and blocks until a Response APDU has been received. A soft reset can also be carried out using a SlotChannel method. Additional
methods provide the slot number and a reference to the CardTerminal object associated with the SlotChannel. The SlotChannel is
opened when it is created and can be closed explicitly to terminate
communication with the card.
9.1.2.1
120
Figure 9.5:
Data Transport
Classes
+ CardlD(answerToResetResponse : byte[])
+ CardlD(ct : CardTerminal, slot: int, answerToResetResponse : byteO)
+ gelATRO : byte[]
+ getHistoricalsO : byte[]
+ getSlotiDO : int
+ equals(obj : Object) : boolean
+ toStringO : String
ResponseAPDU
APDU
I(from opencard.core.tenninal)
lfrom opencard.core.tennlnal)
+ APDU(buffer : byte[])
+ APDU(buffer : byte[], length: int)
+ APDU(size : int)
+ append(bytes : byte[]) : void
+ append(b : byte) : void
+ getBufferO : byte[]
+ getByte(index : int) : int
+ getBytesO : byte[]
+ getLengthO : int
+ setByte(index : int, value: int) : void
+ setLength(length : int) : void
+ toStringO : String
+ ResponseAPDU(apdu : byte[])
+ ResponseAPDU(size : int)
+ dataO : byte[]
+ swO: int
+ sw10: byte
+ sw20: byte
...
P---
CommandAPDU
from ocencard.core.terminall
+ CommandAPDU(buffer : byteO)
+ CommandAPDU(buffer : byte[], length: int)
+ CommandAPDU(size : int)
Response-
APDU
Response-
APDU
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 terminallayer exceptions extend CardTerminalException.
--
121
Figure 9.6:
CardTerminal
Exceptions
OpenCardExcepllon
II
InvalidSlolChannelExceplion
from ooencard.core.tennlnal)
CardTerminal
~.-.\ T~ ~
+ InvalidSlotChannelExceptionO
+ InvalidSlotChannelExcepUon(msg : String)
+ InvalidSlotChanneIException(msg, terminal)
TerminalLockedException
from
eneard.oOllennlnal)
+ TenninalLockedException{msg : String)
+ TenninaILockedException(msg, terminal)
CardTerminalExceplion
+ CardTermlnalExceptlon(s : String)
+ CardTerminalException(msg : String, terminal)
+ CardTermlnaIExceptlon(msg, terminal, slot)
+ getCardTerminalO : CardTerminal
+ getSlotO : int
TerminallnitException
(from opencard.core.tennlnal)
+ CardTenninalExceptionO
F------
+ TennlnallnitException(msg : String)
+ TermlnallnltException(ms9, terminal)
TerminalTimeoulExceplion
tfrom o~~ncard.core.terminal)
A'----"~
CardNotPresentException
from ooencard.core.tenninal
+ getTimoutvalueO : Int
CommunicationErrorException
+ CommunicationErrorExceptlon{)
+ CommunicationErrorExceptlon(msg : String)
+ CommunicationErrorExceptlon(msg. terminal)
+ CommunlcationErrorException{msg, terminal,
slot)
Each CardTerminalException contains references to the responsible slot and the CardTerminal object. The application can
use these references to identify the device reporting the problem.
The following table describes when the exceptions are to be used.
Table 9.1:
Terminal Layer
Exceptions
122
CardNotPresentException
Thrown when an attempt is made to communicate with the card,
but the card is no longer present in the slot.
CommunicationErrorException
Thrown to indicate that an error has occurred when communicating with the card acceptance device.
InvalidSlotChannelException
Thrown if an invalidated SlotChannel is reused.
TerminallnitException
Thrown when a CardTerminal cannot be initialized.
Ter.minalTimeoutException
Thrown when the card acceptance device does not respond within
the expected len~h of time.
TerminalLockedException
Thrown when the card terminal has already been locked.
9.1.4
PIN I Password Support
The OpenCard Framework tenninal layer provides support for obtaining a PIN or password from the user and passing it to the smart
card. The rationale behind the implementation of this support requires
some explaining.
CardTenninailOBlender
Interface
CHVEncoder
/from tarmln,n
+ CardTerminal10Blender(ioControl ; CardTerminallOControl)
+ Input(character : inti : Int
+ result() : String
CHVControl
CardTenninallOControl
from tannln,l)
from tannlnall
+ CardTermlnaIiOControl(blender: CardTermlnaliOBlender)
+ blender() : CardTermlnaliOBlender
+ InputSet() : String
+ termlnatorSet() : String
+ maxlnputChars() : Int
+ timeout() : Int
I(1fomtannlnol)
(1fomtannlnal
Figure 9.7:
PIN / Password
Support Classes
IE-
+ CHVControl( ... )
+ prompt() : String
+ applicatlonlD() : String
+ chvNumber() : Int
+ passwordEncodlng() : String
+ passwordOlfset() : Int
+ loControl() : CardTerminaliOControl
Interface
Verifl8dAPDUlnterface
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 extended functionality.
The most common form of extended functionality consists of a
simple display with PIN pad. When a device of this type is used, the
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 received 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.
PIN support
rationale
--
123
Prompt String
Text used to prompt the user for his PIN or password.
Application ID
Text string that identifies the application requesting the password.
Password Offset
Integer specifying the offset within the APDU where the password
is to be placed.
Password Encoding
String specifying the password encoding (character string, BCD,
etc.) required by the card.
CHV Number
Identifies the CHV to be obtained. Used for cards that support
more than one CHV string.
IO Control Object
Object of the class CardTerminalIOControl.
The CHVControl is a container class for CHV characteristics.
These characteristics are listed in the Table 9.2. It is not required that
all fields are used in all cases.
When a password is required, the CardService typically creates
a CHVControl object and passes it to the CardChannel using the
sendVerifiedAPDU() method (see Section 10.1.1, "The Card Access Classes").
The CardTerminalIOControl is a container class for parameters relating to the card acceptance device PIN pad and display. These
parameters are listed in the following table. Again, not all parameters
are required.
Table 9.3:
10 Control
Parameters
Character Set
List of the allowed characters. This list may be used to enable or
disable specific keys on the PIN pad.
Terminator Set
Set of codes that will terminate user input. This list may be used to
enable cancel or correction keys, for example.
124
Timeout Value
Maximum time to wait for user input.
IO Blender Object
An obiect of the class CardTerminalIOBlender.
The CardTerminalIOBlender is an abstract class that can be
implemented to provide special handling such as data formatting if
required by the card. The CardService would generally provide an
implementation of the CardTerminalIOBlender class if neces-
sary.
The CHVEncoder interface contains constant definitions for
common PIN or password encoding schemes. This interface also defines a method that can be used to provide special encoding.
The CardTerminal can implement the VerifiedAPDUlnterface if the card reader is capable of obtaining a PIN from the
user, inserting it into an APDU, and passing it to the card. If the
CardTerminal implements this interface, the OpenCard Framework
will automatically use the card reader PIN pad.
CHVEncoder
9.2
Terminal Layer Optional Components
The optional components relating to the terminal layer are contained in two packages. The opencard. opt. terminal package
contains direct extensions to the core package, while the opencard. opt. terminal. protocol package contains specialized
classes used for handling the protocol between the host and the
card reader.
CommandAPDU
(from opencard.core.termlnal)
I(from _rd.oottermlnal)
Interface
PowerManagementlnterface
ISOCommandAPDU
I(from ooencard.oottermlnal)
<<Interface
TerminalCommand
Figure 9.B:
Terminal Layer
Optional
Components
from ooencard._termlnal)
Interface
Usertnteraction
from ,,-cord._termlnal)
--
125
These components may be useful in special cases, but the programmer 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 usually 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 opencard.opt.terminal Package
Terminal layer
optional
components
ISO command
support
Power
management
Terminal
command
User interaction
Terminal locking
126
The opencard. opt. terminal package contains classes that directly extend the functionality of the terminal layer core components.
Figure 9.8 shows the optional OpenCard terminal layer components.
The optional components provide two new classes and four new interfaces to the CardTerminal programmer.
The ISOCommandAPDU class adds extended support for APDUs
that conform to the ISO 7816 standard. Constants describe the seven
APDU cases defined by the standard. Additional methods are provided 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.
The PowerManagementlnterface provides functions to explicitly power-up and power-down an inserted smart card. When a
card is inserted into a slot, the CardTerminal must always automatically power it up. The methods provided by the PowerManagementInterface can be used in addition to the automatic card
power-up function.
The TerminalCommand interface provides a type of 'transparent'
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.
The Userlnteraction interface adds methods for directly accessing display and PIN pad capability of the card acceptance device.
These methods allow text display and allow the application to directly obtain input from the keyboard. Another method, promptUser (... ) , displays a text string and returns keyboard input with one
simple call.
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 interface without breaking any existing code.
Application requirement
No lock required
OCF behavior
The behavior of OCF 1.1.1 is unchanged
Lock on CardTerminal or
slot is required
Abstract
lockable
Terminal class
127
9.2.2
T1 Block class
Figure 9.9
T1 Protocol
Classes
Uermlnal
+ craaIIIIBIock(.) : T1BIock
+ cr_BIock() : T1Block
+ craataSBIock(): TfBlock
T1Block
tllnnlnal.
from
toea
+ TfBIock()
+ CIIIcEDCO: Int
+ getBlock() : byta()
+ getBIockTypa() : Int
+ geISourcelll() : int
+ getPCB{) : byte
+ getControlBIts() : Int
+ geISou"'-ess() : Int
+ ge!RequestadSequenceNumberll : Int
-. -
....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
128
separately for each CardTerminal implementation. The exchangeDa ta ( ) method is protected since it is meant to be used
by the TIProtocol class internally.
The TIProtocol base class constructor requires a default source
address, remote address, and timeout value. The derived class that
implements the exchangeData () method may require other parameters that relate to communication with the card.
After the CardTerminal implementation creates a TIProtocol
object, it should call the open () method. The open () method synchronizes communication with the card by issuing the appropriate Sblock requests.
The CardTerminal implementation can use one of the transmi t () methods to communicate with the card. The simplest transmi t () method accepts a byte array of data to be sent to the reader
and returns a byte array containing data received from the reader.
The remaining transmi t () methods allow the default host address
and remote address to be overridden.
The TIProtocol class also provides accessors and modifiers for
many data fields representing the protocol internal state. Examples of
these fields include block waiting time, send sequence count, and receive sequence count.
The opencard. opt. terminal. protocol package provides
exceptions for many protocol error conditions that may occur. These
are explained in the table below.
TIBlockEDCErrorException
Thrown when an error is detected in the checksum.
TIBlockLengthException
Thrown when a difference is detected between calculated and received block length.
TIBlockNotlmplementedFeatureException
As mentioned above, this implementation of the T1 protocol is not
complete. This exception is thrown if an attempt is made to use an
unsupported feature.
TIDataPacketTooLongException
Thrown when the info field of an I-block is greater than 254 bytes.
TIException
Base exception for all T1 exceptions.
TIIOException
Thrown if a communication error occurs.
TITimeoutException
Thrown when a send or receive timeout occurs in the T1 protocol.
TIUnknownBlockException
Thrown if a T1 block of unknown type is processed.
Using T1
protocol
support
Table 9.4:
T1 Protocol
Support
Exceptions
--
129
9.3
Tracing in the Terminal Layer
Terminal layer
traces
Activating trace
output
The '7' following the colon specifies the debug trace level. Note
that this setting activates tracing only for the base class, not for the
CardTerminal implementation. To activate tracing for the CardTerminal implementation, specify the fully qualified path name of
the implementation class or its package in the OpenCard. trace
system property.
To activate debug tracing for the entire core terminal package, set
the OpenCard. trace property as follows:
IOpencard.trace = opencard.core.terminal:7
9.4
130
1. You can use the Java Communications API, also known as the
javax.comm interface, to create a pure Java solution. This is the
preferred mechanism, since it allows you to achieve a high degree
of platform independence.
Communication
possibilities
2. If you are working with a device that is not supported by the standard serial and parallel ports, or if the Java Communications API
is not available on the platform of your choice, you can write a
driver using the Java Native Interface. This will require 'C' as well
as Java programming, and will also be highly platform-specific.
At this point, you might be asking yourself about the PC/SC interface. The Personal Computer / Smart Card interface was developed
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 platform, all installed PC/SC card acceptance devices can be accessed
through OpenCard if the OpenCard PC/SC CardTerminal is configured.
OCF PC/SC
support
9.4.1
The Java Communications API
The Java Communications API provides stream-oriented serial and
parallel device support and is available on many platforms. Since
many card acceptance devices are serially attached, the Java Communications API is quite useful to the CardTerminal programmer.
The Java Communications API provides classes that allow serial
port access. These classes provide the capability to access and change
the serial port parameters such as baud rate, number of stop bits, and
parity to be used during communication. They also provide methods
to obtain an output stream for sending data to the serial port and an
input stream for receiving data from the port.
The CardTerminal implementation can also register itself as an
event listener in order to be notified when data becomes available or
when the serial port control line state changes.
For more information, please see the JavaSoft documentation
[JNI98].
Java
Communications
API
131
9.4.1.1
Using the Java Native Interface
Java Native
Interface
The Java Native Interface (JNI) provides a means of accessing operating system native binaries from a Java Application. A Java native
class consists of the actual Java class that can be used by a Java application along with a portion, typically written in 'C', that runs in the
native operating system environment.
Since the native portion is operating system dependent, such code
is much less portable than code written to the Java Communication
Interface. If your application is to run on multiple platforms, you will
have to port the native portion of your code to each platform individually.
However, if you are writing a CardTerminal for a device that is
not serially attached, the JNI provides a good alternative.
Please see the JavaSoft documentation [JCM98] for more information about the Java Native Interface.
9.5
The Implementation
Figure 9. 10:
CardTerminal
Implementation
CardTerminal
(from terminal)
T1 Protocol
CardTerminalFactory
(from protocol)
(from terminal)
~------~------~
Pollable
(from terminal)
-protocol / /
GCR410CardTerminai
(from gemplus)
GemPlusCardTerminalFactory
(from gemplus)
132
the abstract methods, and must write a CardTerminalFactory capable of creating instances of the CardTerminal derived class.
Figure 9.1 0 shows the classes we will be using for the implementation. The CardTerminal implementation extends the CardTerminal abstract class, and the CardTerminalFactory implementation implements the CardTerminalFactory interface.
This section uses a CardTerminal implementation for the
GemPlus GCR410 card acceptance device as an example. The
source code fragments shown in the following sections are taken
from that code. The complete source code can be found at
http://www.opencard.org/SCJavaBooki.
The GCR 410 reader uses the T=l protocol for communication
with the host. The example code uses the T=l protocol support
classes from the opencard. opt. terminal. protocol package.
9.5.1
USing the T=1 Protocol Support
Since T1Protocol is an abstract class, the CardTerminal programmer must extend it and implement the exchangeData ()
method. This customizes the T=l protocol support to use the communication mechanism selected for this CardTerminal implementation - in this case, the Java Communications API.
The GCR410T1Protocol class extends T1Protocol. This implementation assumes that the CardTerminal implementation initializes communication through the port. The CardTerminal provides an output stream to send commands to and an input stream to
receive responses from the card acceptance device. The class declaration and constructor for this class is shown below.
public class GCR410T1Protocol extends T1Protocol
GCR410T1Protocol(int hostID, int remoteID, int timeout,
InputStream in, OutputStream out)
super (hostID, remoteID, timeout);
this.in = in;
this.out = out;
Extending
T1Protocol
The input and output streams passed as parameters to the constructor are saved for use by the exchangeDa ta () method. The default host ill, remote ill and timeout needed by the protocol are
passed to the T1Protocol base class.
133
Exchange
Data(. . .)
do
receiveChar = in.read();
if (receiveChar != -1) {
... add new character to buffer ...
II
134
return receiveBlock;
exchangeData
9.5.2
I CardTerminal
I
(from opencard.core.terminal)
I
I
Pollable
(from opencard.core.terminal)
Figure 9. 11:
CardTerminal
Implementation
Methods
GCR410CardTerminai
(from com.ibm.opencard.termlnal.gemplus)
<Constructor>
The constructor is protected since the CardTerminal is meant to
be instantiated by a CardTerminalFactory.
getCardID ()
Returns the ATR packaged in a CardID object for a specified slot.
isCardPresent ()
Returns 'True' if card is present in specified slot.
open()
Generally used to set up communication with card acceptance device.
Table 9.5:
CardTerminal
Implementation
Methods
close ()
Terminates communication and releases resources.
internalFeatures();
Enhances the properties object provided as an input parameter with
card reader specific features. Used by the CardTerminal base
class.
135
InternalReset()
Perlorms a wann reset on the card in the specified slot. Used by
the CardTerminal base class.
internalSendAPDU()
Sends a command to the card and receives a response. Used by the
CardTerminal base class.
This example also implements the Pollable interlace as an aid
in generating card inserted and card removed events. This adds one
method to the implementation:
Table 9.6
The Poll Method
The implementation must check the device status and generate appropriate events.
We will now cover the example implementation in more detail.
Since going through the code line-by-line would be exhausting, we
explain the concepts behind the method implementations and illustrate the relevant points with code fragments.
The file GCR41 OCardTerminal. java contains the complete example implementation.
9.5.2.1
Initialization and Termination
To start off, the new CardTerminal class must be declared. This
provides the abstract method definitions we must implement.
Class
declaration
Constructor
136
open()
Tracer
137
I I setup streams
serOut = serPort.getOutputStream();
serIn = serPort.getInputStream();
The final major task for the open () method is adding the CardTerminal object to the CardTerminalRegistry polling list. After
this is done, the poll () method will be called periodically by the
CardTerminalRegistry polling thread.
Polling setup
II close protocol
ctracer.debug("close", "close communication protocol");
protocol.close();
II close the streams
ctracer.debug("close", "close input and output streams");
serIn.close();
serOut.close() ;
II close the serial port
ctracer. debug (" close", "close serial port");
serPort.close() ;
Reporting
features
138
might have. Since our example device is very simple, we do not have
to override the internal Features () method.
9.5.2.2
Some Private Helper Methods
This section describes a few helper methods contained in our example implementation (See Figure 9.10 above). These methods are not
required by the CardTerminal base class or the Pollable interface, but they provide frequently required functionality.
The UpdateCardStatus 0 method sends a command to the
GCR 410 that returns information about the inserted card. Depending
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 inserted card - most importantly, it will retrieve the communication
protocol (T=O or T=1) being used between the GCR 410 and the inserted card.
The getCardStatus 0 method merely retrieves the status information 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
to power up the card. It uses the T=1 protocol support set up by the
open () method to communicate with the device:
byte[] sendData = new byte[] { (byte)Ox6E, (byte)OxOO,
(byte) OxOO, (byte) OxOO};
Checking card
status
Power-up card
Send power-up
command
try
rcvData=protocol.transmit(HOST_ID,TERMINAL_ID,sendData) ;
catch (TlException tle) {
throw new CardTerminalException(tle.toString());
The powerUpCard () method maps all exceptions to CardTerminalException. It then updates the card status and pieces together
the ATR string from the information returned by the reader:
GettingATR
UpdateCardStatus(slotID);
tmpATR[lenATR++]=rcvData[4]; II TS 3B=direct, 3F indirect
tmpATR[lenATR++]=rcvData[5]; II TO
139
if
if
if
if
((tmpATR[1]&Ox10)==Ox10)
((tmpATR[1]&Ox20)==Ox20)
((tmpATR[1]&Ox40)==Ox40)
((tmpATR[1]&Ox80)==Ox80)
cachedATR = ATR;
return ATR;
II powerUpCard
9.5.2.3
Detecting card
insertion
Now that we have covered the helper methods, we can turn to detecting a card insertion or removal.
The isCardPresent () method returns true if a card is present
and returns false otherwise. It checks for card presence by examining the status byte retrieved by the GetCardStatus () methods:
public boolean isCardPresent(int slotID) throws
CardTerminalException
return ((getCardStatus(slotID) & STATE_CARD_INSERTED)
STATE_CARD_INSERTED);
PoliO method
140
also contain logic that produces events only if there has been a state
change.
Our poll () method contains such logic. It first retrieves the current card status and tests it to determine if a card is present. The cardlnserted () and cardRemoved () methods from the CardTerminal base class generate the events:
Poll method
logic
UpdateCardStatus(O) ;
if (!cardInserted)
if (isCardPresent(O))
cardInserted = true;
cardInserted(O);
else {
if (!isCardPresent(O))
cardInserted = false;
cachedATR = null;
cardRemoved(O) ;
9.5.2.4
Data Exchange
The final set of methods to be implemented get data from or exchange data with the card.
The getCardID () method retrieves the ATR for an inserted card.
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 implementation 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.
Get Card ID
--
141
Sending the
APDU
Please note that the T=O implementation requires additional processing depending on the different cases specified in the ISO 7816-3
specification (see Section 2.2.2, "T=O and T=l").
The method transmits the command to the reader, which will in
tum pass it to the card. The first byte returned by the reader is a status
byte. Data following the status byte is the response from the card.
tmpReceiveBuf = protocol.transmit(HOST_ID, TERMINAL_ID,
sendCmd) ;
if (tmpReceiveBuf == null)
throw new CardTerminalException("no response from reader");
II
142
9.5.3
Implementing the CardTerminalFactory
Implementing a CardTerminalFactory is a straightforward task.
The CardTerminalFactory interface from the opencard. core. terminal package defines the required methods.
Figure 9.12:
CardTerminalFactory
Implementation
GemPlusCardTerminalFactory
(from com.ibm.opencard.terminal.gemplus)
+ openO : void
+ closeO : void
--
143
Open, close
In our example implementation, the open () and close () methods 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 parameters - name, device type, and communications port. The method
checks the device type parameter to make sure that a GCR410 CardTerminal has been requested. After the parameters have been
checked, the method creates an instance of the CardTerminal and
registers it with the CardTerminalRegistry.
Create Card
TerminalsO
is it a GCR410?
II
II
II
144
The OpenCard Framework service layer shields the application programmer from smart card details. This layer abstracts the smart card
and on-card applications. Figure 10.1 shows the general structure of
this layer.
Figure 10. 1:
OCFService
Layer Structure
Application
CardService Implementation
The OpenCard Framework provides the tools needed for card access. These tools are divided into core and optional components. The
CardService implementation uses these components to offer a
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 communicating with the card to implement the functionality defined by
the interface.
Standard interfaces are available (see section 10.3, "Standard
CardService Interfaces"); however, the application programmer is
free to write his own CardService to encapsulate smart card specific details. This can be useful if the application is to support multiple smart cards of different types.
Defining
CardService
interfaces
Standard
interface
145
Service layer
core
components
Figure 10.2:
Service Layer
Class Diagram
Inlerface
CardlDFiller
Inlerface
PrimaryCardServiceFaclory
(from opencard.core.service)
Inlerface
CardServicelnlerface
(from opencard.opt.service)
CardServiceExceplion
(from opencard.core.service)
CardServiceRunlimeExceplion
(from opencard.core.service)
146
minal whose slot contains the card. CHV handling will be delegated
to the CardTerminal if it has the necessary capability.
CHV handling
The service layer optional components contained in the opencard. opt. service package extend the core functionality with additional interface and exception definitions.
This section provides a detailed description of the service layer
core and optional components and how CardService implementations use them. Figure 10.2 shows a class diagram for the service
layer. For clarity, only the base exceptions are shown.
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 Figure 10.3.
C8rdService Support
Application Access
PrlmaryCardServlceFacIory
cardServlce
cardServiceFactory
cardType
SmartCard
cardRequesl
CardlOFilter
Figure 10.3:
CardService
Layer Core
Components
C8rdAccess
cardChannei
Exceptions
CardServiceExeeption
CardServlcelmpiementaUonException
CardServk:elnabilltyExcepllon
CardServicelnvaiidCr_i~
CardServk:elnvaiidParameterExcepllon
CardServiceOper_nFailedExceplion
CardServlceRuntimeException
CHVSupport
CHVDlaIog
CardHoiderVerlflcationGUI
DelaullCHVDlalog
DelaullCHVDlalogResourceBundle
CardServlceUsageException
InvalidCardChannelException
The application can use the Application Access classes to wait for
card insertion and obtain a particular CardService for the inserted
card.
The Card Access classes provide the base functionality for synchronizing access to the card. They are used by a CardService implementation or by other framework classes.
Service layer
classes
--
147
10.1.1
The Application Access Classes
SmartCard class
Figure 10.4:
The Application
Access Classes
The classes making up this group are shown in Figure 10.4. An application 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.
Interface
Card Request
CardlDFilter
(from openeard.eore.lierviee)
+ isCandidate(CardID): boolean
+ getFilterO: CardlDFilter
~ + getCardServiceClassO: Class
'------------'
+ getCardTerminalO: CardYerminal
+ getTimeoutO : int
SmartCard
getWaitBehavlor() : int
(from opencard.core.service)
+ isTimeoutSetO : boolean
+ SmartCard(CardServiceScheduler, CardlO)
+ claseO : void
+ toStringO : String
StartO
Configuration
loading
148
Configuring the
terminals
Configuring the
services
Shutdown OCF
Multiple
SmartCard
objects
Get CardlD
149
Access
CardService
The application uses the getCardService (... ) method to retrieve a reference to the CardService that implements the desired
interface.
In the following example, the application wants to prepare a digital 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 getCardService (. .. ) to gain access:
Getting a
CardService
signatureService ~ (SignatureCardService)
card.getCardService(SignatureCardService.class, true);
Exclusive
access
Getting a
SmartCard
Waiting for
events
Waiting
synchronously
150
inserted card.
When the application has finished using the inserted smart card, it
calls the close () method. The Smart Card object will close the current session with the physical card and release all associated resources.
The beginMu tex () and endMu tex () methods are bracket functions that allow the application exclusive access to the card across a
sequence of CardService calls. If an application uses the beginMu tex () method, it must be sure to call the endMu tex () method
eventually. If it doesn't, other applications wishing to access the card
will be blocked.
How do we obtain a SmartCard object? This is done with help
of SmartCard class methods. There are two basic ways to go
about this: the application can either wait for a CardTerminalEvent indicating that a card has been inserted and use the event
to obtain a SmartCard object, or use the synchronous SmartCard. wai tForCard C.. ) method to wait for card insertion and obtain a SmartCard object all in one step.
If the application is event-driven, waiting for events might be the
best alternative. To do this, the application must register itself as a
CTListener with the EventGenerator. The EventGenerator
will notify the application when cards are inserted or removed. The
application can pass the CardTerminalEvent object to the static
SmartCard. getSmartCard (... ) method to obtain a Smart Card
object.
If the application is structured such that a synchronous method
would be more advantageous, the application can describe the characteristics of the desired smart card and pass them to the static wai tForCard C.. ) method.
CardRequest.NEWCARD
CardRequest.ANYCARD
Specifying card
properties
Table 10.1:
CardRequest
Constants
If the application provides a CardService class, the waitForCard (... ) method will wait until a card is inserted for which the
CardServi ce is available. After wai tForCard (... ) completes
successfully, the SmartCard. getCardService (... ) method can be
used to obtain an appropriate CardService instance.
When a card is inserted, the wai tForCard (... ) method will check
CardlDFilter
151
Using
waitForCard(. .. )
SmartCard. start () ;
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
Public CardServiceRegistry
methods
152
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 responsible 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 information 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 objects can obtain a reference to the single CardServiceRegistry
object by using the getRegistry () method.
You will recall that the Smart Card start () method configures
the CardServiceRegistry by instantiating CardServiceFactory objects and adding them to the registry list. This is done by using 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 CardServiceFactory objects by calling the getCardServiceFactories ()
method.
Figure 10.5:
The Card
Access Classes
i E - - - - - - I CardServiceScheduler
(from opencard.core.servIce)
I(from oDlllC8l'd.core.~Ice)
CardServiceReglstry
- CardServiceRegistryO
+ add{factory : CardServlceFactory) : void
- eliocateCardServiceScheduler(channel : SlolChennel) : CardServiceScheduler
# getCardServiceClassFor(clazz : Class, aid : CardlD, scheduler) : Cless
+ getCardServiceFactories() : Enumeration
# getCardServicelnstance(Class, cardlD, scheduler, smartCard, block) : CardService
+ getRegistry() : CardServiceRegistry
# getSmartCard(ctEvent : CardTerminalEvent, raq : Card Request) : SmartCard
- isCardRequesISatisfied(cardRequesl, cardlD, terminal, scheduler) . boolean
# releaseScheduler(scheduler : CardServiceScheduler) : void
+ remove(factory : CardServiceFaclory) : void
+ loStringO : Siring
Protected
registry
methods
--
153
Figure 10.6:
Channel and
Scheduler
cardChannel
frcm opencard.core.service)
# cardChannel(slotchannel : SlotChannel)
+ isOpenO : boolean
- assertCardChannelOpenO : void
+ getCardTenninalO : CardTenninal
+ setState(state : Object) : void
+ getState() : Object
+ sendCommandAPDU(cmdAPDU : ComrnandAPDU) : ResponseAPDU
+ openO : void
+ close() : void
# closeFinalO : void
+ finalize() : void
+ toStringO : String
cardServiceScheduler
I (frcm opencard.core.service)
+ 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{)
CardChannel
154
CardChannel objects per smart card. For now, however, only one
CardChannel object can be allocated per smart card.
The CardServiceScheduler allocates the CardChannel object to CardServices sequentially. If a CardService attempts to
allocate a CardChannel when all channels are already in use, the
attempt will either block until a CardChannel becomes available or
fail. The CardServiceScheduler provides methods to allocate
and release CardChannel objects. When allocating a CardChannel, the caller can specify whether or not to wait if a CardChannel
is not immediately available. If the caller does not wish to wait, the
allocateCardChannel c.. ) call will return null if no CardChannel is available.
The CardChannel class provides methods for exchanging data
with the smart card. The sendCommandAPDU c.. ) method sends an
APDU to the card, waits for the response, and returns the response
APDU to the caller.
The SendVerifiedAPDU c.. ) method exchanges data with the
card, but also obtains a password or PIN from the user before doing
so. The password is inserted into the APDU at the appropriate location, either through the user dialog provided as a call parameter, or
through the card reader. The CardChannel checks if the CardTerminal implements the VerifiedAPDUInterface. If so, the APDU
will be sent to the card reader, which will obtain the password from
the user, complete the APDU, and send it to the card. If the CardTerminal is not capable of password handling, the CHVDialog provided with the sendVerifiedAPDU c.. ) call will be used to obtain
the password.
The CardServiceScheduler has two more interesting methods.
Calling the reset c.. ) method causes a warm reset to be carried out
on the card. This method can be useful, for example, when the CardService implementation wishes to reset the card security state. The
reset (... ) method requires a blocking flag as parameter and returns
a CardID object. If the blocking flag is set to true, the method will
wait until the card has been reset and will return the new CardID
object for the card. If the blocking flag is false, the reset C.. )
method will immediately return a null object if the channel is currently in use. The getSlotChannel () method will return the
SlotChannel object associated with the CardServiceScheduler. The active slot and the CardTerminal object can be obtained
from the Slot Channel.
To round off the discussion of the CardChannel, we will mention two methods that help CardService implementations share information about the card state. It is important to realize that CardServices for a particular smart card are often related. By building
CardServiceScheduler
CHV support
More scheduler
methods
Card state
155
upon and using the functionality provided by already existing CardServices, the CardService programmer can save time and code.
When building a set of related CardServices, it is important to have
a mechanism that allows information concerning the state of the card
- the last file selected, for example - to be passed from CardService to CardService.
The setS tate (... ) and getS tate (... ) methods allow an arbitrary
object to be stored and retrieved from a CardChannel object. Related CardServices can define a common object representing the
card state and store the state object with the CardChannel.
10.1.3
10.1.3.1
The CardService
CardService
reuse
156
cardType
In:l.core.servtce
fI cardService()
+ setCardChannel(channel : cardChannel)
+ getCardChannel() : cardChannel
+ setCHVDialog(dialog : CHVDialog) : void
+ getCHVOialog() : CHVDialog
+ getCard() : Smartcard
fI initlalize(scheduler, smartcard, blocking)
fI allocatecardChannelO : void
#I releasecardChannelO : void
assetlSchedulerStillAliveO : void
Figure 10.7:
The
CardService
Support Classes
+ cardType()
+ cardType(type : intI
+ getType() : int
+ setlnfo(Object) : void
+ getlnfoO : Object
Interface
PrimaryGardServiceFactory
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 CardService base class. This class provides methods for use by the application as well as methods to be used by the CardService module. 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
called CardService module obtain a CardChannel? The CardService 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 module itself. It makes sure that a CardChannel is
available for communication with the card. If a CardChannel has
been provided via setCardChannel (... ) , then allocateCardChannel (...) does nothing. Otherwise, it uses the CardServiceScheduler to allocate a new CardChannel object.
After the CardService implementation has called allocateCardChannel (), it uses the getCardChannel () method to retrieve the CardChannel object.
Extending the
base class
Sharing the
CardChannel
CardService
methods
157
Allocate a
CardChannel
Instantiate a
CardService
CardService
initialization
158
try (
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.
CardService modules are instantiated by the CardServiceFactory (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 CardService module to be called. For this reason, every CardService
module must provide a default constructor that, as a minimum, simply calls super ( ) .
After it has created a new instance, the CardServiceFactory
will call the CardService module's initialize (... ) method,
passing it three parameters - the associated CardServiceScheduler 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 provides a method for getting the associated Smart Card object. However, no method is provided for obtaining the CardServiceScheduler object. Sometimes the CardService module will need to access the scheduler - for example, when customized CardChannel
objects are used. In this case, the CardService module must im-
plement its own ini tialize (... ) method, overriding that of the
CardService base class. The CardService module can save a reference to the CardServiceScheduler object from within its initialize (... ) method.
If the CardService module provides its own initialize (... )
method, it must be sure to call super. ini tialize (. .. ) to properly
initialize the CardService base class.
The final CardService base class method of interest to the
CardService module is getCHVDialog (), which retrieves the
current CHVDialog object stored by the CardService base class.
The CHVDialog object is needed when the CardService module
uses the CardChannel sendVerifiedAPDU(... ) method.
The remaining CardService base class methods are primarily
for use by the application.
The application calls the setCHVDialog (. .. ) method to customize the dialog used to obtain the card holder verification string from
the user.
The getCard () method provides the application with a reference
to the Smart Card object associated with the CardService. This is
primarily useful when the application needs the Smart Card bracket
functions beginMutex () and endMutex () to execute several
CardService module methods without interruption.
CHV support
Exclusive
access
10.1.3.2
The CardServiceFactory
As explained previously, the CardServiceRegistry holds references to all configured CardServiceFactory objects in the system. 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
CardServiceFactory creates CardService module objects. The
CardServiceFactory base class contained in opencard.
core. service is an abstract class that must be extended by the implementation in order to produce specific CardService module objects. 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 getCardType (... ) method passing it a CardID and CardServiceScheduler object. The CardServiceFactory analyzes the CardID to
determine whether it recognizes the card. If necessary, the Card-
CardService
Factory
159
Recognizing a
card
CardType
CardType
constructor
160
ServiceFactory can communicate with the card using the CardService Scheduler to make further determinations.
The getCardType C... ) method must return null if the card is not
recognized. If the card is recognized, it returns a valid CardType
object.
The CardType object is simply a container for information resulting from the analysis of the card. This object is passed to other
CardServiceFactory methods when attempting to create a new
CardService module instance, for example. Proper use of the
CardType object can make it easy to write a CardServiceFactory module that supports a number of different smart cards (cards
of a particular family, for example) and CardService modules.
Only the CardServiceFactory module that created it evaluates
the data it contains, so in effect the CardServiceFactory module
writer determines its meaning.
A CardType constructor can accept a numeric value that could,
for example, be used to identify a specific type of card. Additionally,
the set Info C... ) and getInfo C... ) methods can be used to store and
retrieve an arbitrary object with the CardType object.
The next CardServiceFactory method used by the CardServiceRegistry is getClasses C... ). This method accepts a
CardType object as parameter and returns a list of all the CardService classes supported.
To instantiate a new CardService object, the CardServiceRegistry will call the getCardServiceInstance C... )
method. This method is passed all parameters required for instantiating and initializing the CardService.
Both getCardType C... ) and getClasses C... ) are abstract methods of the CardServiceFactory base class. To create a CardServiceFactory to support your CardService classes, you must
extend the CardService base class and implement these two methods.
The following code fragment shows the basic framework for a
CardServiceFactory implementation.
II constructor
public TestCardServiceFactory() {}
protected CardType getCardType(CardID cid,
CardServiceScheduler scheduler)
... analyze the card, like the ATR or with additional
commands executed via the CardServiceScheduler ...
return cardType;
II class TestCardServiceFactory
Primary factory
10.1.4
The CHV Support Classes
The CHV support classes, shown in Figure 10.8, help OCF to obtain
a card holder verification string from the user. As you recall from
section 10.1.2, "The Card Access Classes", the CardChannel provides the sendVerifiedAPDU(... ) method, which is used by the
CardService when a CRV value must be sent to the card.
CHV support
--
161
CardChannel
CHVDialog
Figure 10.8
CHVSupport
Classes
+ getCHV(chvNumber) : String
f:J ------.JI
DefaultcHVDialog
Urom openeard.oore.s.rvlce)
1+ getCHV(chvNumber) : String
II DefaultCHVDialogResourceBundle
I Urom ooencard.core.ssrvlce)
1# getContentsO : ObjectDD
CardHolderVerificationGUI
I (from opencaRi.core.servtce
# 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
Application
CHVDialog
CardChannel
CHV
mechanism
DefaultCHV
dialog
Resource
bundle
162
CHVCardService
163
10.1.5
164
Figure 10.9:
CardService
Exception
Hierarchy
Table 10.2:
Checked
CardService
Exceptions
--
165
Table 10.3:
CardService
Runtime
Exceptions
CardServiceRuntimeException
Base class for all CardService runtime exceptions.
CardServiceUsageException
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 credential to the CardService, or that the smart card responded with
an invalid credential. The latter case could arise if the MAC protecting a message is wrong, for example.
CardServicelnvalidParameterException
Thrown if the application passes an invalid parameter to the CardService.
10.2
CardServiceInterface
166
Compatibility
with OCF 1.1
Table 10.4:
Optional
CardService
Exceptions
167
Figure 10.11:
Optional CardService
Exceptions
card5ervleeMisslngCredentialsExceplion
V..m ........_ )
Card5ervlceObjectNotAvallableException
Vrom opencant.opl_)
Card5ervlcelnvalidCommandExceplion
vrom openo:anI.opI.-)
cardServiceMlssingAuthorizationException
vrom ........optservlce)
Card5ervlcelnsufficlentMemoryException
vrom opencord.opI.HIVICe)
CardServiceResourceNotFoundExcepllon
vrom opencord.opt_)
opencard.opt.service Exceptions
10.3
Standard CardService Interfaces
Standard
interfaces
Application
advantages
Card provider
advantages
168
Current
standard
interfaces
10.3.1
The ISO File System Card Service
Although called an interface, this standard package contains a set of
classes and interfaces that encapsulate file access for ISO file system
cards. Figure 10.12 shows the opencard. opt. i so. f s package
containing these classes.
This package extends opencard. opt. service to obtain the
standard methods required by all CardService modules. It also extends the opencard. opt. securi ty package to make it possible to
implement secure messaging.
The file 110 capability defined by the ISO file system package is
modeled after the stream 110 classes from the java. io package.
The ISO file system package contains three interfaces that must be
implemented in order to provide support for a specific smart card.
These are the FileAccessCardService, the FileSystemCardService, and the CardFilelnfo interfaces. Figure 10.35 shows
the main abstractions provided by this package in more detail.
The FileAccessCardService provides methods for accessing
transparent as well as structured files on the smart card as defined by
the ISO 7816 specification. Methods include read (... ), readRecord (... ) , wri te (... ) , and appendRecord (... ) . These methods are
primarily intended for use by CardFile and associated classes.
The FileSystemCardService defines extensions to the ISO
7816 functionality. The application can use methods from this interface to create, delete, invalidate, and rehabilitate files.
Extending
Open Card
packages
File access
--
169
java
CardFilelnfo
CardFile
170
10
Interface
Interface
FlleAcoessCardServioe
from oPenCird.ODt.tao."
FiloSyslemCardServlce
(from opencard.opt.lso.b
getRoot() : CardFilePalit
1':."=cr=eate(par:;:;=en:=:I:7:~Ca:::rd:;:F;;:IIePa=lhr,_=:7:;::byte=m:7:::void:;:;!'
exlsts(flle : CardFllePallt) : boolean
+ delele(flle : CardFiIePalh) : void
getFllelnfo(llle : CardFllePath) : CardFllelnfo
+ invalldate(flle : CardFllePath) : void
reod(flle : CardFIIePaIh,
in!, length: Inl) : byte{]
+ rehablillate(Ilie : CardFIIePalh) : void
reodRecord(CardFIIePalh, recordNumber : Inl) : byte{!
~
reodRecords(file : CardFIIePaIIt, number: In!) : byle{!O
+ wrlle(CardFIIePallt, IoIfseI, source, soIfse~ length)
-ll1e_s)'$_
+ wrIle(CardFIIePallt, offset: In!, data : bytem : void
r - - - l . - -___- - - - ,
+ wrileRec:ot'd(fIle: CardFIIePaIIt, recordNumber, data) ~
CardFlle
appendRecord(file : CardFllePaIIt, data : byte{]) : void
-IIle_access
i..... _d.opU,o.1
many conslructors ... CardFIIe(... )
CardFl1ePaIIt
~ 'getCanonicaIPalltO: CardFllePalh
_oponantoptJ"",fs
getAbsolutePathO: CardFllePalit
CardFllePath(path : String)
.llIe.J>l1h
+ getPathO : CardFilePath
CardFIIePath(blles : byte{])
getName() : SIring
CardFilePaIIt(paIIt : CardFIIePath)
getFllelD() : shorl
+ components() : Enu_atlon
+ Is[)jrecloryO : boolean
+ append(palh : CardFllePaIIt) : CardFllePalh
+ IsFIIe() : boolean
append(cardFllePathCGmponenl):CardFIIePat
Interf
IsDFO : boolean
startsWith(prellx : CardFllePalh) : _lean
CardFlleinfo
+ isEFO : _lean
equals(filePalit : 0I>jecI) : boolean
""'" .............' ..,'
/V' IsTransparenq) : _lean
c:ommonPrefixLength(paIh : CardFilePaIIt):lnl gatFlIeID() : shorl
" - ' . IsCyoIioO : boolean
+ greateslCommonPrefix(palh) : CardFllePalh
+ is()jrec:tory() : boolean
IsVariable() : boolean
+ ohornpPreflx(prefix) : CardFilePalit
IsTransparenq) : _lean
getFllelnlo() : CardFllelnfo
+ .,hompTaiiO : _lean
IsCyolio() : boolean
creaie(daIa : bytem : void
+ tai~) : CardFllePathComponenl
IsVariable() : boolean
+ delele(relpath : CardFllePath)
numberOfComponenlsO : Inl
+ gatLenglh() : Inl
'" and more()
+ hashCode() : Inl
+ getRecordSlze() : Int
'-----"-..,----,,.---1
IoString() : String
getHeade~) : byteO
~
_at :
.,,,
file.J>lrent
CardFilePath
171
10.3.2
Interface
CardServicelnterface
(from opencard.oplservice)
+ setCHVDialogO
+ getCard()
Interface
SecureService
1/
+ provideCredentialsO
Interface
SignatureCardService
(from opencard.optsignature)
+ signDataO
+ signHashO
+ verifySignedDataO
+ verifySignedHashO
Interface
KeyGenerationCardService
(from opencard.oplsignature)
+ generateKeyPairO
+ readPublicKeyO
Interface split
Signature
generation
172
Interface
JCAStandardNames
+SHA1_RSA
+RAW_RSA
+SHA1_DSA
+ RAW_DSA
+ SHA1
+MDS
+ ZERO_PADDING
+ PKCS_PADDING
+ PKCS8_PADDING
+ ISO_PADDING
+ DES_CIPHER
Interface
KeylmportCardService
(from opencard.opt.signature)
+ importAndValidatePrivateKeyO
+ importAndValidatePublicKeyO
+ importPrivateKeyO
+ importPublicKeyO
Key
generation
10.3.3
The Application Management CardService
Interface
AppletManagerCardService
(from opt.applet.mgm!)
+ instaIiApplet(appletCode)
+ removeApplet(appletlD)
+ registerApplet(appletID)
Interface
AppletAccessCardService
I(from opt.applet.mgm!)
+ listO
+ getlnfo(appletlD)
+ exists(appletID)
Interface
EMVTags
AppletCode
I(from opt.apple!.mgm!)
+ AppletCodeO
Appletlnfo
(from opt.apple!)
~
I
I
# label : String
# aid: AppletiD
# domain: SecurityDomain
# data : Object
AppletiD
(from opt.apple!)
+ RC_O: int
......
+ RC_F: int
+ AppletlD(byte OJ
+ AppletID(int)
+ AppletID(String)
+ getRegistrationCategoryO
Figure 10.15:
Application
Management
+ AppletinfoO
+ getAppleti DO
+ getDataO
+ getDomainO
+ getLabelO
# setLabelO
# setAl DO
# setAppleti DO
# setDataO
+ setDomainO
+ toStringO
EMVAppletlnfo
(from opt.emv.mgm!)
# discrDatal : byte[]
# prefName : byte[]
# priolnd : byteO
fj---
+ EMVAppletlnfo( ... )
+ EMVAppletlnfo(TLV)
+ getPreferredNameO
+ getPriorityO
+ getDiscretionaryDataO
+ fromEMVTLVgetLabelO
+toEMVTLVO
+ toStringO
The base classes for describing and managing on-card applications, or better, applets are contained in the package opencard. opt. applet and opencard. opt. applet. mgmt. The term
"applet" as we use it in this documentation can be either a program,
which is executed on the card itself (like a typical Java Card applet),
173
174
Part III
Smart Card Application
Development Using OCF
Security
Secure
messaging
Lack of
standards
Security access
module
--
175
Internal and
External
authentication
~ PublicKeyRef
C
Credentials
176
PrivateKeyRef
SecretKeyRef
The OpenCard Framework uses credential objects to encapsulate such environment dependencies on cryptographic keys and algorithms. The application creates credentials appropriate for the envi-
KeyRef, KeyFile
Export
restrictions
11.1
Exportable OCF
version
Credentials
177
Credential for
SAM
Figure 11.1:
Open Card
Security
Classes
opencard.opt.security Package
Java security
classes
178
For the most part, the Java security interfaces used by OCF are
containers for cryptographic key information. The Key class provides
simple methods describing the key information it contains. Priva 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-
sors for DSA key parameters as well as type safety when using the
DSA algorithm. The Signature class from the Java security package is used to compute digital signatures.
11.2
1 The actual export-restricted deliverable package contains one OCF class and additional classes used by the reference implementation and demonstration code.
179
Figure 11.2:
Security Class
Categories
Interface
SymmelricCredentlal
f------H---t:s!
(from security)
Credentials
11.2.1
180
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. Relationships 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. securi 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 ..................",
;'
+ DSAPublicKey(p, q, g, y)
+ opname(argname) : return
+ getAlgcrithm() : StrIng
+ getEncoded() : by1e{)
+ getFormat() : string
+ getParams() : java ... DSAParams
+ opname2(argname) . return
+ get
Biglnteger
'"
- - - --
"",m_"d._
+ DSAParams(p, q, g)
+ opname(argname) : return
+ getG() : java.math.Biglnteger
+ getPO: java.math.Biglnteger
+ geIQ(): java.math.Blglnteger
yo :
DESKey
- -- --- --
RSACRTKey
-"
DSAPublicKey
(ft'Om jaVU4lCUrtty.
--
"""HI
- - -
-~I DSAParams
Figure 11.3:
Cryptographic
Key Classes
.1
(ftOm1~~_
.lI!Om ......DSAPriyateKey
__
+ DSAPrivateKey(p, q. g, x)
+ getAlgcr~hmO : StrIng
+ getEncoded() : bytell
+ getFormat() : String
+ getParamsO : Java ... DSAParams
+ getXO . Biglnteger
~~I
-I
---------------_-1>\
i (ftOm . . . . . .- - .. .urIM
--------- ' -
OSAParams
Key
RSAPubllcKey(ftOmjavL......,
I....m.....................
+ RSAPublIcKey(elen, e, m. keylen)
+ RSAPublIcKey(e. m)
+ getAlgcrithm() : StrIng
+ getEncoded() : by1e{)
+ getFormat() : string
+ maxlnputlengthO: int
+ maxOUtputlength() . Int
+ modulus() : Bigln1eger
+ publicExponent() : Biglnteger
.... ....
RSAPriyaleKey
....m.....................
PubllcKey
""'mjaWo_
11.2.2
The Smart Card Key Classes
Different types of smart cards store keys in different ways. File system 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 selection. 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.
181
Key references
Figure 11.4:
Smart Card Key
Classes
java.lang.security Package
PublicKeyFile
(from security)
PrivateKeyFile
(from security)
SecretKeyFile
(from security)
+ PublicKeyFile(directory:
+ PrivateKeyFile( directory :
+ SecretKeyFile(directory:
+ getAlgorithmO : String
+ getDirectoryO : Card File Path
+ getEncodedO : byte[]
+ getFormatO : String
+ getKeyNumberO : int
opencard,opt.security Package
Key files
Signing data
182
The PublicKeyFile, PrivateKeyFile, and SecretKeyFile classes implement the corresponding key reference interfaces
specifically for ISO file system oriented cards. They contain a CardFilePath object that points to the proper directory on the card and a
key number to be used within that path.
The digital signature CardService implementations provided in
the com. ibm. opencard. signature package of the reference implementation use these classes. For example, in order to sign data
using the MFCSignatureService, the application must create a
PublicKeyFile object that points to the desired key on the smart
card. This object is passed to the signData (... ) method along with
the data to be signed. The MFCSignatureService uses information
from the PublicKeyFile object to select the key before passing the
data to the card.
11.2.3
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.
Interface
Credential
CredentialStore
I (from
opencard.opt.securitvl
# CredentialStoreO
(from security)
Interface
SecurityDomain
(from security)
Figure 11.5:
CardService
Interface
Classes
CredentialBag
(from opencard.opt.security)
+ CredentialBagO
+ addCredentialStore(credstore : CredentialStore) : void
+ getCredentialStore(cardlD : CardlD, clazz : Class) : CredentialStore
+ getCredentialStores(cardlD : CardlD, clazz : Class) : CredentialStore(j
Interface
Interface
SecureService
AutCardService
(from opencard.opt.security)
+ provideCredentials(
domain: SecurityDomain,
(from opencard.opUecurity)
+ closeApplicationO : void
+ externalAuthenticateO : boolean
+ getChallengeLengthO : int
+ internalAuthenticateO : byte[]
As discussed previously, the credential encapsulates a cryptographic algorithm along with key data. Since the methods needed by
the credential are highly dependent on the algorithm used, the eredential interface provided by OCF is just a tag interface.
This interface is extended for some common algorithms by other
classes in this package, which we will discuss shortly. If needed,
other CardService implementations can extend Credential for
algorithms not yet supported by the standard OpenCard package.
Credentials whose algorithms are implemented completely in
software can be provided along with the CardService. To use
these, the application must instantiate the Credential by providing
the required key material.
If the application environment calls for the keys and algorithms to
be stored in a SAM, the application will have to implement aCredential for the card or cards in use.
Credential,
algorithms,
keys
--
183
CredentialStore
CredentialStore
methods
CredentialBag
Setting up
credentials
Secure
CardService
Credentials for a specific smart card type are collected in aCredentialStore object. CredentialStore is an abstract class that
must be implemented to support a particular type of card. The CardService provider generally implements the CredentialStore
since it must match the CardService.
The fetchCredential (... ) and storeCredential (. .. ) methods access the credentials with the help of an identifier whose type is
defined appropriately for the smart card.
Support for different types of smart cards is provided through the
CredentialBag, which is a container for CredentialStore objects.
The application creates Credential objects for all cards to be
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 CredentialStore and Credential objects. Since the application always
passes all credentials to the CardService, the application does not
need to be card specific.
A CardService that implements secure messaging must implement the SecureService interface. The provideCredentials (...) method allows the CredentialBag to be passed to the
CardService.
Security
domain
Along with the CredentialBag, the provideCredentials (...) 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 implemented 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 supported and sets up the CredentialStore and CredentialBag
objects. This can be done during initialization if the user operation is
clear from the beginning.
184
Filling the
CredentialBag
store.storeCredential(O,
new DESSecureCredential("Ox6b258f15d07c43ea";
store.storeCredential(l,
new DESSecureCredential("Ox31323437383b3d3e";
store.storeCredential(5,
new DESSecureCredential("Ox70737576797a7c7f";
rootKeyBag.addCredentialStore(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 implementation.
The DESSecureCredential class implements the DES algorithm 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
SecureCredentla1
fromacctsl
+ DEsslgnCredenllal(key : DESKey)
+ getstrongRandomO : byteD
.. 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
--
185
Card
independent
programming
186
11.2.4
Credentials
I(trom security)
RSASignCredential
+ RSASignCredenlial(privaleKey : RSACRTKey)
+ RSASignCredenlial(privaleKey : RSAPrivateKey
+ sign(dala : byteO) : byteO
+ getlnputLengthO : int
..... rlty)
DSASignCredential
+ DSASignCredenlial(privateKey : DSAPrivateKey
+ sign(dala : byteO) : byteO
+ gellnpulLength() : int
Figure 11.7:
Credentials
Interface
SymmetricCredential
t------[>I
(trom security)
Defined
credentials
AutCardService
187
11.3
OCF in a
browser
188
11.3.1
System and
shared library
access
JDK 1. 1 security
model
Browser
security models
OCF concept is
browser
independent
--
189
11.3.2
Invocation of Privileged Methods
SystemAccess
Installing
browser-specific
object
OCF provides specific SystemAccess subclasses for the predominant web browsers. The applet detects the browser environ-ment
and installs the appropriate support. The applet can install opencard. opt. netscape. NetscapeSystemAccess when run-ning
under Netscape Navigator and opencard. opt. ms. MicrosoftSystemAccess when running under MS Internet Explorer. The
methods in these classes obtain the needed privileges before actually
making a call to a privileged method as shown in the following example.
Netscape
SystemAccess
method
190
Figure 11.8:
OCFSystem
Resource
Access
Serial Port
File
System
System
Properties
11.3.3
Security Implications
The mechanism described in the previous section allows the OpenCard Framework to access protected system resources via a common
interface, even on different browsers.
To assure that a SystemAccess instance can not be misused by
other applets [NET97], the scope of each SystemAccess instance is
limited to the thread that installed the specific subclass. In other
words, each thread has its own SystemAccess instance.
If an applet uses OCF, it must be packaged with the appropriate,
browser-specific subclass of SystemAccess and must install an instance of this class in each thread that uses OCF.
This approach guarantees that no applet that is not properly
signed, but that is running in the same Java Virtual Machine as a
signed applet, can make use of the system resources obtained by that
signed applet. The situation is depicted in Figure 11.9.
191
Figure 11.9:
Hostile Applets
Cannot Access
Resources
JVM
Serial Port
Protected
,,",,\"~T"'rn
File
System
System
Properties
" ..,..,LJU.
192
12 Using OCF
12.1
195
12.2
12.2.1
Setting the OCF Configuration Properties
As we have explained in Chapter 9.1 ''Terminal Layer Core Components", the CardTerminalRegistry singleton keeps track of the
configured CardTerminal objects and the CardServiceRegistry keeps track of all CardServiceFactory classes that are able
to instantiate a CardService. When the framework starts up, these
registries are initialized based on the OCF configuration properties.
The OpenCard. terminals property defines how the CardTerminalRegistry is initialized, the OpenCard. services property
defines how the CardServiceRegistry is initialized.
The syntax of the property string for either property is as follows:
<record-O> <record-I> _ <record-n>
where records are separated by a white-space and each record consists of a class name and optional string parameters separated by a
"I", i.e.
class-name I <parameter-I> I
... I <parameter-N>
196
12 Using OCF
1. [java.home]/lib/opencard.properties
2. [user.home]/.opencard.properties
3. [user.dir]/opencard.properties
4. [user.dir]/.opencard.properties
where [xxx.yyy] are the respective path variables as defined in the
default system properties. It loads the properties from each file, in
tum merging them with the system properties. If the properties file
being read contains a property name that has already been defined in
the properties set, the new definition will be ignored by default.
It is possible to override a property that is already defined in the
properties set. You can do this by defining the property name anew
and adding an additional property to your property file with the name
name. override that has the value true.
A typical opencard.properties file is:
# Configure the CardService Registry:
Example
opencard.
properties
OpenCard.terminals =\
com.gemplus.opencard.terminal.\
GemplusCardTerminalFactorylmygcrlGCR410lcOMl
# Configure Tracing. Detailed for all samples only:
OpenCard.trace = opencard:l com.ibm:l samples:7
You can determine the locations where OCF will look for the
opencard.properties file using the following short application:
197
import java.util.Properties;
public class queryPropertiesLocation
public static void main( String[] argv
Properties props = System.getProperties();
System.out.println(
"Looking for OpenCard Properties file in:\n\t" +
props. get Property (" java. home") +
"\\lib\\opencard.properties\n\t" +
props . get Property ("user . home" ) +
"\\.opencard.properties\n\t" +
props. get Property ("user. dir") +
"\\opencard.properties\n\t" +
props. get Property ("user. dir") +
"\\.opencard.properties\n") ;
12.3
opencard.core.service.SmartCard;
opencard.core.service.CardRequest;
opencard.opt.iso.fs.FileAccessCardService;
opencard.opt.iso.fs.CardFile;
198
12 Using OCF
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, because during framework startup all configuration work and initialization of attached card terminals must be done. This could add unexpected delays when done implicitly during an access. In addition, errors 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 () command 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. shutdown () call into the finally block.
try {
SmartCard.start() ;
At first glance, it may seem strange that shutting down OCF could
raise another exception. However, the shutdown may cause dynamic
199
12.3.2
Obtaining a SmartCard Object via
waitForCard( ... )
After we took care of starting and closing the framework, we can
now use OCF to interact with the smart card. We make our program
wait until the user inserts her card. For waiting, we use SmartCard. wai t ForCard (CardReque s t) , which blocks until a card is
inserted that matches the given CardRequest.
II
II
{
A smart card was inserted that does not match
Handle how it would be appropriate in your app
else {
II Here we need to add code to work with the card
200
12 Using OCF
card to be inserted uses CardTerminalEvents. This alternative requires only slightly more programming effort.
We will demonstrate the alternative in the next sample program. In
this first simple example here we will wait synchronously for the card
to be inserted.
After we have worked with the card and do not need to access it
any longer, we call the close () method to indicate that the card is
no longer needed in this application.
12.3.3
201
12.3.4
If you want to use another smart card instead of the card that is provided in this book, you need to make sure that a FileAccessCardService 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
In Section 13.1 "Internet Stock Brokerage", we present a demo application that allows buying stock over the Internet and having the order
digitally signed by the personal signature smart card. In this section,
we show how the smart card related part of the brokerage applet can
be implemented using the OpenCard Framework.
The client side of this demo application executes as an applet in a
web browser. The applet should not make any assumptions on when
the signature card is inserted. The user may have inserted the signature card before the applet was started or she may not insert it until
being prompted to do so. In addition, if the applet is used for several
202
12 Using OCF
12.4.1
Attributes
The attribute card is a reference to a Smart Card object, which is
the application's representation of an inserted smart card.
For the services that we are expecting from the smart card, we
need references to the appropriate OCF CardServices. For the services of reading and writing data, we maintain in fileService a
reference to a FileAccessCardService. For generating digital
signatures, we maintain in signatureService a reference to a
SignatureCardService. We set the references card, fileService, and signatureService when a smart card is inserted and
reset them to null when the smart card is removed.
It is possible that our SignatureCard objects are used in situations with more than one card terminal slot. To react appropriately on
card removal events, we need to test if the event came from the slot
that contained our signature card. We keep a reference to this slot in
the attribute slot.
We create the attribute earlierException to temporarily store
exceptions that may be caught in the cardInserted method to be
re-thrown or analyzed in one of the access methods.
--
203
12.4.2
Constructor
In the constructor, we start OCF by calling the static start ( )
method of the class Smart Card. Then we add the object being created as a listener for CardTerminalEvents by calling the method
addCTListener (... ) of the EventGenerator singleton. This singleton monitors all registered card terminals and sends card insertion or
card removal events to its listeners. You can always obtain the
EventGenerator singleton by calling the static method EventGenerator.getGenerator().
Once the SignatureCard object is registered as a CTListener,
the EventGenerator singleton will call the registered object's
cardInserted () or cardRemoved () method whenever a card is
inserted or removed respectively. To find out about any cards, which
were inserted in a reader before the object was registered as a
CTListener, we use createEventsForPresentCards () to create card insertion events for cards which are already present:
SignatureCard() throws SignatureCardException
try {
SmartCard.start() ;
EventGenerator.getGenerator()
.addCTListener(this) ;
EventGenerator.getGenerator()
.createEventsForPresentCards(this) ;
204
12 Using OCF
12.4.3
cardlnserted()
The OpenCard Framework calls the method cardInserted ( )
whenever any smart card is inserted in a card terminal. We are only
interested in cards for which at least a FileAccessCardService
can be instantiated. Therefore, we create a card request, specifying
FileAccessCardService . class as the desired interface and try
to get a smart card object using the event obtained in the parameter
event.
If the getSmartCard (... ) was successful, we call the method allocateServices () (see below) to create the file access and signature services required by the other methods. As the method cardInserted (... ) is a listener method that is called by the framework, it
may neither perform any long running operation nor throw an exception. Therefore, we store any exception that might occur and keep it
for later processing by one of the methods sign (... ) , getCardHolderData () ,or setCardHolderData (... ) .
In addition to the functional code, we insert two tracer invocations
with different levels and purposes into cardInserted (). We use
the method Tracer. info (String, String) to inform that the
function cardInserted ( ) was entered. With the call to
Tracer. critical (String, Throwable) we record information
about the exception at the place where it was caught.
public void cardInserted(CardTerminalEvent ctEvent)
i Tracer. info (" cardInserted" ,
"Got a CARD_INSERTED event.");
try {
205
In all methods of class SignatureCard we do not leave the handling of OpenCard exceptions to the caller of the method because we
want to encapsulate all OCF dependencies in that class. In addition,
in the method cardlnserted () we must deal with exceptions in a
special way, because in this method we must immediately return to
the caller. Therefore, we merely store an exception that occurred in
the instance variable earlierException to later handle it in one of
the other methods.
12.4.4
allocateServices(SmartCard, int)
The private method allocateServices (... ) allocates a file access
service and a signature service for a smart card represented by a
given smart card object. First, we get a file access service by calling
the getCardService (... ) method of the smart card object specified
by the parameter card. Then we use the same mechanism for obtaining a signature service.
If we were successful in getting the first service, we set the attribute slot with the reference passed in as a parameter. This enables us
to react appropriately on card removal events.
private void allocateServices(SmartCard card, int slotID)
throws ClassNotFoundException,
CardServiceException {
fileService = (FileAccessCardService)
card.getCardService(
FileAccessCardService.class, true);
II If we get here, remember the slot for card removal
slot = slotID;
SBCHVDialog dialog = new SBCHVDialog() ;
fileService.setCHVDialog(dialog) ;
try {
signatureService
(SignatureCardService)
card.getCardService(
SignatureCardService.class, true);
signatureService.setCHVDialog(dialog);
II Special handling of failure to allocate
II a signature service:
catch (ClassNotFoundException e)
iTracer.critical ("allocateServices" , e);
206
12 Using OCF
We provide both card services with a cardholder verification dialog, using the method setCHVDialog (... ). We set this dialog because the card is set up with the cardholder data file as well as the
private key file for generating signatures protected by a password.
The dialog must implement the interface CHVDialog. This interface
declares the method getCHV (int), which is called by the service
whenever a cardholder verification is required for accessing a certain
function of the smart card.
allocateServices (... ) is private and only called from other
methods of the class SignatureCard. Therefore, we do not need to
handle all exceptions within the method. The only exception that we
want to handle is the ClassNotFoundException that might occur
from trying to allocate a signature service. This exception is expected
for a card without digital signature capability, as the card provided in
this book. With such a card, our program will still be able to read and
write the cardholder information.
12.4.5
cardRemovedO
OCF calls the method cardRemoved () whenever a card is removed
from a card terminal. We use it to reset the references to the smart
card object and the services to indicate that no card is present anymore. Note that we do not assume that only one card reader with one
slot is connected to the system. We only reset the references to the
card services, the card, and the slot if the card was removed from the
slot we are using with our signature card:
public synchronized void cardRemoved(
CardTerminalEvent ctEvent)
i Tracer. inf 0 ( "cardRemoved" ,
"Got a CARD_REMOVED event.");
if (ctEvent.getSlotID() == slot)
i Tracer. info ( "cardRemoved" ,
"The removed card was ours.");
card = null;
Slot = 0;
fileService = null;
signatureService
= null;
207
12.4.6
signatureCardPresent(}
The method signatureCardPresent () checks for the presence of
a signature card. This is the case if a card is present for which a file
service and a signature service were instantiated.
public boolean signatureCardPresent()
return fileSystemCardPresent()
&& (signatureService !; null);
12.4.7
getCardHolderData(}
The method getCardHolderData () reads data about the cardholder from the smart card, i.e. her name and e-mail address, and returns this data in a byte array.
First, we check whether an exception has been thrown by a preceding invocation of the method cardlnserted ( ) , and re-throw the
exception if that is the case. This is done in the private method
propagateAnEarlierException () (see Section 12.4.8).
public byte[] getCardHolderData()
throws SignatureCardException,
IOException, FileNotFoundException
try {
propagateAnEarlierException() ;
208
12 Using OCF
Next, we create a card file input stream and use it to create a data
input stream. OCF lets us operate with these streams like with standard Java I/O streams. We create a byte array with the size of the
cardholder data file. We determine that size by calling the method
getLength () of the file object representing the cardholder data file.
We read the data from the file into the new byte array and close the
file. Finally, we return the byte array with the cardholder data.
II
II
209
12.4.8
propagateAnEarlierExceptionO
The private method propagateAnEarlierException () checks
whether there was an earlier exception that was not handled, because
it occurred in a method that had to return immediately. If this is not
the case, propagateAnEarlierException () has no effect.
If the attribute earlierException contains an earlier exception,
we wrap it into a new SignatureCardException object which we
then throw. We reset the attribute containing the earlier exception because the exception is handled now.
private void propagateAnEarlierException()
throws SignatureCardException
if (earlierException == null)
return;
SignatureCardException signCardExcp
new SignatureCardException("Exception of "
+ earlierException.getClass() .toString()
+ " from earlier method execution:",
earlierException) ;
earlierException = null;
throw signCardExcp;
12.4.9
setCardHolderData(String)
The method setCardHolderData(String cardHolderData)
writes the given cardholder data to the smart card.
In the first part, which we do not show here, we perform the same
steps as in getCardHolderData () . Again, we try to obtain a card
file object that we refer to as file.
Once we have the card file object, we use standard Java 110 stream
mechanisms again, this time for writing to the card. We create a
CardFileOutputStream and then, using this stream, a DataOutputStream that we call dos, to which we then write.
210
12 Using OCF
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 algorithm in combination with SHA-l and Zero-Padding. If this is successful, we return the obtained signature as a byte array, otherwise
we return null:
byte[] sign(int keyNumber, byte[] data)
throws SignatureCardException, InvalidKeyException
byte []
try (
signature
null;
= signatureService.signData(
kf, JCAStandardNames.SHA1_RSA,
JCAStandardNames.ZERO_PADDING, data);
catch ...
--
211
Note that the sign (... ) method will not work with the card provided in this book, because this card is not capable of performing
public key cryptography.
12.4.11
close()
12.4.12
Class SignatureCardException
Our class SignatureCard uses SignatureCardException objects to communicate all exceptions from the smart card access
through OCF to the caller.
Strategies of exception handling are a topic in its own right. A
good and exhaustive strategy might be to create an own exception
type for the most likely failures, like no smart card reader was found,
no card was found, a PIN was not accepted by the card, or the card
was not of the expected type. The application can then handle these
failures with good user guidance. Errors, which obviously are caused
by program defects, like for example null-pointer exceptions, are not
caught and bring the program to a halt at the place where they surfaced.
For this example we have tried to not let the straight functional
code become buried in exhaustive error handling. We have used the
single exception type SignatureCardException for all failures
212
12 Using OCF
that are no program defects. To allow the caller to find out more
about the failure, we pass the primary exception as an attribute of the
SignatureCardException. The attribute can be obtained with the
method get PrimaryExcept ion () .
We also add the primary exception's message text to the text
passed in when creating the new SignatureCardException object. Thus, the message text that is returned or displayed by the functions getMessage () or printStackTrace () contains the primary
exception's text in addition to the new text.
Here is the complete source code for this class with commentary
lines removed:
public class SignatureCardException extends Exception {
private Exception primaryException;
public SignatureCardException(String message)
super (message) ;
primaryException = null;
12.4.13
213
compiling it, and running it with the card provided in this book and
with the simple test stub Test. java. You will find all files for this
sample in samples. stockbroker. We recommend that you try different trace settings in opencard. properties to follow the control
flow.
After you understand the concepts and mechanics of this sample,
you might want to review the original complete Internet Stockbroker
demo that is part of the OCF reference implementation. You will not
be able to execute this demo with the card provided in this book.
However, the demo source code will help you to understand how the
class SignatureCard that we developed in this section fits into the
overall application context.
214
12 Using OCF
Today, a lot of companies and businesses are transforming into ebusinesses to improve their internal efficiency, to improve the link to
their suppliers, and to reach new markets via the Internet. The rising
number of e-business transactions and increasing transaction values
make security a top priority. As a result, integration of secure tokens
like smart cards into e-business applications becomes more and more
important (see Chapter 3).
In this chapter, we give two examples of using smart cards to secure e-business applications. In Section 13.1, we describe an Internet
stock brokerage scenario, where the smart card is used to digitally
sign stock orders. In Section 13.2, we present a scenario, where smart
cards are used to pay via the Internet.
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 architecture 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
In an Internet stock brokerage application, apart from the usual Internet security issues, especially data integrity and non-repudiation are
important to the broker. Data integrity means that orders sent from
the customer to the broker cannot be changed without detection. NonU. Hansmann et al., Smart Card Application Development Using Java
Springer-Verlag Berlin Heidelberg 2002
--
215
13.1.2
216
Tier-3
Certificate
Server
Database
Server
Figure 13. 1:
3-Tier Architecture
with Clients Using
Smart Cards
Transaction
Server
Application
Server
Tier-2
Tier-1
13.1.3
Protocols
Given the architecture described above, all application functionality
is located on the application server in HTML-Pages, applets and
servlets. In this scenario, ordering shares works as shown in Figure
13.2.
Smart
Card
Application
Server
Client
Get HTML-page with
Database
Server
Figure 13.2
Simplified
Representation
of the Purchase
Process
Transaction
Server
app~
to sign Order
Digital Signature
Place Order
Confirmation
og Confirma1jp
Confirmation
--
217
13.2
Distributed Payment Systems
In this section, we give a short introduction to card-to-card payment
schemes. We give a motivation to enable card-to-card payment
schemes for the Internet and present an architecture that allows for
secure card-to-card payments via the Internet, using the OpenCard
Framework for card access.
218
13.2.1
219
Figure 13.3:
A Payment
According to the
GeldKarte
Payment
Scheme
Purse Card
Terminal
Merchant Card
...
Card Info
Debit (7)
Debit Response (8)
...
Challenge (2)
Card Info
..
...
...
Payment (9)
--""
When the terminal is switched on, it reads certain data from the
merchant card. This data is needed whenever a payment shall be conducted. 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 information 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 conducts the card-to-card payment protocol:
I. The terminal sends a command to the merchant card to obtain a
random challenge to be used.
2. The merchant card generates a random number and sends it back
as the random challenge.
3. The terminal sends the challenge and the key-generating key ID
to the purse card with a begin-debit command.
4. The purse card sends back a begin-debit response that amongst
other data contains the merchant card's random challenge and is
signed by a message authentication code (MAC).
5. The terminal sends the relevant parts of the begin-debit response
to the merchant card with a begin-payment command. As it contains the merchant card's challenge and is signed by a MAC, this
220
13.2.2
Card-to-Card Payments via Internet
Today, a large number of companies already offer their goods or
services in the Internet and some of these companies also allow customers to purchase goods or information via the Internet. In most
cases, the customer's credit card has to be used to pay. This has some
drawbacks. Using a credit card is quite expensive for the merchant,
because credit card companies charge to the merchant significant
percentages of the paid amount, depending on the business segment
of the merchant and the value of the purchased goods. Also, credit
cards do not allow for anonymous payments. Credit card companies
--
221
exactly know when and where a customer buys something with his
credit card.
Using a prepaid and anonymous electronic purse scheme overcomes 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 merchant 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 articles with additional background.
In the rest of this section, we describe a Distributed Acceptance
Terminal for payments via the Internet using the GeldKarte.
13.2.2.1
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 Computer 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:
1. The customer navigates to the merchant's web site using a browser
like Netscape Navigator or Internet Explorer, selects goods and
presses some "BUY" button.
2. An applet is loaded from the merchant's site. This applet is able to
conduct the GeldKarte payment protocol and to access the inserted
card using the OpenCard Framework. Alternatively, this applet
could also be present on the customer's machine already, e.g. if a
bank decides to distribute it on CD.
3. On the merchant's server, there is a servlet that can conduct the
merchant's part of the payment protocol and can access present
merchant cards via OpenCard Framework.
4. The customer is asked by the applet to enter his card, if it is not already inserted.
5. The payment protocol is conducted between the customer applet
and merchant servlet. Before the amount on the card is actually re-
222
Purse Card
Server
Merchant Card
...
--
- ..
~n
Debit (13)
..
Figure 13.4:
The Message
Trace ofa
GeldKarte
Payment via
Internet
Payment (10)
.-
Payment (16)
Payment Response (17)
As Figure 13.4 shows, there is no direct relation of messages exchanged with cards and messages exchanged via the Internet. Some
parts of the protocol can be conducted with the local smart card and
do not require communication with the peer on the other side of the
network connection.
When the merchant part of the distributed payment system is
started, it needs to initialize by reading information from the smart
card, which will be required in later payments. Having done this, it
waits for payments to be initiated by the client.
223
13.2.2.2
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.
224
Figure 13.5:
A Merchant
Accepts
Payments
Herself
Merchant WebServer
with Merchant Cards
or Token
Database
Server
Cards
A Service
PaymentServer with
Merchant Cards
or Token
Provider Accepts
Payments on
8ehalfofa
Merchant
........................."!~~~~.~~.........,~~:....................
Merchant
WebServer
Database
Server
Customer
Appliances
with Purse
Cards
225
To allow for scenarios like the latter, the payment protocol needs
to be independent from the trading protocol. The trading protocol
would be conducted between the customer's computer and the merchant's server, but in between, the payment protocol would be conducted with the payment server. Figure 13.7 shows how the payment
protocol may be embedded in a purchase transaction.
Figure 13.7:
The Payment
Protocol
Embedded in a
Trading
Protocol
Payment
Applet
Request HTML page
Payment
Server
Browser
HTML
Order
r------...
.-----
pa~
Web
Server
e with offers
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
An advantageous architecture is a three-layer stack, where the first
layer is responsible for card access, the second layer is responsible
for protocol handling and the third layer is the application layer as
shown in Figure 13.8. The card access layer uses the OpenCard
Framework for access to cards. This makes the implementation platform independent and makes readers exchangeable. The software
will run on workstations, personal computers, and network computers
on the client side and different kinds of servers.
226
Figure 13.8:
Architecture of a
Web-based
Distributed
Payment System
227
Internet
Customer
Term i nal
.,
,
Purse
Card
"
Merchant
Card
13.2.4
Implementation
In this section, we present a prototype implementation we developed
at IBM. Our approach entirely relies on Java technology, both on the
client as well as on the server side. Figure 13.10 shows the software
stack we chose.
228
Payment
Applet
Web
Browser
OCF
...-"I
. :::: .....,.
Java
Virtual
Machine
Trading
Servlet
Payment
Servlet
OCF
javax.servlet
Ii
Web
Server
Java
Virtual
Machine
13.2.4.1
13.2.4.2
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import opencard.core.*;
import opencard.core.service.*;
import opencard.core . terminal.*;
public class PaymentServlet extends HttpServlet
SmartCard card_ = null;
229
To implement the payment protocol in the servlet, we had to override the methods init, doPost and destroy. As the same mechant
card shall be used by the payment servlet for handling all incoming
requests, we use the instance variable card_to store a Smart Card
object to be initialized in the ini t method and be used in the doPost method.
The ini t method is invoked when the servlet is loaded. The application server loads a servlet at startup, when the first HTTP request
for that servlet is received or when the administrator explicitly loads
it. A servlet's ini t method has the responsibility to initialize the
servlet and allocate all necessary resources so that the servlet is ready
to process incoming requests. The following code sample shows a
simplified version of the ini t method of our payment servlet.
public void init(ServletConfig config) throws
ServletException {
super.init(config) ;
try {
SmartCard.start() ;
CardRequest cr =
new CardRequest(HaendlerKarteSvc.class);
card_ = SmartCard.waitForCard(cr);
MerchantCardService merchant Service
(MerchantCardService)
card.getCardService(MerchantCardService.class,
true) ;
MerchantProtocol merchant Protocol
new MerchantProtocol(merchantService);
serverAdapter_=
new PaymentServerAdapter(merchantProtocol);
card_.beginMutex() ;
catch (Exception e)
throw new UnavailableException(
"Initialization failed: " + e.getMessage());
230
The payment servlet does not require any parameters from the
servlet configuration; thus we pass the ServletConfig object config to the ini t method of the super class HTTPServlet and ignore
it in due course. Our payment servlet handles incoming payment requests using a Merchantprotocol object for interaction with the
smart card and a PaymentServerAdapter object for receiving and
parsing HTIP requests and dispatching them to the appropriate
methods of the protocol object. Thus, our ini t method needs to start
the OpenCard Framework, obtain a SmartCard object for the merchant card, get the appropriate MerchantCardService from the
Smart Card object, create a MerchantProtocol object from that
card service and create a PaymentServerAdapter linked to the
protocol object. Finally it calls the beginMutex method of the
Smart Card object to assure exclusive access to the card.
The doPos t method is called whenever the server receives a
HTTP POST request addressed to the servlet. The server passes an
HTTPServletRequest and a HTTPServletResponse to the
service method, which processes data read from the input stream obtained from the request object and writes the result to the output
stream obtained from the response object. The following sample code
shows a simplified version of the service method.
public void doPost(ServletRequest req, ServletResponse rsp)
throws ServletException, IOException {
DataOutputStream os ~
new DataOutputStream(rsp.getOutputStream());
DatalnputStream is ~
new DatalnputStream(req.getlnputStream());
try {
byte [] data ~ new byte [is. readInt ()] ;
is.readFully(data) ;
data ~ serverAdapter_.receive(reqMsg) .getContent();
os.writelnt(data.length) ;
os.write(data, 0, data. length) ;
os.flush() ;
catch (Exception e) {
II return empty response to indicate error
byte[] data ~ new byte [0] ;
os.writelnt(data.length);
os.write(data, 0, data. length) ;
os. flush () ;
throw new ServletException(
"Error processing request: " + e.getMessage());
231
232
14.1
............ p
..;:.~~--I
Figure 14.1:
The Process for
Developing a
Card Applet
--
233
14.2
Inside the Java Card
To better understand what our card applet needs to do and how we
drive it from the off-card application, we first take a look at the objects on a Java Card and their life cycle.
14.2.1
Package
Contents
java.lang
javacard.framework
Classes and interfaces for the core functionality of a Java Card applet.
This package provides smart card specific interfaces like IS07816 and PIN, and classes like
Applet, AID, and APDU. In addition, it contains the class JCSystem, which corresponds to
JDK's java.lang.System.
234
javacard.security
javacardx.crypto
14.2.2
Lifetimes of On-card Programs and Objects
Another important distinction between a Java environment on a
workstation and the Java Card environment is the lifetime of the
applets and of the objects owned by the applets.
The applets installed in the card have a long lifetime. They will
terminate only when they are explicitly de-installed. Otherwise, they
will stay alive as long as the card is usable.
The objects created and owned by an applet are allocated in the
EEPROM by default and thus persistent. The specification defines a
way to create transient arrays but does not define a way to make an
object transient. The Java Card system class JCSystem provides
makeTransient ...Array () methods for Boolean, Byte, Short,
and Obj ect. Transient arrays are alive until the card is powered
down or the applet is deselected.
When an applet is installed on the card, its installation method
public static install (... ) is called. This method should allocate all objects the applet will use, thus making sure during installation that sufficient space will be available for the applet later. Otherwise, an out-of-memory failure should surface already during installation. If the installation was successful, the applet must call one of its
inherited register () methods to get its application identifier registered with the Java Card runtime environment.
After an applet has been installed, it can be used by an application.
For communicating and working with an applet, the application must
select it by sending an appropriate select command, a SELECT
APDU with the application ID of the applet. The applet that became
selected is called the "active" applet. All APDUs that the application
is sending to a card are passed to the active applet. This applet remains active until another applet is selected.
Lifetime of the
applets
Lifetime of the
applet's
objects
Selecting the
active applet
235
process(APDU)
14.3
Selection
processing
236
process(APDU)
Our sample applet has four methods, which can be called from the
off-card application through the appropriate APDU: performCHV (APDU), getField (APDU), setField (APDU), and selectFile (APDU) .
237
OwnerPIN
1**
* The OwnerPin must be matched before this applet
* cooperates.
*1
private OwnerPIN pin_
= new OwnerPIN(PIN_TRY_LIMIT, MAX_PIN_SIZE);
deselect()
1**
* Actions to be performed if this applet is deselected.
*1
public void deselect()
pin_.reset () ;
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
238
ISOException
and IS07816
!=
(byte) Ox80)
ISOException.throwlt(
IS078I6.SW_CONDITIONS_NOT_SATISFIED) ;
I I For brevi ty, the checks for PI and P2 not shown here ...
false)
IS078I6.SW_SECURITY_STATUS_NOT_SATISFIED) ;
setOutgoing-AndSend(. .. )
(short) 0);
&
setField(APDU)
buffer [4]) ;
239
240
setOutgoingLength(short)
and
SendBytesLong(.. .)
II Le currently
short le = apdu.setOutgoing();
apdu. setOutgoingLength (bcField.length) ;
Now we have seen all run-time functions of our applet. The bit
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:
instal/(.. .)
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();
me.register() ;
241
The constructor allocates all instance data for our applet. To prevent that the applet fails during runtime for lack of memory, the constructor already claims all memory needed for the lifetime of the
applet:
/**
* 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 objects 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 objects 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. Therefore, 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.
242
14.4.1
AooletEroxv ..n
AnnletP..mxv.2
ApplelProxy 1
DIU.
I.e
..,
P2
INS
D.U1
ISO 7816
SW,
APDU's
Figure 14.2:
All
Communication
between OCF
and the Java
Card is through
ISO 7816
APDUs.
SW2
Java Card
OS Kemel
The communication layer between the proxy and the card is standard 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
hold knowledge about the card, we can best make them subclasses of
the OCF CardService. As specialized card services, before sending
APDUs, card applet proxies must allocate a card channel for communication with the Java Card from the card service scheduler -like
any other card service.
Applet proxies
are special
CardServices
243
Card applet proxies as well as all other card services! may be used
in multithreaded programs. This means they may be instantiated several times by different threads so that concurrent access by different
instances to the card must be serialized. If the card channel has already been allocated by another card applet proxy, the threads of activity of card applet proxies trying to allocate it are blocked until the
current owner of the channel releases it.
As there might also be several instances of the same card applet
proxy class, it must be possible to share the associated card applet's
state so that the different proxy instances interact properly. A card
channel may hold a card state object. We let this card state object
contain a collection of several applet state objects. Each applet state
object represents the state of a card applet on the card (see Figure
14.3). If, for example, we have a card applet that simulates a file system, the state would consist of the currently selected directory and information about the access conditions.
Figure 14.3:
Card Applets
with their Associated Proxies
and States
Ch::lnlnAI~.. Card
State
Card Applet 2
Card Applet 3
244
Base class
AppletProxy
Controlling the
Selection State
Reflecting applet
state changes in
the associated
proxies
14.4.2
responsibility that we give this base class is to actually send and receive the APDUs. Here we also make sure that the correct receiving
BasicAppletCardService
245
applet is selected before the APDU is sent, and that the PIN is
(re-)entered if necessary.
Figure 14.4:
The Off-card
Classes Driving
Our Sample
Card Applet
C..dServlce
+ setC8rdC. . . . . O
# allocateClWdC. . . . .O
# rel_ee.dCl ... O
BaslcAppletC..clServlce
et
# getCardState()
# Inlaallze()
AppIetlD
(from appIet)
- selectApplet()
# sendConnandAPDU()
+ sendConnandAPDU()
# sendVeritiedAPDU()
ca-d
+ ca-clnserted()
+ ca-dRemoved()
BuslnessCwd()
+ getAd*essO
# getBuslnessC..dState()
+ get o
#getReld()
# Initialize()
buslnessCardPrmcy
+ ca-dlnserted()
+ ca-dRernoved()
+ dose()
+ getBUSlnesslnfa()
+ setBuslnesslnfa()
# performCHVO
# setRelcI()
+ set..... ()
BusinessCard
DUs and card communication, we do not expect that other application programmers use it directly. Rather we create an abstraction that
246
14.4.2.1
Class BusinessCardProxy
Class BusinessCardProxy is responsible for acting as a proxy to
the card applet BizCardApplet.
First we define several constants for BusinessCardProxy objects, 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.
public class BusinessCardProxy extends AppletProxy
II Return codes.
protected final static int OK = Ox9000;
protected final static int CHV FAILED
Ox6982;
II Field identifiers.
protected final static int NAME = 0;
protected final static int TITLE = 1;
protected final static int ADDRESS = 4;
247
setAddress(. .. )
setField(. . .)
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.
248
II
ResponseAPDU response
sendCommandAPDU(cc,
BUSINESS CARD_AID, setFieldAPDU);
switch (response.sw() & OxFFFF) {
case OK :
return;
case INDEX OUT OF RANGE
throw new CardServicelnvalidParameterException(
"Index out of range");
default :
throw new CardServiceUnexpectedResponseException(
"RC=" + response.sw());
finally
releaseCardChannel() ;
GetBusinessCardState
(CardChannel)
--
249
initia/ize(. .. )
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 inessCardState object. We set it to reflect that the PIN verification
(or cardholder verification, CRY) has not been successfully done yet.
250
Next, we put this card applet state object into the card state. Finally,
we release the card channel.
II Get the business card applet state.
II If not already there, create it.
BusinessCardState state = (BusinessCardState)
cardState.get(BUSINESS_CARD_AID) ;
i f (state == null) (
state = new BusinessCardState();
state.setCHVPerformed(false) ;
cardState.put(BUSINESS_CARD_AID, state);
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 http://www.opencard.orglSCJavaBooki.
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 distribution 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.
14.4.2.2
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 unnecessary selection commands is avoided.
All instances of the class BasicAppletCardService associated
with the same physical card share a common object of type CardState to ensure a consistent view including keeping the information
on the active applet. BasicAppletCardService uses an application identifier for this CardState that can not collide with an application identifier of a real applet and applet proxy:
251
Using the proxy state mechanism also for the state of the Basic
AppletCardService we access the same state object for the same
sendCommandAPDU(.. .)
selectApplet(... }
active. It does not create and send the APDU directly though. Rather
it delegates this to the method selectApplet (... ) of an object of
type ISOAppletSelector (instance variable selector-->:
/ / in selectApplet (CardChannel ... , AppletID appletID) ...
if ((state.getSelectedAppletID() == null)
I I (!state.getSelectedAppletID() .equals(appletID)))
AppletInfo info =
selector_.selectApplet(channel, appletID);
252
sendComman-
14.4.2.3
Class BusinessCardState
For our business card applet we are interested only in one state information. We need to know whether a valid PIN has been entered
after this applet became active. This information is stored in the boolean 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:
public class BusinessCardState extends AppletState
protected boolean chvPerformed_ = false;
public void appletDeselected()
chvPerformed_ = false;
public boolean isCHVPerformed()
return chvPerformed_;
public void setCHVPerformed(boolean chvPerformed)
chvPerformed
chvPerformed;
253
Now we have seen the applet proxy for our card applet, its base
classes, and the state object associated with it.
In our example we do not intend to let an application program use
BusinessCardProxy objects directly. Instead, we provide as application programming interface a class BusinessCard.
14.4.2.4
Class BusinessCard
Class BusinessCard is responsible for storing business card information 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 contained in the complete source code for the business card sample program, which we provide as package samples. business in the
sample code archive on http://www.opencard.orglSCJavaBooki.
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.
254
In this chapter, we give an overview on card management and application management systems. We also describe how OCF can be used
to support these systems on client devices. In Section 15.1, we give
an overview on card, application, and key management systems and
the life cycles of cards and applications. Card management systems,
as well as application management systems need to perform cardrelated actions on various client platforms. In Section 15.2, we show
how the OpenCard Framework can be used to support application
download to smart cards via the Internet and for application personalization via the Internet.
15.1
Introduction
The tasks related to the management of smart cards and card applications 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 allow for management of multi-application smart cards in a multienterprise environment. Application management refers to the functions 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 management systems: Card Management Systems (CMS), Application
Management Systems (AMS), and Key Management Systems
(KMS). The different management systems within a smart card system 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 management system and each application provider owns his own application
U. Hansmann et al., Smart Card Application Development Using Java
Springer-Verlag Berlin Heidelberg 2002
15. 1 Introduction
--
255
15.1.1
Card Management Systems
Card management systems are used to manage entire smart cards.
They allow to issue cards, to handle damage, theft or loss of cards, to
keep track of the states of individual cards and of the applications on
these cards, and finally to withdraw and replace cards. The life cycle
of smart cards spans a number of states that may be very different
depending on the approaches chosen by the card issuer and to some
extent on design decisions made by the card operating system provider. In this section, we describe a very generic life cycle model
with a rather big number of card states. In concrete smart card systems, some of these states may be missing.
256
Enabled - the data that is common for all cards of a lot has
been written to the persistent memory. Personalization moves
the chip to the next state.
Active - this is the state where the card is actually used by the
cardholder. Expiry, loss, theft, damage or blocking moves the
card to one of the next states.
Withdrawn - this state represents the end of the card life cycle,
where the card is not usable anymore.
15.1.2
Loaded - the application has been loaded on the card, but cannot yet be used. Installation moves the application to the next
state.
Personalized - the application has been personalized with cardindividual data. Issuing the application to the cardholder moves
it to the next state.
Inactive - usage of the application has been dispensed. Withdrawal moves the card to the next state.
Withdrawn - this state represents the end of the card life cycle,
where the card is not usable anymore.
15. 1 Introduction
--
257
15.1.3
15.2
258
15.2.1
Example
An example where post-issuance application download and personalization are required is the following scenario: A customer of a bank
has a smart card that hosts a purse application and a home banking
application. While doing home banking, he realizes that now his bank
also offers online brokerage with smart cards and he wants the brokerage application on his card. He clicks on the link to the application
management system for the brokerage application and the application
download applet is displayed in the browser. First, it creates a new
application directory with appropriate files for the brokerage application on the card. Then, the application download applet lets the card
compute an asymmetric key pair and retrieves the public key from
the card. It sends the public key together with parameters entered by
the cardholder to the brokerage key management system for certification, receives the certificate, and stores it on the card. From now
on, the customer can use his card to digitally sign orders instead of
using transaction numbers.
15.2.2
Security
Each of the actions performed during application download needs to
be appropriately secured, e.g. by usage of security domains associated with application providers. A security domain contains cryptographic keys that are owned by the application provider. Examples
for security domains are GlobalPlatform security domains on Java
Cards or application directories that contain key files on file system
cards. Installation of a security domain on a card usually requires a
key owned by the card issuer. Once a security domain for an application provider has been installed, only the keys of the application provider are needed for further actions: Application code and data can be
downloaded using the application provider's keys that have been installed on the card with the security domain. Figure 15.1 shows an
example of a protocol that may be conducted between a client that
wants to download an application to the card, the card issuer's card
management system, and the application provider's application management system on a high level.
259
Figure 15. 1:
Application
Download on a
GlobalPlatform
Java Card
Client
AMS
CMS
--
....
--
Sucess Notification
Request Application
--
-.. ..
-
Get Application
-...
Sucess Notification
--
Sucess Notification
--
--
---
260
15.2.3
Architecture and Technology
One approach to implement card and application management functions is a three-tier architecture as shown in Figure 15.2.
Figure 15.2:
Infrastructure for
Decentralized Card
Administration and
Personalization
Tier-3
Tier-2
Tier-1
Tier-l consists of these devices where card or application management tasks shall be performed, like personal computers, network
computers, ATMs, set-top boxes or any other smart card enabled
device connected to a network. Tier-2 consists of application servers
hosting card and application management software. Tier-3 consists
of database systems that are used to trigger and track actions performed on Tier-2 and Tier-l and to provide the required data.
Standard Internet technology can be used to implement a three-tier
system like this. At Tier-I, a Web Browser can be used for running
the required management appiets. The management applets can use
the OpenCard Framework to access smart cards. At Tier-2, a Web
Server with an integrated application server can be used to
provide the required HTML pages as well as for running servlets that
provide the connection to Tier-3. At Tier-3, database servers can be
used to manage data required for card and application management.
--
261
Figure 15.3:
A Possible
Software Setup
for Web Based
Card and
Application
Management
Enterprise
Java Beans
WebServer
javax.comm
15.2.4
Application download to smart cards always depends on the particular card operating system of the card. In this chapter, we discuss postissuance download of applications to smart cards with two different
262
kinds of card operating systems: File system oriented smart cards and
Java Cards with GlobalPlatform (see Chapter 2).
15.2.4.1
1. Creation of a new application directory (ADF) under the applications unique application identifier (AID).
2. Registration of the new application directory in the directory file.
3. Creation of data files, key files, and password files in the new application directory.
4. Writing initial data to the data files, writing initial keys to the key
files, and writing initial passwords to the password files.
For each of the above steps, certain access conditions need to be
fulfilled. Usually, creating the application directory, adding an entry
to the directory file, creating the key file inside of the application directory, and writing initial keys to that file require keys owned by the
card issuer. Once these steps have been performed, more files inside
of the application directory may be created and be written to using
application keys.
Regarding application download, one problem with file system
cards is that most older card operating systems have not been designed for download of applications via networks. Often, the secure
messaging mechanisms implemented on these cards require exchange
of a random number for each protected or encrypted command that
has to be sent to the card. If this is the case, it is not possible to prepare a sequence of commands on the application management system
server, pre-calculate the appropriate MACs on the server and send the
whole sequence to the client. Instead, each command to be sent to the
card with a MAC requires communication with the server.
263
15.2.4.2
15.2.5
Post-Issuance Application Personalization
After an application has been installed on a card, it needs to be personalized to add card individual data to the application files. This
may be immediately after application installation in the case of postissuance application download or long after the application has been
installed in the case of an application that had been pre-installed at
card issuance and that was inactive. For personalization, data from
the card and additional data to be entered by the cardholder requesting the application as well as data from databases of card issuer or
application provider may be required. Once the required data has
been gathered, it needs to be sent to the application provider who
needs it for generating the personalization data set. The rest of the
procedure depends on the type of smart card that is used.
For smart cards that allow usage of one random challenge for a
sequence of commands - like Java Cards for example - the application management system can generate personalization scripts, which
are sequences of personalization commands. It embeds the required
data in personalization Command APDUs, signs, and encrypts parts
of these APDUs using keys that match the keys of the application security domain on the card. The personalization script can then be sent
264
to the client that sends all Command APDUs in the script to the smart
card one after the other. Figure 15.4 shows this scenario.
..
Logon
Figure 15.4:
The Simplest
Case of
Post-Issuance
Application
Personalization.
Check
Response Credential
Get Input,
Card Type
and Challenge
Generate
APDU 1-n,
Pers. Script Build Script
~
Send APDU
1-n to Card
Confirmation
Update
Database
Send APDU 1
to Card, get
Challenge
Challenge
Send APDU 2
to Card, get
Challenge
Generate
APDU APDU 1
Generate
APDU APDU2
Figure 15.5:
Post-Issuance
Personalization
for a Card that
Requires
Challengeresponse per
Command
...
Challenge
Send APDU n
Confirmation
to Card.
..
Generate
APDU APDU n
Update
Database
265
16.1
Device Profiles
There are a big variety of pervasive computing devices on the market
with very different capabilities, e.g. mobile phones, screen phones,
personal digital assistants, intelligent card terminals, payment terminals, wearable computers, and intelligent car radios. It is not reasonable to address the full range of devices with a single framework because they are just too different. We see three classes of devices to
which we will refer as high-end, medium, and low-end pervasive
computing devices. The most relevant criteria for our classification
are the installed memory and the Java language subsets available on
these devices. Table 16.1 gives a brief characterization of the three
profiles.
On big terminals, the full OpenCard Framework can be used. It
was originally developed for use on Personal Computers, Network
Computers, and Workstations, but it is compact enough to fit in highend devices like screen phones and kiosks. The OpenCard FrameU. Hansmann et al., Smart Card Application Development Using Java
Springer-Verlag Berlin Heidelberg 2002
267
work provides support for multiple card readers that may have multiple slots as well as many convenience functions that in some cases
can save work for application programmers.
Table 16.1:
Device
Categories
Big Devices
Medium
Devices
Small Devices
RAM
> 1024KB
256-1024 KB
ROM
> 1024KB
256-1024 KB
< 256 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,
Kiosks, Wearable Computers,
Telematics
units
Intelligent Card
Terminals,
Set Top Boxes
Small Payment
Terminals,
Mobile Phones
268
16.2
OCF for Embedded Devices
As mentioned in the previous section, the full version of the OpenCard Framework is not adequate for medium and low-end terminals.
It has been designed to run on Personal Computers, Network Computers, Workstations etc. and thus has features which are not needed
in a terminal environment: automatic configuration from property
files, multiple card terminal support, dynamic attachment and detachment of card terminals for example.
The concept of the OpenCard Framework for embedded devices is
to provide subsets of the OpenCard Framework with functionality reduced to the essential features required inside of terminals. One subset is intended for low-end terminals and only contains a minimal
subset of the original OpenCard Framework classes. The other subset
offers more features but still is much smaller than the full Open Card
Framework. The Figure 16.1 shows which OpenCard Framework
packages these subsets span: The subset for low-end devices only
contains classes at the terminal layer, while the subset for medium
devices additionally contains classes on the event and service layer.
As the subset for small devices is a subset of that for medium devices, all applications for the low-end subset also run on the medium
subset.
Medium
Subset
Figure 16. 1:
The Subsets of
the OpenCard
Framework for
Embedded
Devices
Small
Subset
269
16.2.1
Differences between OCF and OCF for Embedded
Devices
The generic architecture of the OpenCard Framework has been
adapted for terminals, where only one card reader with one or more
slots or transceivers exists. Another important change to the architecture was the introduction of strict layering. All dependencies from
the terminal package to the event package have been removed. As a
result, the terminal package can be used alone if desired.
The following picture gives a rough overview on the architecture
of the OpenCard Framework for Embedded Devices. Arrows indicate
dependencies of classes on other classes. The classes with thick borders and the mark (S) are singletons i.e. there is exactly one instance
of these classes [GAM95]. The boxes with dotted borders depict interfaces.
Figure 16.2:
Architecture of
OCFfor
Embedded
Devices
I opencard.core.event
...........................
f .......................................
opencard.core.service
CTListener
... - ....... -
opencard.core.terminal
Card Reader
Unlike in the full OpenCard Framework, the class CardTerminal in the OpenCard Framework for Embedded Devices is a singleton that represents the single card reader of the embedded device. As
there is exactly one CardTerminal instance, which can always be
obtained by calling the appropriate static method the CardTerminalRegistry does not exist in OCF for Embedded Devices. The
card reader of the device in which OCF for Embedded Devices runs
may have one or more slots. The number of slots may be queried and
270
Card services that are relying on the secure cardholder verification feature of the full OpenCard Framework must be slightly
changed. OCF for Embedded Devices doesn't provide this feature since it runs inside of terminals.
Card service factories using the deprecated customization feature for CardChannels must be changed so that they use the
state objects associated with CardChannels instead.
--
271
16.2.2
Footprint Statistics
In this section we provide footprint statistics on the prototype of OCF
for Embedded Devices 1.2.2 developed at IDM. We list the footprint
of each class and package as well as the total footprint of the medium
subset and the low-end subset.
To get an idea what footprint a pure Java driver for the built-in
card reader of a card terminal might add, we implemented a pure Java
driver prototype for the Gemplus GCR 410, which turned out to require 7 K.
The footprint of card services will be very different, depending on
functionality. It may be between 1 and 5 K for simple card services
with small functionality. Card services with a rich functionality may
have a footprint of 10 to 20 K. The size of the very simple pass
through card service that only routs given APDUs to the card is about
1 KB for example.
The numbers below were obtained by using JDK 1.2's javac compiler with the option -g:none, which generates class files without debug information.
Table 16.2:
Footprint
Statistics of OCF
for Embedded
Devices
272
25KB
7KB
32KB
l6KB
6KB
Part IV
Appendices
A The Card
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 directory 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 verifying digital signatures. A special feature of this card is that it can even
generate key pairs on the card.
275
A.2
The File Structure on the Card
The file structure on the card that comes with this book is very simple
to be easily understandable. It contains three application directories:
The first directory belongs to the loyalty application example in
Chapter 9. The second directory belongs to the Internet Broker Demo
that is available on the OpenCard web site and is described in Chapter 10.
The third directory belongs to the Business Card Demo that is also
available on the web site http://www.alphaworks.ibm.comlas part of
the OCEAN package. Figure A.t shows an overview of the file
structure.
Figure A. 1:
The File Structure
of the Card that
Comes with this
Book
MF
EF CHV1
EF CHV2
EF_KEY
EF_AUT
EF DIR
--t
H EF
H
l-I
L.{
OF LOYALTY
ADDRESS
EF_BONUS
EF NUMBER
OF BUSINESS CARD
H EF
-I
-I
MY INFO
I
I
-I
-I
-I
-1
EF _PUBLIC_DATA
I
I
I
EF PRIVATE DATA
EF SERIAL NUMBER
EF ORDER LOG
EF FOREIGN_INFO
EF POINTER
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 single 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).
276
A The Card
Always
The access condition Always means that access is possible by
simply sending the appropriate command APDU.
Never
The access condition Never means that access is possible under
no circumstances.
--
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 programs 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
File EF CHVI (OxOOOO)
File Type:
Transparent
Size:
23 bytes
AC Update:
Cardholder Verification 2
AC Read:
Never
Data ---------------------------------------------
OxOl,
OxOO,
OxOO,
"password" ,
Ox03,
Ox03,
"unblckpw" ,
OxOl,
OxOl
// Activation
// Way to present
1/ Key Number in relevant EF KEY
1/ Password
// Initial attempt counter
// Remaining Attempts
// Unblock Password
// Initial Attempt Counter
// Remaining Attempts
278
A The Card
File Type:
Size:
AC Update:
AC Read:
Variable (2 records)
32 bytes
Never
Never
File Type:
Variable
Size:
16 bytes
AC Update:
Enciphered with Key 0
AC Read:
Never
Data Record 1 -------------------------------------OxOO,
II Key Number
Ox06,
II Algorithm ID (DES)
Ox03,
II Attempt counter
OxOO,
II Key Version
OxFFFF,
II Key usage counter RFU
Ox0123456789ABCDEF
II Key with odd parity
File EF DIR (Ox2FOO)
File Type:
Size:
AC Update:
AC Read:
Data ---------------------------------------------
279
Ox61,
38,
Ox4F,
9,
OxD276000022,
Ox00000060,
Ox50,
16,
"PKCS#ll token
Ox52,
7,
OxOO, OxA4,
OxOO, OxOO, Ox02,
OxCllO,
Ox61,
33,
Ox4F,
9,
OxD276000022,
OxOOOOOOOl,
Ox50,
11,
"SCT LOYALTY",
Ox52,
7,
OxOO, OxA4,
OxOO, OxOO, Ox02,
OxlOOO,
OxOOOOOOOOOO,
Ox6l,
33,
Ox4F,
9,
OxD276000022,
Ox00000002,
280
A The Card
",
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
II
Application Template 1
Length of contained data
Application identifier tag
Application ID length
Application ID: RID
assigned to IBM
Application ID PIX PKCS11
Application label tag
Application label length
Application label
No Application Pref. Name
No App. Priority Index
Command to Perform
Command to Perform Length
MFC Select
PI, P2, P3
File id of Application DF
Application Template 2
Length of contained data
Application identifier tag
App. Identifier length
Application identifier: RID
Application identifier: PIX
Application label tag
Application label length
Application label
No Application Preferred
Name
No Application Priority
Index
Command to Perform
Command to Perform length
MFC Select
I I P1, P2, P3
II File id of Application DF
II No Directory Discretionary
II Template
II Padding to multiple of 40
II Application Template 3
II Length of contained data
II Application identifier tag
1/ Application 10 length
II Application identifier: RID
II Application identifier: PIX
Ox50,
13,
"BUSINESS CARD",
Ox52,
7,
OxOO, OxA4,
OxOO, OxOO, Ox02,
Ox08l5,
OxOOOOOO
II
II
II
II
II
II
II
II
AC Read:
Cardholder Verification I
Data --------------------------------------------"IBM PvC Smart Card Solutions",
OxOD, OxOA,
"[email protected]"
Directory OF_LOYALTY (OxlOOO)
AC Create:
Protected with Key 0
AC Delete:
Protected with Key 0
File EF_ADDRESS (Oxl002)
File Type:
Transparent
Size:
66 bytes
AC Read:
Cardholder Verification 2
AC Update:
Protected with Key 0
Data ---------------------------------------"Old Orchard Road",
OxOD, OxOA,
"Armonk, New York", OxOO
File EF BONUS (OxlOO3)
File Type:
Transparent
File Size:
4 bytes
AC Read:
Cardholder Verification I
AC Update:
Cardholder Verification 1
Data ---------------------------------------OxOOOOOOOO
File EF NUMBER (Oxl004)
281
File Type:
Transparent
Size:
8 bytes
AC Read:
Always
AC Update:
Never
Data ---------------------------------------Ox40E20100
Directory DF_PKCSll (OxCll0)
AC Create:
Cardholder verification 1
AC Delete:
Cardholder Verification 1
File Type:
Transparent
Size:
AC Update:
16 bytes
Never
AC Read:
Always
Data ---------------------------------------"0123456789ABCDEF"
File EF_ORDER_LOG (OxC002)
File Type:
Linear Fixed, Record Size 20
Size:
AC Update:
5 * 20 bytes
Cardholder Verification 1
AC Read:
Cardholder Verification 1
Data ---------------------------------------"11111111111111111111",
"22222222222222222222",
"33333333333333333333",
"44444444444444444444",
"55555555555555555555"
File EF_PUBLIC_DATA (OxCl00)
File Type:
Transparent
Size:
1000 bytes
AC Update:
Always
AC Read:
Always
File EF_PRlVATE_DATA (OxC200)
File Type:
Transparent
Size:
AC Update:
1000 bytes
Cardholder Verification 1
AC Read:
Cardholder Verification 1
282
A The Card
Always
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 http://www.opencard.org/. To access
this book's card, you need to make the following entry in the opencard. properties file:
OpenCard.services =
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.
--
283
Gemplus
http://www.gemplus.coml
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
http://www.gemplus.comldevelopersl
This web site contains the latest information for developers, like a forum, latest trends, and current drivers. It also provides access to
OpenCard CardTerminals and CardServices for hardware from
Gemplus.
285
GlobalPlaHorm
http://www.globalplatform.org
Visa and other companies from the smart card and finance industry
founded GlobalPlatform. This organization continues the development of the Open Platform technology, originally started by Visa.
IBM
http://www.ibm.com/pvc/
IDM Pervasive Computing provides a wide range of technology and
solutions for pervasive computing and smart cards. IDM is committed 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
http://www.mondex.com/
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.
286
Multos
http://www.multos.com/
On this web site, the Maosco consortium provides infonnation about
its Multos smart card operating system, the companies behind Maosco, and how you can obtain implementation and application licenses. Developers find technical manuals,. technical bulletins, as
well as training modules.
OpenCard
http://www.opencard.orgl
OpenCard Framework provides a Java application-programming interface to smart cards. It is supported by the OpenCard Consortium,
which was founded by members from the IT industry, smart card industry, 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 interested parties.
PKI Survey
http://home.xcert.com/-marcnarc/PKI/
On this web page you can find excellent links to infonnation on public key infrastructure (PKI) and cryptography.
PC/SC
http://www.pcscworkgroup.com/
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.
287
Proton World
http://www.protonworld.com/
ERG, American Express, Banksys, and Visa founded Proton World
in 1998. Proton World is now owned by ERG and provides the Proton electronic purse scheme.
On this web site, you can find a description of Proton, a list of current projects, and recent press releases.
Schlumberger
http://www.slh.com/smartcards/
Schlumberger is a leading smart card provider.
On this web site, you can find information about Schlumberger
products and solutions.
Visa
http://corporate.visa.com/mclfacts
Visa International is the leading credit card organization with over
21.000 member financial institutions. Visa has founded the OpenCard 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.
288
C Bibliography
C Bibliography
289
R.c. Merkle, Secure Communication Over Insecure Channels, Communications of the ACM, v. 21, nA, 1978, pp. 294-299
290
C Bibliography
[MIL86] V.S.Miller, Use of Elliptic Curves in Cryptography, Advances in Cryptology - Crypto '85 Proceedings, Springer-Verlag, 1986, pp. 417--426
[MNDX02] Mondex Electronic Cash, 2002, http://www.mondex.coml
[MUL02] Multos, http://www.multos.coml
[NETOl] Netscape Object Signing, Establishing Trust for downloaded software,
http://developer.netscape.comldocs/manualslsignedobj/trustlowp.htm
[NET97] Preventing Subversion of Public Helper Methods,
http://developer.netscape.comldocs/manuals/signedobj/capabilitiesl
[NIS94] National Institute of Standards and Technology, NIST FIPS PUB 186,
Digital Signature Standard, U.S. Department of Commerce, May 1994
[OCC99] OpenCard Consortium, 1999, http://www.opencard.orgl
[OCF99] OpenCard Framework Programmer's Guide, 1999,
http://www.opencard.orgl
[OCFEOl] OpenCard Framework for Embedded Devices Specification 1.2.2,
2000,
http://www.opencard.orgidownload/docs/l.2T/ocfembeddedspec.zip
[PCSC02] PC/SC Workgroup, http://www.pcscworkgroup.coml
[pGP02] The International PGP Homepage, 2002, http://www.pgpi.coml
[PR002] Proton World, 2002, http://www.protonworld.coml
[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
[RMI99] Java TMRemote Method Invocation, http://java.sun.comlproductsljdklrmi
[SCH96] Bruce Schneier, Applied Cryptography, Wiley, 1996
[SER99] James Duncan Davidson, Danny Coward, Java Servlet Specification
v2.2, Sun Microsystems, 1999
C Bibliography
--
291
292
. C Bibliography
D Glossary
D Glossary
293
Digital Signature - encrypted digital fingerprints of data, ensuring 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).
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".
Java Card - a smart card that has the capability of running Java
programs using a restricted command set and library on-card.
Java Card Runtime Environment (JCRE) - The execution environment for Java Card applets.
294
0 Glossary
Response APDU - An APDU sent back by a smart card after receiving a command APDU.
ROM - Read Only Memory
RSA - Most important asymmetric cryptographic algorithm. The
acronym stands for the inventors Rivest, Sharnir and Adlemen.
Symmetric Cryptographic Algorithm - cryptographic algorithm, 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 device.
o Glossary
295
Elndex
3
3-tier architecture 215
A
AAM 33
Abstract Syntax Notation (ASN)
27
acceptance device 69
access condition 30, 244
access conditions 277
access control 17
access modes 275
application selection 79
ApplicationManagementCardService 97
approval of cards and terminals
78
Architecture Overview 93-100
ARPAnet 35
asset protection 90
association 92
asymmetrical key 44, 46
ATR 26,76,77,79,95, 120
attacks 21
authentication 15, 36, 43-46
B
Bank of America 42
beginMutexO 150
benefits 13, 15-16
biometric identification 72-73
BizCardApplet 247
BizCardRecord 240
Booch 92
browser security 188
building access 15
bulk encryption services 80
BusinessCard 247,254
BusinessCardProxy 245,
247-51
BusinessCardState 253-54
byte array 236
byte code converter 234
c
cap file 234
card acceptance device (CAD) 69
E Index
297
CardExecutiveCardService 245,251-53
CardExecutiveCardState
250
CardFile 97,170,199,201
CardFileInfo 169
CardTechiSecurTech 87
CardTerminal 95,96, 115,
118,132,135,196
CardTerminalEvent 97,
117, 150,201
CardTerminalException
122
CardTerminalFactory 96,
115,118,143
CardTerminalIOBlender
125
117,149,196,204
card-to-card payment 220
card-to-card payment schemes
218
CardType 160
Carte Bancaire 14
cash handling 15
CBC 54
CEPS 38,43
certificate 46
certification 71, 72
challenge-response 44
challenge-response protocol 59
Chipknip 38
CHVControl 124
CHVDialog 155, 159, 162
CHVEncoder 125
chvPerformed 253
Cipher 235
Cipher Block Chaining (CBC) 53
CLA 25
class byte (CLA) 25
class libraries 234
Clearing System 42
clock signal 19
close () 201
cold reset 19
Command APDU 24
CommandAPDU 121
203,205--6
CardServiceException
165
CardServiceFactory 96,
112,158,159-61,196
CardServiceImplementationException 165
CardServiceInabilityException 165
CardServiceInterface
166
CardServiceInvalidCredentialException 166
CardServiceInvalidParameterException 166
CardServiceOperationFailedException 165
CardServiceUsageException 166
CardTerminalIOControl
CardNotPresentException 122
cardRemovedO 117,141,207
CardRequest 151,199
CardFileOutputStream
210
CardFilePath 171,182
CardHolderVerification
GUI 162
CardID 95,119,149
CardIDFilter 151
cardInserted () 117,141,
298
CardServiceRegistry 96,
Elndex
124
CardTerminalRegistry 96,
CommunicationErrorException 122
compiler 234
Concentration Point 42
configuration 148
configuring 195
contact card 17, 69
contact unit 69
contactless card 16, 17
CORBA 242
CPU 17
createEventsForPresent
Cards () 204
Credential 176, 183
CredentialBag 184
CredentialStore 184
credit card 13, 15
Crypto Service Provider 80
crypto token 47
cryptographic algorithms 51
cryptographic coprocessor 18,70
cryptographic protocols 59
cryptography 51
CT/ST 87
CTListener 97,150,203,204,
247
Cyclic Record 29
D
Danmont 38
data integrity 215
DataOutputStream 210
debugging 105
decrypt 14, 24
decryption 45
dedicated file (DF) 28
DefaultCHVDialog 162
denotes inheritance 92
DES 52
DES modes 53
deselect () 236
DESSecureCredential 185
destroy () 232
development cost reduction 90
development kit 24
E
e-business 35-49
ECB 53
e-commerce 36
EEPROM 17
EF 28
electrical characteristics 78
electromagnetic radiation 75
electromagnetic wave 17
Electronic Code Book (ECB) 53
electronic commerce (ecommerce) 36
electronic contract 35
electronic purse 13, 15, 35,43,
37-43, 71
electronic signal 76, 77
electronic ticket 35,48
elementary file (EF) 28
elliptic curve algorithms 58
e-mail 46
embossed printing 14
EMV 43,77-79,94
encrypt 14, 24
encryption 35, 36
endMutex () 150
error detection code (EDC) 128
Euro 38
expiration date 46
export restrictions 177
external authentication 30, 59
E Index
--
299
F
fabrication 21
file identifier 28
file structure 276
file system 24
file system smart cards 28-30
FileAccessCardService
169,199,203
FileSystemCardService
95, 169
Fixed Record 29
fraud 14,48
G
garbage collection 31
GCR410 137
GCR410CardTerminal 136
GCR410TIProtocol 133
GeldKarte 15,38,39-40,219
getAddress () 247
getBusinessCardState(C
ardChannel) 249
getCardService (... ) 201,
206
getField(APDU) 241
get Length () 209
getpath () 202
GlobalPlatform 82-84
ground connection 19
GSM 15,26
H
handshake protocol 67
hardware 13,16-22
hardware security 21
hashing 80
HexString 102
history 87
home-banking 15
hybrid algorithms 59
hybrid smart card 17
IBM 87
IBM JCOPlO 254
IBM MFC family 275
300
Elndex
iButton 20
ICC 79
ICC Resource Manager 80
ICC Service Provider 80
ID-OOO 20
ID-1 20
identification card 14
IFD Handler 80
imprint 14
industry initiative 75-83
init () 230
initialization 22, 93
initialize (... ) 250
INS 25
install (... ) 235,241
installing 195
instruction byte (INS) 25, 237
integrated circuit 14
Integrated Circuit Card (ICC) 79
interface device (IFD) 69,79
Inter-industry commands for
interchange 76
inter-industry security
architecture 77
internal authentication 60
International Organization for
Standardization (ISO) 75
Internet 35
internet brokerage 215
internet customer terminal 227
Internet Stockbroker demo 214
interoperability 78
Interoperability Specification for
ICCs and Personal Computer
Systems 1.0 (PC/SC) 79
InvalidCardChannelException 166
InvalidSlotChannelException 122
ISO 7816 75,78
ISO 7816-1 75
ISO 7816-10 77
ISO 7816-2 19,76
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
ISO 7816-6 77
ISO 7816-7 77
ISO 7816-8 77
ISO 8824 27
ISO 8825 27
ISO file system CardService
169
ISO standards 77
IS07816 (interface) 234
ISOCommandAPDU 126,127
ISOException 239
issuing 93
J
Jacobson 92
Java Card 24,31-32,233-54
Java Card 2.1 236
Java Card applet 31
Java Card emulator 234
Java Card Forum 31
Java Card Framework 234-35
Java Card Runtime Environment
31,32
Java Card security framework
235
Java Card simulation environment
234
Java Card specification 31
Java Communications API 131
JavaNativeInterface 131
Java sandbox 189
K
Key 178
key generation 80
key handling 172
key management 80
KeyEncryption 235
KeyFile 177
KeyGenerationCardService 172
KeylmportCardService
172
KeyRef 177
L
Lc 25
Le 25
length byte 25
life cycle 234
lifetime of the applet 235
Linux 105
loadProperties() 196
login 44-45
loyalty 48
loyalty scheme 15
M
MAC 30,54
magnetic stripe 14, 15,20,72
makeTransient 235
management board 89
manufacturing process 22
Maosco 32
mask 24
mass-transit 15, 17
master file (MF) 28
mechanical characteristics 78
mechanical contacts 19
MEL 32
memory 17
memory card 16-17
merchant card 219
message authentication code
(MAC) 30,54,61
method 92
MF 28
MFC 30
MFCCredentialStore 185
MFCSignatureService 182
microcomputer 13
micropayment 37
microprocessor 17
microprocessor card 16-17
MicrosoftSystemAccess
108, 190
mobile phone 20
module 21
module insertion 22
E Index
--
301
Mondex 38, 40
Multi-Function Card (MFC) 30
multiplicity 92
Multos 24,32-33,40
Multos Executable Language
(MEL) 32
N
native code 195
NC 87
NetscapeSystemAccess
108, 190
Network Computer (NC) 87
network login 44-45
non-repudiation 36,216
o
OCF advantages 90-91
OCF architecture 91-99
OCF configuration 196-98
OCF for Embedded Devices
267-72
OCF objectives 89-90
OCFllCardServiceFactory 167
off-card 23, 233
on-card 23, 233
on-line transaction 37
OpenCard Consortium 71, 87,
195
opencard.core 101
opencard.core.service
146
opencard.core.util 102
opencard.opt.javacard
246
opencard.opt.security
178
opencard.opt.service
166
opencard.opt.signature
172
opencard.opt.util 109
opencard. properties 112,
197
302
Elndex
OpenCard.trace 107
OpenCard.trace.eventsOnly 107
OpenCardConfigurationProvider 104, 196
OpenCardConstants 101
OpenCardException 101
OpenCardPropertyFileLoader 110, 149, 197
OpenCardPropertyLoadingException 104
OpenCardRuntimeException 101
Optional CardService exceptions
167
optional components 126
OwnerPIN 238
p
PI 25
P2 25
parameter byte 25
passivation layers 21
pass-phrase 44
PassThruCardService 111
password 44, 123, 155
payment 15,36,71,220
payment acceptance 225
payment protocol 222, 223
payment server 224, 226
payment system 78
payment terminal 82,219
payment via Internet 221-26
payments via the Internet 218
PC/SC 70, 79-82, 131
PCMCIA 69
performCHV (... ) 238,248
Personal Identification Number
(PIN) 70
personalization 22, 83, 93
phone card 13
physical characteristics 79
physical examination 21
physical security 21
PIN 70, 123, 155
PIN-pad 70
PKACredential 187
Q
Quick 38
R
RAM 18
Ravensburg 39
reader 23, 26, 195
reference implementation 93
register () 235
registered application provider
identifier (RID) 76
registry 95
relationship 92
s
SAM 37,175
sample application 195
secret 14
secret keys 15
secure 14
secure access 35,43--46
secure authentication 35
secure channel 83
secure messaging 27,61, 175
secure session 45
secure storage 15
secure token 15,216
SecureService 184, 187
security 15, 83, 175
Security Access Module (SAM)
37
security issue 35
security requirements 16
SecurityDomain 184
SecurityManager class
31
SELECT APDU 236
select () 236
selectApplet (... ) 252
sendBytesLong (... ) 241
server login 44--45
service layer 145
Service Payment Terminal 42
service () 231
servlet 218,229,230
session key 45, 66
setAddress(String) 247
setCHVDialog (... ) 207
setField (... ) 239,247
E Index
--
303
setOutgoingAndSend (... )
239
setOutgoingLength
(short) 241
setSystemAccess (... ) 109
SHA-l 58
shutdown () 149, 199
signature 18,38
Signature 179
signature verification 172
SignatureCard 203
SignatureCardService
172,182
signatureService 203
SignCredential 187
singleton 152
slot 70, 96, 119
SlotChannel 98, 119, 154
Smart Card for Windows 24,
33-34
smart card key classes 181
Smart Card Toolkit for Visual
Basic 34
Smart Card 95,148,199,203,
247
SSL 45
standard CardService
interfaces 168
standards 75-83
start () 103, 148,204
static electricity 75
status word 26
String 236
structured card query language
(SCQL) 77
supply voltage 19
SWI 26
SW2 26
Swindon 40
symbolic name 28
symmetric cryptographic
algorithms 52
symmetrical key 45
SymmetricCredential 187
synchronize 146
syslogO 105
system properties 196
system property 107, 148
system resources 189
SystemAccess 108, 190
304
Elndex
T
T=O 24,26-27,76
T=1 24, 26-27
T=14 76
TIBlock 128
TlException 129
TIProtocol 128, 133
Tag 114
Tag-Length-Value (TLV) 27,
113
tamper-resistant 14, 15
technical committee 89
terminal 23,71-72,69-73
terminal vendor 89
TerminalCommand 126
TerminallnitException
122
TerminalTimeoutException 122
testing of cards and terminals 78
tier 216
time-to-market reduction 90
TLS 45,67
TLV 27,113,114
toolkit 24
trace 130
TraceLevels 105
Tracer 97, 105
Tracer. critical (String,
Throwable) 205
Tracer. info (String,
String) 205
TracerEvent 106
TracerListener 97, 106
trading protocol 226
transient array 235
transmission protocol 76
Transparent 29
transport protocol 79
triple DES 53
trusted authority 46
trusted channel 46
u
UML notation 91
Unified Modeling Language
(UML) 92
URLClassLoader III
USB 69
user. dir 110
user. home 110
Userlnteraction 126
v
Variable Record 29
vendor independence 90
VerifiedAPDUlnterface
125, 155
Visa Cash 38,40,41-43
voltage 76
w
waitForCard( ... ) 150,
200-201
warm reset 19
x
X-rays 21
z
ZentraIer KreditausschuB (ZKA)
39
ZKA 39
E Index
305