Add Security Support

The previous Sample Applet example is extremely simple and is not realistic. In particular, it does not include any form of security. Users are not authenticated and no transport security is provided. Of course, every smart card that implements the Java Card platform includes such security mechanisms, because they are central to Java Card technology.

The following section describes how to add security support to the Purse example.

The Purse interface in the package examples.securepurse is similar to the Purse interface used in the Sample Applet example. In addition, it might include reason codes for exceptions to report security violations to the terminal. This example replaces the Purse interface used in theSample Applet example with the following examples.securepurse code. ThePurse interface in the examples.securepurse does not include an implementation, which means that, in particular, it does not include any support for security.

The applet keeps its original organization but it also includes additional code that is dedicated to the management of security.

package examples.securepurse;

import javacard.framework.*;
import javacard.framework.service.*;
import java.rmi.*;

public class SecurePurseImpl implements Purse {
    private short balance;
    private SecurityService security;

    SecurePurseImpl(SecurityService security) {
        this.security = security;
    }

    public short debit(short amount) throws RemoteException, UserException {
        if ((!security
                .isCommandSecure(SecurityService.PROPERTY_INPUT_INTEGRITY))
                || (!security
                         .isAuthenticated(SecurityService.PRINCIPAL_CARDHOLDER)))
           UserException.throwIt(REQUEST_FAILED);
        if (( amount < 0 )|| ( balance < amount ))
            UserException.throwIt(REQUEST_FAILED);
        balance -= amount;
        return balance;
    }

    public short credit(short amount) throws RemoteException, UserException {
        if ((!security
                .isCommandSecure(SecurityService.PROPERTY_INPUT_INTEGRITY))
                || (!security
                        .isAuthenticated(SecurityService.PRINCIPAL_APP_PROVIDER)))
           UserException.throwIt(REQUEST_FAILED);
        if (( amount < 0 )||( amount > MAX_AMOUNT ))
           UserException.throwIt(REQUEST_FAILED);
        balance += amount;
        return balance;
    }

    public short getBalance() throws RemoteException, UserException {
        if ((!security.isAuthenticated(SecurityService.PRINCIPAL_CARDHOLDER))
                && (!security
                        .isAuthenticated(SecurityService.PRINCIPAL_APP_PROVIDER)))
            UserException.throwIt(REQUEST_FAILED);
        return balance;
    }
}