ArticlePDF Available

Abstract and Figures

This work proposes a methodology for the rigorous development of Java Card smart card applications, using the B Method. Its main feature is to abstract the particularities of Java Card and smart card aware applications from the specifier as much as possible. In the proposed approach, the specification of the aplication logic needs not be preoccupied with the specific aspects of the Java Card platform (in particular, communication between the card acceptance device and the smart card itself). Platform-specific code can then be automatically generated during the refinement and code generation process. An interesting side-effect of this approach is that the specification may be reused with any other platform of implementation.
Content may be subject to copyright.
Developing Java Card Applications with B
Bruno Emerson Gurgel Gomes1, Anamaria Martins Moreira1, David D´
eharbe1
1Departamento de Inform´atica e Matem´atica Aplicada
Universidade Federal do Rio Grande do Norte (UFRN)
Lagoa Nova
59072-970 – Natal – RN – Brazil
{bruno, anamaria, david}@consiste.dimap.ufrn.br
Abstract. This work proposes a methodology for the rigorous development of
Java Card smart card applications, using the B Method. Its main feature is
to abstract the particularities of Java Card and smart card aware applications
from the specifier as much as possible. In the proposed approach, the specifi-
cation of the aplication logic needs not be preoccupied with the specific aspects
of the Java Card platform (in particular, communication between the card ac-
ceptance device and the smart card itself). Platform-specific code can then be
automatically generated during the refinement and code generation process. An
interesting side-effect of this approach is that the specification may be reused
with any other platform of implementation.
1. Introduction
The smart card support is a component of the IT infrastructure in a growing number of
sectors [11]: banking, mobile and non-mobile communications, ID/access, leisure, retail
and loyalty, transport, healthcare, government, multimedia, etc. Most of the applications
require a high-degree of reliability, and make smart card aware software design a suitable
application for formal methods.
Java Card [4] is one of the leading technologies in this sector as it provides sig-
nificant features: multiple applications, portability, compatibility with a leading program-
ming language technology (Java). The strategic importance of this market is a strong
motivation to address the problem of providing rigorous software development processes
for smart-card aware applications based on the Java Card technology.
The B methodology [1] is a good candidate for such process. Based on the experi-
ence gathered from the development of formalspecification languagessuch as VDMand
Z, B has been one of the foremost formal methods with a strong industrial support and
has been applied in the development of safety-critical applications.
In this paper, we propose a specialization of the B methodology that aims at im-
proving the productivity in the development of Java Card software. Previous work [16]
showed the possibility to automatically generate Java Card code from B modules. How-
ever, this work is limited to the translation of the language aspects and ignores some im-
portant aspects of the Java Card platform, such as the communication between the host
application and the applet running on the smart card, leaving its specification and imple-
mentation as an additional burden to the designer. The goal of the research presented in
The work presented in this paper has been partially financed by CNPq (Conselho Nacional de Desenvolvimento Cient´ıfico e
Tecnol´ogico), a Brazilian governmental agency for the development of science and technology.
this paper is to provide B design guidelines specific for the Java Card framework which
make it possible to automate part of the specification and implementation needed to build
the communication protocol between the card applet and the host application.
The paper is organized as follows. The fundaments are presented in Section 2.
(overviewing smart cards and Java Card) and 3. (introducing the B method). The core
contribution of the paper is in Section 4., where the application of the B methodology to
design Java Card components is presented. Section 5. concludes the paper with related
work and some final remarks.
2. Smart Cards and Java Card
A smart card is a plastic card that looks like a common magnetic-stripe card, but that has
embedded in it an integrated circuit with a microprocessor and memory. This kind of card
offers several advantages compared with magnetic-stripe cards [10]. The most important
advantage is the security in data processing and storage provided by the smart card envi-
ronment composed by operating system, microprocessor and applications. In application
level, personal identification numbers (PIN) and cryptographic algorithms can be used
to improve the security. Other advantages are storage capacity, millions of times greater
than the capacity of magnetic-stripe cards; and the remote database query independence,
once every data the card needs is found in its memories or is supplied by an external
application.
Many applications can benefit from the use of smart cards. Telecommunication,
financial and transportation industries and the health care sector are good examples. The
secure transaction mechanisms and the elements for secure user identification and data
storage, besides the mobility of the cards, make them an ideal platform for these applica-
tions.
Java Card technology consists in a Java language subset. It allows memory-
constrained devices, like smart cards, to run applications in a secure and inter-operable
way. Security is obtained through Java elements, like its secure execution environment,
which controls, for instance, the level of access to all methods and attributes; and the
applet separation by a resource named applet firewall [4]. Inter-operability is the char-
acteristic that allows the execution of a Java Card application in any smart card that
follows the Java Card specifications, independently of hardware and software manufac-
turers, without or with few code modifications.
The use of this technology brings many improvements for the developer of smart
card applications. The ease of programming in Java, that abstracts the low level details
of the smart card system; and Java development tools (like IDEs, simulators and emula-
tors) allow a rapid application build, test and installation, reducing the time and the cost
of software production. Moreover, other benefits are the possibility of multiple applica-
tions to coexist in a same card and the ample compatibility with smart card international
standards, like ISO 7816.
2.1. Smart Card system and communication model
A smart card system is composed of hardware and software components. These compo-
nents are: Support software, software for communication with the card acceptance device
(CAD), the CAD itself and the smart cards and their applications.
User-CAD communication software (host application) This software is responsible
for the communication between an external application, called “host application”,
and the one inside the card. It sends commands for the smart card application
and receives the responses to these commands. This software can be included in a
desktop computer, ina cell phoneor in a securitysubsystem.
Card Acceptance Device (CAD)ACAD is the device localized between the host ap-
plication and the smart card. It supplies power to the card and is the means of
communication between the host application and the application inside the card.
ACAD can be connected to a desktop or a terminal, such as an electronic payment
terminal.
Smart Cards and their applications Inside the card’s memories are installed the appli-
cations. This can be done when the card is being manufactured, installing ap-
plications in its ROM memory, or later, installing the applications in the card’s
non-volatile and writable memory. Languages like C, the assembly language of
the card and Java Card can be used to develop these applications. Today, Java
Card is supported in more than 95% [14] of the cards and is considered the best
choice when productivity and security are the main requirements.
Support software This kind of software provides services to a smart card application.
For instance, we could have an application that allows the applet to access a credit
card operator service in a secure way.
The communication between these environmentitems is performed through a half-
duplexed protocol called Application Protocol Data Unit (APDU). An APDU message
has the form of a data package exchanged between the host application and the application
in the card in a master-slave architecture. The host application sends commands to the
card application, that, in turn, sends back a response. The command and the response
APDU are the two protocol structures used to send these messages. In this protocol, a
command APDU is always paired with a response APDU [4].
Acommand APDU has the structure shown in figure 1 below:
Figure 1. Command APDU structure. SOURCE: [9]
The command header is obligatory and is composed by four 1 byte fieds: CLA,
INS,P1 and P2. The CLA field identifies a class of command and response APDU .
The INS field corresponds to a instruction inside a CLA. These instructions can be, for
instance, method calls. P1 and P2 are parameters that can be used to supply some addi-
tional information to the INS instruction. The command body is required only for extra
data sending or receiving. The data is sent in the DATA field and has its length specified
in Lc. If a response with data is expected, its length has to be informed in the Le field.
The Lc and Le fields have 1 byte of length.
Aresponse APDU has a simple structure, which is shown in the figure 2 below:
Figure 2. Response APDU structure. SOURCE: [9]
The response is formed by the optional body, that contains the Data field, with
the data returned to the host application and the trailer, which contains the fields SW1 and
SW2 that together inform the command APDU processing status.
2.2. Java Card applets
AJava Card applet is a class written in the Java Card subset of the Java language that
inherits the javacard.framework.Applet class. This class is a blueprint that defines some
variables and methods of an applet [4]. It makes, for instance, the implementation of the
install and process methods obligatory. The install method creates the applet by invoking
its constructor method and registers it in the Java Card Runtime Environment (JCRE),
by invoking the register method. The process method receives the APDU messages of
the host application, does the initial processing of these messages, and invokesa method,
passing to it the APDU object as a parameter.
Example 1 A short applet example summarizing the affirmations made above is:
import javacard.framework.*;
public class Transport extends Applet {
//The current amount of credit
private short balance;
//The INS code of addCredit method
public static final ADD_CREDIT = 0x01;
/** Constructor method */
private Transport(byte[] bArray, short bOffset, byte bLength) {
balance = 0;
register();
}
/** Invoked by the JCRE, install is the applet entry point. It
creates an applet instance and registers it in the
JCRE through the invocation of the applet constructor method. */
public static void install(byte[] bArray, short bOffset, byte bLength) {
new Transport(bArray, bOffset, bLength);
}
/** process receives an APDU object and selects the instruction
specified in its INS filed. */
public void process (APDU apdu) {
byte[] buffer = apdu.getBuffer();
switch (buffer[ISO7816.OFFSET_INS]) {
case ADD_CREDIT:
addCredit(apdu);
}
/** The method addCredit adds some data to the balance attribute. */
public final void addCredit(APDU apdu) {
byte[] buffer = apdu.getBuffer();
byte bytesRead = (byte) apdu.setIncomingAndReceive();
balance = (short) (balance + buffer[ISO7816.OFFSET_CDATA]);
}
}
3. Software development with B
The B method for software development [17, 1] is based on theB Abstract Machine Nota-
tion (AMN) and the use of formally proved refinements up to a specification sufficiently
concrete that programming code can be automatically generated from it.
Its mathematical basis consists of first order logic, integer arithmetic and set the-
ory, and its basic constructs concerning them are very similar to those of the Z notation
[12]. Its structuring constructs are however stricter and more closely related to impera-
tive modular programming language constructs, with the intention of being more easily
understood and used outside the academic world. Also, its more restrictive constructs
simplify the job of support tools. Industrial tools for the development of B based projects
have been available for a while now [5, 2], with specification and verification support as
well as some project management tasks and support for team work. Its modular structure
and characteristics make it adequate for the specification of Application Programming
Interfaces (APIs) or other software components.
3.1. The B methodology
A B specification is structured in modules which are labeled according to their abstrac-
tion level: MACHINE,REFINEMENT or IMPLEMENTATION, from the most abstract to
the most concrete. The development process starts with one or more MACHINEs, which
may be refined into REFINEMENTs (optional) and then into IMPLEMENTATIONs. The
original abstract MACHINEs are to be proved consistent with respect to some specified
properties (particularly, the INVARIANT of each MACHINE) and then, each refinement
step has to be proved correct with respect to the corresponding machine. The IMPLE-
MENTATIONs are then checked for compliance with the code generator for a particular
language and, if it is the case, programming code may be generated. Assuming the cor-
rectness of the code generator, the generated code can be guaranteed to satisfy the stated
properties of the abstract specification (the MACHINEs).
3.2. The B notation
Although we concentrate our introduction to the B notation on the more abstract speci-
fication (i.e. MACHINE), similar comments apply to the remaining levels. A B module
contains two main parts: a state space definition and the available operations. It may
additionally contain auxiliary clauses in many forms (parameters, constants, assertions),
but those, essentially for practical purposes (i.e. to promote modularity, reuse, etc.), and
do not extend the expressive power of the notation. In the remainder, we will restrict our
discussion to the core clauses of the module specification.
The specification of the state components appears in the VARIABLES and IN-
VARIANT clauses. The former enumerates the state components, and the latter defines
restrictions on the possible values they can take. Essentially, if Vdenotes the state vari-
ables of a machine, the invariant is a predicate on V. Let us denote I N V such invariant
predicate. All verifications carried out throughout the development process have the in-
tention of checking that no invalid state will ever be reached as long as the operations of
the machine are used as specified.
For the specification of the initialisation as well as the operations,B offers a set of
so-called substitutions. These are “imperative-like” constructions with translation rules
that define their semantics as the effect they have on the values of any (global or local)
variables to which they are applied. The semantics of the substitutions is defined by the
substitution calculus, a set of rules stating how the different substitution forms rewrite
to formulas in first-order logic. Let Sdenote a substitution, Ean expression, then [S]E
denotes the result of applying Sto E.
The basic substitution, denoted v:= E(V), where Eis an expression on variables
V, states that, when the operation completes, the value of variable vis E(V), where
the values of the variables appearing in this expression are taken when the operation
initiates. For instance, an operation that would incrementing a counter variable cnt would
be specified as cnt := cnt + 1. Indeed, the basic substitution is very similar to the side-
effect free assignment construct found in imperative programming languages. Applying
such substitution to an expression consists in substituting the target variable vwith the
source expression. For instance, [cnt := cnt + 1]cnt 0 = cnt + 1 0. The B notation
provides conditional, non-deterministic, parallel, and other substitution constructs.
One very particular substitution is the PRE-THEN-END, which can be used to
specify any pre-condition that the definition of the operation assumes in order to “work
properly”. For instance, a partial operation that increments our counter variable only
up to a certain value max would be specified as cnt := PRE cnt <max THEN cnt :=
cnt +1 END . This construct offers the full expressive power of first-order logic to specify
the domain of an operation. It is therefore very useful to specify the bounds of application
of an operation, within which one expects that the machine will not reach any invalid
state.
Example 2 A very simple example of a B machine is:
MACHINE Transport
VARIABLES
balance
INVARIANT
balance : NAT
INITIALISATION
balance := 0
OPERATIONS
addCredit (cr) =
PRE
cr : NAT &
cr > 0 &
balance + cr <= MAX_DATA
THEN
balance := balance + cr
END
END
This example was extracted and simplified from the Transport machine, the main
machine of our sample transport application (Section 4.2.5.). In this piece of code, we
can see the machine name definition in the MACHINE clause. The state variable, named
balance, is typed in the INVARIANT clause and initialized in the INITIALISATION clause.
An operation, named addCredit, is used to add some positive natural value to the balance
variable.
3.3. Proof obligations
To guarantee the correctness of a B module, proof obligationsmust be generated from the
initialization clause and the operations definition, establishing that:
1. the initialization actions take the machine into a valid state, i.e. the initialization
substitution Sestablishes the invariant: [S]I N V .
2. the machine will not be taken from a valid state into an invalid one when any of
the machine’s operations is executed as long as the user provided parameters and
the machine variables are such that the pre-condition P RE for application of the
substitution Scorresponding to this operation evaluates to true: P RE I N V
[S]I N V .
4. Applying the B method to Java Card development
Smart cards store software components that are used by client applications, also called
host applications, that communicate with thecard via card acceptance device. Due to ob-
vious restrictions, the code embedded in smart cards has a simple structure. In particular,
Java Card imposes stringent restrictions on the Java language, e.g. excluding complex
data types and multi-threading. This is one of the scenarios for which the B notation is
well adapted.
The B method is used to specify the functionality of the card-side components.
However, this would require from the specifier to get into details of Java Card specific
communication and security issues. It is possible nevertheless to develop a completely
portable B specification of the application, as if it would execute on the same host as
the client application. From that specification, we propose to generate the “glue” code
responsible for hiding from the host all the complexity of implementing the APDU-based
communication protocol to access the card. Assuming that the specified component can
be implemented as a JAVA class with an interface I, our approach results in the generation
of the following components:
A host-side component Chwith interface I, responsible for performing remote
method invocation on the smart card by means of the standard protocol. Each
method in this class is thus responsible for communicating with the smart card, by
encoding, sending, receiving and decoding the APDU buffer carrying the method
calls, exceptions and return value.
A smart card-side component Cs, responsible for reading the APDU buffer con-
tents set by Ch, decoding them and dispatching the parameters to the code imple-
menting the logic of the corresponding specification operation, coding the result
into a response APDU packet and storing it into the APDU buffer.
4.1. Guidelines for the specification development
Our approach imposes few constraints on the specification of the smart card component.
As advocated by the proponents of aspect oriented programming (AOP) [8], the basic
functionality of a component should remain separated from other concerns (in our case,
the necessity to handle calls, exceptions and return values as APDU buffer contents).
Indeed, we see the Java Card specific part of the code as an aspect of the code transversal
to the application itself, or, as called in the AOP community, a crosscutting concern. In
AOP, however, the idea is that the source code of the aspect will still be separated from the
code of the application. Here, we do not try to do this, mainly because the management of
aspect could create execution resources overhead that smart cards cannot afford and also
because the user of the methodology shall not have to work at the source code level. Thus,
Java Card “aspects” remain separated at the specification level, while the generated code
is already weaved, i.e., aspect related code is already included in the application specific
code.
But better, from the specifier’s point of view, is that our approach relieves him
from the duty of specifying the aspect. Indeed, the particular characteristics of Java
Card make it possible to automatically generate most of the Java Card aspect code from
the original, Java Card free, application specific B specification.
For full automation of the process, however, some restrictions on the B machine
apply. They are:
1. The B integer variables must be restricted to the range of some Java Card integer
type, that are: byte, short. The int type is not supported in all Java Card imple-
mentations, for this reason it should not be used in a B specification. We provide
the specifier with (B specification and implementation of) Java Card compliant
data types.
2. The Java Card limitations must be respected for the B implementation machine.
For instance, a generated class can have at most 256 public or protected static
fields [13] and, consequently, a B machine must obey this restriction.
As long as the restrictions outlined here are respected, it is possible to automat-
ically generate Java code from the B specification of the API. But then, only a generic
specification which does not reflect its Java Card aspects would be available. Generation
is then executed in two steps:
1. in a first step, a Java Card extended version of the original specification is gen-
erated as well as some auxiliary specifications to relate Java Card aspects and
application specific aspects (all of them B machines)
2. in a second step, Java Card code is generated.
4.2. The development process
The process proposed in this paper starts from a initialB specification (a B MACHINE) of
the desired API. Let us call it API.mch. This machine is then submitted to two parallel
refinement/implementation sequences:
1. To develop the Smart Card implementation of the API, a refinement is usually
applied to make it a full-function machine, i.e.,all operations have minimum pre-
conditions (only typing restrictions) and deal internally (through exceptions) with
all the potential problems of invalid data and actions. We call this refinement
API FF.ref. Normally, an additional machine dealing with exceptions data
(say, API Exceptions.mch) is also generated. More information on how to
derive this refinement and the corresponding API Exceptions.mch from the
original specification is given in section 4.2.1., below.
2. The second line of development takes care of the implementation of the
API on the host side and is fully automatable. This implementation (say,
API Host imp.imp) translates the actions specified in each operation of
API.mch into data that is used by the Java Card Runtime Environment (JCRE)
to create APDU commands. It can be viewed as a wrapper, such that the host
application remains unaware of the Java Card remote implementation of the ma-
chine’s attributes and methods. A more detailed description of this implementa-
tion process is given in Section 4.2.4..
The relations among these specifications is shown in Figure 3.
B refinementB implementation
INCLUDES
API.mch
API_Host_imp.imp API_FF.ref API_Exceptions.mch
Figure 3. The two lines of development for an API machine
4.2.1. The full function API
The full-function machine API FF.ref refinement is required in order to have a more
robust specification for the API. The original abstract machine API.mch may only define
the main behaviour of each API operation, stating operation’s preconditions that have to
be satisfied in order to have a correct (invariant preserving) execution of the machine.
This kind of non-robust behaviour is in general not allowed in Smart Card applications,
and is certainly not the standard style of programming used by Java Card developpers.
Java Cardprogramming style includes internally validating all parameter data for
each operation, and exception raising each time a non-conformance is detected. Thus, the
specification developer may need to include these exceptions. For that, he must define the
API Exceptions machine and include it in the refinement. The API Exceptions
machine must contain all the exception names in a enumerated set (called EXCEPTIONS
by convention). At the API Exceptions implementation level, these constants will be
implemented by natural values and, when translated into a Java Card class, a constant
declaration will be generated for each exception element of the EXCEPTIONS set.
Example 3 If we consider the specification of Example 2, its refinement would look like:
REFINEMENT Transport_FF_ref
REFINES
Transport
INCLUDES
Exceptions
VARIABLES and INITIALISATION : as in the original specification
OPERATIONS
addCredit (cr) =
BEGIN
IF cr > 0 THEN
IF balance + cr <= MAX_DATA THEN
balance := balance + cr
ELSE
setException(data_overflow)
END
ELSE
setException(credit_not_positive)
END
END
END
We provide a template for the API Exceptions machine, containing a
variable to represent the last raised exception, an operation to raise an exception
(setException, used in API FF.ref) and the set EXCEPTIONS. It is the responsi-
bility of the designer to define this set in this machine, or in the refinement API FF.ref
(in this case the machine API Exceptions needs not be modified).
4.2.2. Generation of a Java Card version of the full function API
The full function machine obtained in the refinement above is not formally refinable (in
the sense of the B method) into a regular Java Card implementation of the API: indeed,
Java Card requirements and programming style enforce that method have the APDU
as formal parameter, which is therefore incompatible with the profile of operations in
API.mch.
A translation step has then to be performed to convert the interfaces of operations
to the Java Card style. This translation step takes as input API FF.ref and generates a
new B machine that we call API JC.mch. Note that here we do not strictly follow the B
development process as the resultof the translation is a new B abstract machine. This ma-
chine is then refined and implemented, following the rulesof B, into the B implementation
corresponding to the code that is to be embedded in the card. This new machine is also
imported by the implementation of the API on the host side to implement the variables of
API.mch, as shown in Section 4.2.4.. It uses a pre-defined machine, called JCRE.mch,
specifying parts of the APDU protocol and of the Java Card Runtime Environment, to
directly manipulate the APDU buffer.
This translation step is schematized in Figure 4. Because it only adapts the opera-
tions interfaces, it is fully automatable. In Java Card, the method receives the parameters
and returns its result via the APDU buffer. Additionally, the values passed through the
buffer need to be converted to the actual data types. The generated B machine includes
these necessary steps around the functional logic of the operation. This step is similar to
the AOP concept of weaving aspect with a class and is completely automatable.
Note that we cannot check immediately that the result of the translation is a re-
finement, as the interface is modified. However as the resulting module will be nested
within a wrapper that reestablishes the original interface, it will be possible to carry out
the refinement proof at this level.
4.2.3. Generating auxiliary machines of the Java Card platform
The full function machine API FF.ref is also the source for the generation of two
auxiliary machines needed to specify the logic of the APDU protocol and the Java Card
applet, as well as realizing data conversion between Java data types and APDU buffer
contents. We call these machines API Process.mch and API Conversions.mch.
res <-- op (params) =
BEGIN
IF params_validity
THEN
action
ELSE
exception
END
END
op (apdu) =
PRE
apdu : APDU_CMD_TYPE
THEN
LET params BE
params = apdu’data
INIF params_validity
THEN
action and set response
ELSE
exception
END
END
END
Figure 4. Translation of operation interfaces to meet Java Card standards
The API Process.mch defines a unique operation, named process, corre-
sponding to the process method that every Java Card applet needs to implement,
as explained in Section 2.2.. This operation processes the APDU command in order
to select which operation is to be executed. It uses data from the second machine,
API Conversions.mch, in order to improve readability, staying at a higher level.
MACHINE API_Process
SEES
API_Conversions
INCLUDES
API_JC
OPERATIONS
process (apdu) =
PRE
apdu : APDU_CMD_TYPE
THEN
SELECT
apdu’ins = op_code_of(op1) THEN
op1(apdu)
WHEN apdu’ins = op_code_of(op2) THEN
op2(apdu)
...
END
END
END
The API Conversions.mchmachine specifies all encoding information of the
application logic into bytes, the low level data that is communicated and manipulated in
the Java Card platform. Its minimal contents are shown below, in the case where the
only converted data is the operation names. Further encoding may be needed, e.g., for
enumerated types, such as a type that defines a category of users. In this case, additional
sets and translation functions have to be included and can be automatically generated
using classic compilation techniques.
MACHINE API_Conversions
SETS
OP_NAMES = // names of all operations of the API machine
CONSTANTS
op_code_of //function relating all OP_NAMES to number codes for them
//in the APDU
... other specific application data to be translated (e.g., enumerated types)
PROPERTIES
op_code_of : OP_NAMES --> BYTE
END
4.2.4. The host application’s side
As stated above, from the original abstract specification API.mch a B implementation
API Host imp.imp is derived which translates the actions specified in each operation
of API.mch into data that is used by the Java Card Runtime Environment (JCRE) to
create APDU commands.
This B implementation is constructed using data from its abstract implementation
API.mch and from a series of other machines that define the Java Card platform and
the Java Card implementation of the abstract API.
The general structure of this implementation is:
IMPLEMENTATION API_Host_imp
REFINES
API
SEES
API_Conversions
IMPORTS
JCRE
card.API_JC
INVARIANT
var = card.var (for each variable in API.mch)
OPERATIONS
res <-- op(params) =
VAR dd, st
INsendAPDUCmd(..APDU data..);
dd <-- getAPDUResData;
st <-- getAPDUResStatus;
res := dd’data
END
In Figure 5 is shown the hierarchy of the resulting specifications, which all
“execute” on top of the Java Card Runtime Environment (JCRE.mch): on the host
side we have API Host imp.imp, on the card side we have API JC.mch and
API Process.mch, and, defining the Java Card encoding of application data, the
API Conversions.mch.
Note that the implementation API Host imp can be automatically generated
from API.mch. Furthermore it is interface-compatible and is amenable to automated
refinement verification using existing B provers.
4.2.5. Case study
As a case study to apply the proposed methodology, we developed a specification of a
module for a mass transit system, one of the main business opportunity for smart cards in
the world and in Brazil particularly. The requirements in the case study are the following:
1. The cards are subdivided in three categories: full rate, student rate and gratuitous
rate.
(a) The trip price is one token.
(b) Full and student cards need to be loaded with a positive amount of tokens.
(c) The difference between the full rate and student rate only appears when
the user buys tokens.
2. The information stored in the card are its category (student, full and gratuitous),
the current amount of tokens, an hour and a date.
Figure 5. B specification of the Java Card platform “execution” environment
3. When boarding the vehicle, the user must pass their card through the reader.
(a) For full and student cards, the card is debited one token, and the user is
allowed to board.
(b) For gratuitous cards, no token is debited and the user is allowed to board.
4. Reloading the card is necessary for the full and student cards as soon as the amount
of tokens is equal to zero.
A very simplified version of the specification machine has been used as an illus-
tration for the B notation in Example 2, and a full-function refinement in Example 3.
We derived all the B modules described in the previous sections and generated the corre-
sponding proof obligations.
4.3. Java Card code generation from the B modules
The previous sections describe how, given a generic B machine specifying an API, it is
possible to generate a B implementation that includes data conversion and communication
aspects of the Java Card platform. The user only needs to realize a refinement to a full-
function version, obeying simple conventions to handle exceptional situations. From that
point, our methodology makes it possibleto generate B modules that can be shown to be
a refinement of the original machine and serve as a basis for a Java Card implementation
of this API. The generation of Java Card code from the B implementation level has been
studied previously [16] and an open-source prototype implementation is available. This
tool is a Java code generator that can be configured to respect Java Card restrictions. As
future work, we plan to extend this tool with the ideas presented in this paper.
5. Related work and conclusions
The main contribution of this work is to provide support for a rigorous development of
Java Card components for smart card aware applications, based on the B method. Fur-
thermore, we want to hide as much possible the idiosyncracies of Java Card and smart
cards. To achieve this goal, we proposed that the specification focuses on the so-called
application logic and ignores the aspect related to the implementation of the component
required to implement the Java Card communication protocol. As such the specification
remains generic enough to be refined and implemented towards other platforms.
Related work and tools concerning the generation of imperative (C, ADA) code
from B specifications, e.g., [5, 2, 3], have been around for a while. The generation of
object oriented code or models is however still a matter of current research as in, e.g.,
[7, 6, 15], where the translation from B specifications into UML diagrams is studied.
Recently, a Java code generation tool has been developed [16]. This tool is also a product
of a Smart Card development project (Projet BOM1), and it takes care of some memory
use optimization issues. Our work builds upon this previous work. However, in this
previous work, code generation is executed from an implementation-level B module that
is already very close to the Java Card implementation, and the generated code needs to be
manually modified to incorporate the communication and codification aspects particular
to the Java Card platform. Our proposal is to provide automated support to generate
such B IMPLEMENTATION from a generic specification, as it will be viewed by the
host application on the terminal side. Thus, all Java Card and protocol specific data and
methods are automatically generated from the API’s specification.
The proposed refinement and code generation methodology is composed of two
steps: first, a complete B specification with the Java Card aspects is produced, allowing
for specific verifications to be carried out; only then, Java Card code will be generated.
This second step may be partially carried out with existing tools ([16]). As future work,
we plan to prototype the ideas presented in this paper, i.e. build a tool that implements all
the steps that we identified as automatable, and apply them to different case studies. We
also plan to investigate security and authentication aspects within the proposed process.
References
[1] J.-R. Abrial. The B-Book — Assigning Programs to Meanings. Cambridge University
Press, 1996.
[2] B-Core Ltd. The B-Toolkit. B-Core internet site. Available at
http://www.b-core.com/btoolkit.html. Acessed on: Aug. 13th,
2005.
[3] Didier Bert, Sylvain Boulm, Marie-Laure Potet, Antoine Requet, and Laurent Voisin.
Adaptable translator of B specifications to embedded C programs. In Proceedings of
FME 2003, volume 2805 of LNCS, pages 94–113, Pisa, sept. 2003. Springer-Verlag.
[4] Zhiqun Chen. Java Card Technology for Smart Cards: Architecture and Programmer’s
Guide. Addison Wesley, Boston, 2000.
[5] Clearsy. B language reference manual: version 1.8.5. Available from:
<http://www.b4free.com/public/resources.php>, 2004. Acessed on: June 15 2005.
[6] Houda Fekih, Leila Jemmi, and Stephan Merz. Transformation des sp´ecifications B
en des diagrammes UML. In Proceedings of AFADL: Approches Formelles dans
l’Assistance au D´
eveloppement de Logiciels, Besancon, june 2004.
1lifc.univ-fcomte.fr/RECHERCHE/TFC/rntl bom.html
[7] A. Idani and Y. Ledru. Object oriented concepts identifications from formal B specifica-
tions. In Proceedings of 9th Int. Workshop on Formal Methods for Industrial Critical
Systems (FMICS’04), Linz, sept. 2004.
[8] Gregor Kiczales, John Lamping, Anurag Menhdhekar, Chris Maeda, Cristina Lopes,
Jean-Marc Loingtier, and John Irwin. Aspect-oriented programming. In Proceed-
ings European Conference on Object-Oriented Programming, volume 1241, pages
220–242. Springer-Verlag, 1997.
[9] Enrique C. Ortiz. An introduction to java card technology. Available from:
<http://developers.sun.com/techtopics/mobility/javacard/articles/javacard1>, 2003.
Acessed on: november 19 2004.
[10] Wolfgang Rankl and Wolfgang Effing. Smart Card Handbook. John Wiley & Sons Ltd.,
Baffins Lane, 3rd. edition, 2003.
[11] Derrick Robinson. The worldwide market for smart cards and semiconductors in smart
cards, 2004 edition. Technical report, IMS Research, 2005.
[12] J.M. Spivey. The Z Notation: a Reference Manual. Prentice-Hall International Series in
Computer Science. Prentice Hall, 2nd edition, 1992.
[13] SUN MICROSYSTEMS INC. Java card platform specification. Available from:
<http://java.sun.com/products/javacard/specs.html>, 2003. Acessed on: june 15
2005.
[14] SUN MICROSYSTEMS INC. Java card technology at-a-glance: The
foundation for secure digital identity solutions). Available from:
<http://www.sun.com/aboutsun/media/presskits/javaone2005/JavaCard aag fin
al-3.pdf>, 2005.
[15] B. Tatibouet, A. Hammad, and J. C. Voisinet. From abstract B specification to UML
class diagrams. In Proceedings of 2nd IEEE International Symposium on Signal
Processing and Information Technology (ISSPIT’2002), Marrakech, dec. 2002.
[16] B. Tatibouet, A. Requet, J.C. Voisinet, and A. Hammad. Java Card code generation from
B specifications. In 5th International Conference on Formal Engineering Methods
(ICFEM’2003), volume 2885 of LNCS, pages 306–318, Singapore, November 2003.
[17] J. B Wordsworth. Software Engineering with B. Addison Wesley, Boston, 1996.
... Apart from the related work (e.g. [9], [10], [11], [12]) which mainly considers model driven smart card software development only specific for the Java Card framework [13], the study presented in this paper introduces a platform independent metamodel (PIMM) for smart card systems in order to free the developer from taking into consideration the specific needs of different smart card platforms such as Java Card. Furthermore, the proposed PIMM enables the developer to model the smart card system conforming to data transmission and data storage standards brought by ISO/IEC 7816 standards family [2]. ...
... A methodology based on the B Method [36] is introduced in [11] for the development of Java Card applications. The B method is used to specify the functionality of the card-side components. ...
... This work is based on a previous study [10] and aims to provide automated support to generate Java Card methods from B specifications. In Tatibouet Similar to works in [9], [10] and [11], our previous work [37] also deals with the automatic generation of Java Card applications. Modeling smart card software according to Java Card specifications and code generation from the designed models are guided with a graphical tool. ...
Article
Full-text available
Smart cards are portable integrated devices that store and process data. Speed, security and portability properties enable smart cards to have a widespread usage in various fields including telecommunication, transportation and the credit card industry. However, the development of smart card applications is a difficult task due to hardware and software constraints. The necessity of the knowledge of both a very low-level communication protocol and a specific hardware causes smart card software development to be a big challenge for the developers. Written codes tend to be error-prone and hard to debug because of the limited memory resources. Hence, in this study, we introduce a model driven architecture which aims to facilitate smart card software development by both providing an easy design of smart card systems and automatic generation of the required smart card software from the system models. Differentiating from the previous work, the study in here contributes to the field by both providing various smart card metamodels in different abstraction layers and defines model-to-model transformations between the instances of these metamodels in order to support the realization of the same system on different smart card platforms. Applicability of the proposed methodology is shown for rapid and efficient application development in two major smart card frameworks: Java Card and ZeitControl Basic Card. Lessons learned during the industrial usage of the architecture are also reported in the paper. Finally, we discuss how the components of the architecture can be integrated in order to provide a domain-specific language for smart card software.
... In this paper, we propose a specialization of the B methodology that aims at improving the productivity and reliability in the development of Java Card software. Previous work showed the possibility to automatically generate Java code [17] and Java Card 2.1 components [8] from B modules. [17] is limited to the translation of the language aspects and ignores some important aspects of the Java Card platform, such as the communication between the host application and the applet running on the smart card, leaving its specification and implementation as an additional burden to the designer. ...
... d Java Card 2.1 components [8] from B modules. [17] is limited to the translation of the language aspects and ignores some important aspects of the Java Card platform, such as the communication between the host application and the applet running on the smart card, leaving its specification and implementation as an additional burden to the designer. [8] does not take advantage of the high-level communication facilities provided in Java Card 2.2. The goal of the research presented in this paper is to provide B design guidelines specific for the Java Card framework which make it possible to possible to target the Java Card 2.2 computing environment. The paper is organized as follows. The ...
... If the target platform is Java Card 2.1, then the code generated from the B artifacts needs to implement the coding and decoding of method calls in the APDU-based communication protocol to access the card. We have shown in a previous work an approach to generate automatically such code from a B specification [8]. When the target platform is Java Card 2.2, then the code synthesis can take advantage of the Remote Method Invocation mechanism (RMI) to code at a higher level of abstraction . ...
Article
Full-text available
This paper presents a methodology for the rigorous de-velopment of Java Card smart card applications, using the B Method. Its main feature is to abstract the particularities of Java Card and smart card aware applications from the specifier as much as possible. In the proposed approach, the specification of the aplication logic does not need to take into account the specific aspects of the Java Card plat-form (in particular, communication between the card accep-tance device and the smart card itself). A sequence of pre-established refinements is then applied to the original spec-ification to yield an implementation-level B description of the component, which can then be used to synthesize Java Card code. An interesting side-effect of this approach is that the specification may be reused with any other platform of implementation.
... The B method [3] is a good candidate for such process, since it is a formal method with a successful record to address industrial-level software development. In [4, 5], we proposed two versions of a Java Card software development method (called BSmart) based on the B method. Section 2 summarizes the main steps of the BSmart method. ...
Conference Paper
Full-text available
A smart card is a portable computer device able to store data and execute commands. Java Card [1] is a specialization of Java, providing vendor inter-operability for smart cards, and has now reached a de facto standard status in this industry. The strategic importance of this market and the requirement for a high reliability motivate the use of rigorous software development processes for smart card aware applications based on the Java Card technology. The B method [2] is a good candidate for such process, since it is a formal method with a successful record to address industrial-level software development. In [3,4], we proposed two versions of a Java Card software development method (called BSmart) based on the B method. The main feature of these methods is to abstract the particularities of smart card systems to the applications developers as much as possible. This abstract presents the current version of a tool, also called BSmart, to support the method. The tool provides the automatable steps required by the method and some guidelines and library machines that are useful during the development process. It includes B development tools (type checker, PO generator) and specific BSmart tools (refinement generator, Java Card translator, etc.). In this approach, the card services specifier only needs to apply some refinement steps to his abstract (implementation platform independent) B specification. The generation of these refinements adapts the specification to Java Card standards and introduces platform specific aspects gradually. Finally, from the concrete B refinements the Java Card code implementing the services provided by the card will be automatically generated by the tool. The tool also provides the generation of a Java API for the host-side application from the original abstract specification, encapsulating all the communication protocol details. Thus, the client application code can then be developed in a completely platform independent way. The definition of the method is in a mature stage, and our attention is now focused on the implementation of more robust versions of the BSmart tools and packaging them in a user-friendly environment. The integration of verification and animation tools is also planned for a next release of the tool.
... For the client (host application) we provide the generation of an API to communicate with the applet that takes care of all the work related with Java Card protocol aspects and transparent Java/Java Card data coding/encoding. Previous work [2] [3] introduced the basic structure of the BSmart method. Its tool support has been also presented as a short paper in [4]. ...
Conference Paper
Full-text available
Smart Card applications usually require reliability and security to avoid incorrect operation or access violation in transactions and corruption or undue access to stored information. A way of reaching these requirements is improving the quality of the development process of these applications. BSmart is a method and a corresponding tool designed to support the formal development of the complete Java Card smart card application, following the B formal method.
Article
Full-text available
Automated code generation is fostered by several software development methods. This generation is often supplied by well-known CASE (Computer-Aided Software Engineering) tools. However, automation is still so far and some CASE tools are complemented by non-standard modeling projects. In this paper, we conceptualize projects related to automated code generation, starting from discourse representations in either controlled or natural language, or in conceptual schemas. In this way, we present a graphical summary of crucial concepts related to this issue, by means of a state-of-the-art review. We conclude that automated code generation usually begins from solution-based representations of the problem instead of domain-based representations. Also, we summarize that these starting points are misunderstood by the client and this situation leads to poor validation in early stages of software development lifecycle.
Article
In this article, we present a series of four industrial case studies in software verification. We applied VeriFast, a sound and modular software verifier based on separation logic, to two Java Card smart card applets, a Linux device driver, and an embedded Linux network management component, the latter two written in C. Our case studies have been carefully selected so as to evaluate the industrial applicability of VeriFast. We focus on proving the absence of safety violations, e.g., that the programs do not perform illegal operations such as dividing by zero or illegal memory accesses. Yet, given the sensitive application environment of our case studies, these safety properties typically have security implications. In this article we give a detailed description of the VeriFast approach to software verification based on two of the above case studies, one in Java and one in C. Finally, we draw conclusions on the overall feasibility of using VeriFast to verify software components in industrial domains that have stringent requirements on reliability and security.
Conference Paper
If we want to use Z to write an overall system specification, we need to integrate it into a rich set of documents written in natural language and domain-specific notations. These documents must be easy to write and read by non-mathematicians. On a purely practical level, this implies that we want Z to be part of the ordinary documents that are used every day on the project. That means, in practice, that it has to be integrated into Microsoft Word. I describe a tool for writing and checking Z within the Word environment and some progress towards a process for writing the specification and guidelines for its structure.
Article
Full-text available
Existen varios métodos de desarrollo de software que impulsan la generación automática de código. Para tal fin se utilizan las herramientas CASE (Computer-Aided Software Engineering) convencionales, pero aún están muy distantes de ser un proceso automático y muchas de estas herramientas se complementan con algunos trabajos que se alejan de los estándares de modelado. En este artículo se presentan una conceptualización de los trabajos relacionados con la generación automática de código, a partir de la representación del discurso en lenguaje natural o controlado o de esquemas conceptuales, y un sumario gráfico de los conceptos fundamentales en este tema, tras la revisión de varios proyectos relacionados. Así, se concluye que la generación automática de código suele partir de representaciones de la solución del problema y no desde la representación del dominio. Además, estos puntos de partida son de difícil comprensión para el cliente, lo que impide que se tenga una validación en etapas previas del desarrollo.
Article
Full-text available
Résumé Les méthodes formelles et semi-formelles de conception de systèmes in-formatiques mettent en avant différents concepts principaux de développe-ment. Plusieurs travaux se sont déjà intéressés à la formalisation des mé-thodes semi-formelles par des méthodes formelles telle que la formalisation de UML par B. L'objectif de ces travaux est surtout de pouvoir vérifier for-mellement les propriétés attendues du système. Dans cet article, nous étu-dions le schéma réciproque. Nous voulons représenter des spécifications B par des modèles UML afin d'obtenir une meilleure documentation et lisi-bilité en bénéficiant des concepts de structuration présents en UML. Nous présentons des éléments d'une transformation interactive guidant le concep-teur à générer une représentation naturelle de son modèle. L'objectif global de ce travail est de pouvoir établir une démarche où les représentations en UML et en B constituent deux vues complémentaires d'un même système en offrant à l'utilisateur la possibilité de naviguer entre ces deux vues et de pouvoir choisir le langage le plus adapté. Mots clés : UML, diagramme de classes, diagramme d'état-transitions, mé-thode B, raffinement.
Article
Full-text available
This paper addresses the graphical representation of static aspects of B specifications, using UML class diagrams. These diagrams can help understand the specification for stakeholders who are not familiar with the B method, such as customers or certification authorities. The paper first discusses some rules for a preliminary derivation of a class diagram. It then studies the consistency of the concepts preliminarily identified from an object oriented point of view. A formal concept analysis technique is used to distinguish between consistent classes, attributes, associations and operations. The proposed technique is to incrementally add operations to the formal specification which automatically result in evolution of the class diagram.
Conference Paper
Full-text available
This paper presents the results of the RNTL BOM project, which aimed to develop an approach to generate efficient code from B formal developments. The target domain is smart card applications, in which memory and code size is an important factor. The results detailed in this paper are a new architecture of the translation process, a way to adapt the B 0 language in order to include types of the target language and a set of validated optimizations. An assessment of the proposed approach is given through a case study, relative to the development of a Java Card Virtual Machine environment.
Article
An abstract is not available.
Conference Paper
We have found many programming problems for which neither procedural nor object-oriented programming techniques are sufficient to clearly capture some of the important design decisions the program must implement. This forces the implementation of those design decisions to be scattered throughout the code, resulting in “tangled” code that is excessively difficult to develop and maintain. We present an analysis of why certain design decisions have been so difficult to clearly capture in actual code. We call the properties these decisions address aspects, and show that the reason they have been hard to capture is that they cross-cut the system's basic functionality. We present the basis for a new programming technique, called aspect-oriented programming, that makes it possible to clearly express programs involving such aspects, including appropriate isolation, composition and reuse of the aspect code. The discussion is rooted in systems we have built using aspect-oriented programming.
Conference Paper
The French BOM (B with Optimised Memory) project has analysed issues related to code generation from B specifications. This analysis was built upon the shortcoming of the existing translators, and led to proposals to generate optimised code suitable for embedding in highly memory-constrained devices, such as smart cards. Two code translators have been developed: one targetting C, suitable for system or virtual machine development; the second targetting object oriented languages. This second translator enables the writing of Java Card applications. This paper presents results of the BOM project related to the Open-Source Java/Java Card translator.
Book
The B method is a means for specifying, designing and coding software systems. The long-awaited B Book is the standard reference for everything concerning this method. It contains the mathematical basis on which it is founded, the precise definitions of the notations used, and a large number of examples illustrating its use in practice. J.-R. Abrial, the inventor of B, has written the book in such a way that it can be used for self-study or for reference. It is in four parts, the first dealing with the mathematical foundations, including a systematic construction of predicate logic and set theory, and the definition of the various mathematical structures that are needed to formalize software systems; the author places special emphasis on the notion of proof. The second part contains a presentation of the Generalized Substitution Language and of the Abstract Machine Notation, which are both used to specify software systems; the author gives examples to show how large specifications can be constructed systematically. The next part introduces the two basic programming features of sequencing and loop, with examples showing how to construct small algorithms. The last part covers the very important notion of refinement. It shows how to construct large software systems by means of layered architectures of modules. It culminates with the presentation of several examples of complete development with a special emphasis on the methodological approach. Finally, appendices give summaries of all the logical and mathematical definitions, and of all the rules and proof obligations. With the appearance of The B Book, formal methods practitioners, computer scientists, and systems developers at last will have access to the definitive account of what will become one of the standard approaches to the construction of software systems.