MIDP: SATSA-PKI API Developer's Guide -...

26
MIDP: SATSA-PKI API Developer's Guide Version 1.0 February 2nd, 2007 S60 p l a t f o r m

Transcript of MIDP: SATSA-PKI API Developer's Guide -...

MIDP: SATSA-PKI APIDeveloper's GuideVersion 1.0February 2nd, 2007

S6

0p

la

tf

or

m

Legal NoticesCopyright © 2007 Nokia Corporation. All rights reserved. Nokia and Nokia Connecting Peopleare registered trademarks of Nokia Corporation. Java and all Java-based marks are trademarksor registered trademarks of Sun Microsystems, Inc. Other product and company namesmentioned herein may be trademarks or trade names of their respective owners.

Disclaimer

The information in this document is provided “as is,” with no warranties whatsoever, includingany warranty of merchantability, fitness for any particular purpose, or any warranty otherwisearising out of any proposal, specification, or sample. Furthermore, information provided in thisdocument is preliminary, and may be changed substantially prior to final release. This documentis provided for informational purposes only.

Nokia Corporation disclaims all liability, including liability for infringement of any proprietaryrights, relating to implementation of information presented in this document. Nokia Corporationdoes not warrant or represent that such use will not infringe such rights.

Nokia Corporation retains the right to make changes to this specification at any time, withoutnotice.

License

A license is hereby granted to download and print a copy of this specification for personal useonly. No other license to any other intellectual property rights is granted herein.

MIDP: SATSA-PKI API Developer's Guide | 2

Version 1.0 | February 2nd, 2007

Contents1 About this document.............................................................................................................. 52 Introduction to MIDP security ................................................................................................ 6

2.1 Security risks in the MIDP environment ........................................................................ 62.2 Protection Domains ....................................................................................................... 72.3 Permissions framework ................................................................................................. 82.4 Trusted MIDlets ............................................................................................................. 92.5 Untrusted MIDlets........................................................................................................ 102.6 User granted permissions ........................................................................................... 102.7 APIs and security ....................................................................................................... 11

3 SATSA-PKI overview .......................................................................................................... 124 Using SATSA-PKI ............................................................................................................... 14

4.1 Creating signing requests and managing user credentials ......................................... 144.2 Using signature services ............................................................................................. 14

5 Example: Creating digital signatures................................................................................... 165.1 Prerequisites ............................................................................................................... 175.2 Implementation of the PKI MIDlet................................................................................ 175.3 Developing the PKI MIDlet ......................................................................................... 175.4 Building and running in an emulator............................................................................ 265.5 Deploying to a device .................................................................................................. 26

MIDP: SATSA-PKI API Developer's Guide | 3

Version 1.0 | February 2nd, 2007

Change History

February 2nd,2007

Version 1.0 This is the first release of this tutorial.

MIDP: SATSA-PKI API Developer's Guide | 4

Version 1.0 | February 2nd, 2007

1 About this documentThis document describes the basic capabilities of the SATSA-PKI API of the Security and TrustServices (SATSA) API. The document also provides a step-by-step guide to help you to builda MIDlet using a smart card to digitally sign data and manage user certificates, whichdemonstrates some basic uses of the API.

Intended audience

This document is intended for MIDP developers, as well as Java™ EE and Java SE developerswishing to develop mobile Java applications or services. The reader should be familiar withMIDP 2.0 (especially the LCDUI API) before attempting to understand this example.

Scope

This document assumes a good knowledge of application and service development and theJava programming language. Furthermore, it assumes familiarity with enterprise applicationdevelopment. However, previous knowledge of developing for the mobile environment is notnecessary.

This document focuses on SATSA-PKI and therefore explaining the Java technology is out ofthe scope of this documentation. For information on Java technology, see Java Technology website at http://java.sun.com/ and Java Mobility Development Center at http://developers.sun.com/techtopics/mobility/. For additional information on MIDP tools and documentation, see ForumNokia, Mobile Java section at http://www.forum.nokia.com/java.

MIDP: SATSA-PKI API Developer's Guide | 5

Version 1.0 | February 2nd, 2007

2 Introduction to MIDP securityThis section introduces you to MIDP security. The following topics are handled:

• Security risks in the MIDP environment• Protection Domains• Permissions framework• Trusted MIDlets• Untrusted MIDlets• User granted permissions• APIs and security

For more information on MIDP security, see the documents:

• MIDP 2.0 specification (JSR-118) at http://jcp.org/en/jsr/detail?id=118.• The Recommended Security Policy for GSM/UMTS Compliant Devices (comes with the

MIDP 2.0 specification)

2.1 Security risks in the MIDP environmentThis section introduces the security threats in the mobile environment and some of the targetsof those threats.

The following figure illustrates some of the threats to mobile devices:

Figure 1: Security threats in the mobile environment

The main security threats in the mobile environment are:

MIDP: SATSA-PKI API Developer's Guide | 6

Version 1.0 | February 2nd, 2007

• Loss or theft of devices – mobile devices (or their removable media, otherwise known asmemory cards) are quite small and are carried by their users. Therefore, they can be easilylost or stolen.

• Viruses, Trojans, or unstable or other malicious applications – mobile devices allow 3rd partyapplications to be installed, to access device capabilities and to be used by other, possibly3rd party, applications. Therefore, devices are now exposed to the threats associated withthe installation of applications of unknown origin in a more open environment.

• Misuse of remote management – mobile devices allow applications to be delivered,deployed, operated, and maintained remotely by management servers, possibly without theknowledge or consent of the device user. This remote management therefore poses asecurity threat to these devices.

The possible targets of these security threats include:

• Personal data stored on the mobile device. This includes access information for internetbanking, credit card numbers, building access codes, or family related information.

• Business data stored on the mobile device. This includes client contact information, projectlaunches, marketing plans, or product specifications.

• Business infrastructure accessed by the mobile device. This includes file storage systems,accounting systems, e-mail systems, or security systems.

• Device operating system. This includes access to the device file system, access to otherapplications or access to management capabilities. Note that erroneous or maliciousapplications can cause damage to these areas.

• As a part of regular use, applications on a device may need to communicate with the deviceuser in security related questions. The operating system may need to ask the user to entera password or PIN, an application installer may prompt the user to confirm the installation ofsome software, a secure file system implementation may prompt for a password. Maliciousapplications may try to masquerade as trusted applications and obtain sensitive informationby misleading the user.

2.2 Protection DomainsA protection domain is a set of permissions and interaction modes. Those permissions can beeither automatically granted or deferred until user approval. There are four different interactionmodes for permissions: Blanket, Session, Oneshot, and No (see section User grantedpermissions). When a MIDlet suite is installed, it is assigned to a given protection domain andacquires its permissions and interaction modes.

Each protection domain, except for the untrusted domain, is associated to a set of rootcertificates. When signing a MIDlet suite, it is necessary to use a public key certificate that canbe validated to one of those root certificates. This association will be used to assign the MIDletsuite to a given protection domain. The relationship between root certificates and protectiondomain is that a domain can be associated to many root certificates, whereas a root certificateis associated to only one domain.

The MIDP 2.0 specification recommends four protection domains for GSM/UTMS devices:

• Manufacturer

The manufacturer domain uses root certificates belonging to the device producer.• Operator

The operator domain is used for the network operator MIDlets and may use root certificatesavailable on storages such as SIM cards.

• Trusted third party

The trusted third party domain will encompass well-known Certificate Authorities' (CA) rootcertificates.

• Untrusted

MIDP: SATSA-PKI API Developer's Guide | 7

Version 1.0 | February 2nd, 2007

The mandatory untrusted domain has not an associated root certificate and is used forunsigned and MIDP 1.0 MIDlet suites.

Java Code signing certificates which have been acquired from well-known Certificate Authorities(CAs) and are included in the target devices, can be used to sign MIDlets. Alternatively, diversedeveloper programs, for example, from operators or other software publishers, offer signingservices when an application is submitted to them (see for example Java Verified™ ProgramWeb page at http://javaverified.com/).

Since the amount of domains and their associated permissions may deviate from therecommendations of the MIDP 2.0 addendum in some networks, you should seek informationfrom the network operator your MIDlet suite is targeting to. Additionally, it may be worthwhilechecking the set of root certificates available on a given device for Java authentication.

2.3 Permissions frameworkPermissions are used to protect access to APIs or functions that require authorization beforethey can be used. A MIDlet suite has to request permissions declaratively using the followingattributes either in the application descriptor or in the manifest file:

• MIDlet-Permissions

MIDlet-Permissions contains permissions that are critical for the suite's functionality• MIDlet-Permissions-Opt

MIDlet-Permissions-Opt indicates desired permissions, which are not so fundamental for thecore functionality

For example, for an application's functionality it is critical to make HTTP connections to work.It may also use HTTPS connections for improved security, but it is not so vital. In this case, theapplication descriptor could look like this:

MIDlet-Permissions: javax.microedition.io.Connector.httpMIDlet-Permissions-Opt: javax.microedition.io.Connector.https

Note: MIDlet suites with misspelled permissions will make the installation fail.

Function groups

Instead of making the user manage each individual permission requested by a MIDlet suite,permissions can be grouped by functionality in Function Groups. The user will then givepermissions to Function Groups, for example the "Net Access" Function Group when usingnetwork features, rather than explicitly for thejavax.microedition.io.Connector.http permission. Using a higher-level concept likeFunction Groups instead of single permissions is better suited for user interaction in smalldevices.

The MIDP 2.0 and JTWI specifications have defined the following Function Groups:

• Phone Call (available only in S60)

Permissions related to any function that results in a phone call.• Net Access

Contains permissions related to network data connections.• Messaging

Set of permissions related to sending or receiving messages like SMS.• Auto Invocation

Permissions related to automatically starting a MIDlet, for example by Push Registration.• Local Connectivity

Permissions related to connection via local ports like IrDA or Bluetooth.

MIDP: SATSA-PKI API Developer's Guide | 8

Version 1.0 | February 2nd, 2007

• Multimedia Recording

Permissions that allow to record images, audio, video, and so on.• Read User Data

Set of permissions to read user data, such as phone book or calendar entries• Write User Data

Permissions related to writing user data.

The availability of these Function Groups depends on the device's capabilities. For instance,"Multimedia Recording" would not be available for devices without media capturing facilities orfor those where the Media API is not available.

Function Groups also determine which interaction modes are available for the trusted anduntrusted domains. For example, in the untrusted domain, "Net Access" can be set as sessionor denied, with blanket being disabled. On the other hand in the trusted domain, oneshot,blanket, and denied are allowed.

In addition of the above, Function Groups contain exclusion rules to forbid some combinationsof permissions that are not allowed simultaneously. For instance, it would not be desirable tohave blanket permission for "Net Access" and "Auto Invocation" at the same time. If this werethe case, a MIDlet would set itself for periodical restart and make network connections withoutuser permission, creating unsolicited charges for the user.

An example of Function Groups usage can be seen in S60 screen shots shown in the figurebelow. They show the "Network Access" Function Group found in the Application Managerapplication. The screen shot on the left is for an unsigned MIDlet suite, and the one on the rightis for the same MIDlet signed with a Verisign certificate. Clearly the difference is that with thesigned MIDlet the user can allow the MIDlet to open network connections without user'sprompts.

Figure 2: Network Access Function Group for an unsigned and signed MIDlet suite (Nokia S60screen shots)

2.4 Trusted MIDletsIf the device can verify the authenticity and integrity of the MIDlet suite and assign it to aprotection domain, the MIDlet suite is said to be trusted. A trusted MIDlet suite will have itsrequested permissions granted according to its protection domain. For example, if thejavax.microedition.io.Connector.http permission was requested and the protectiondomain has set the permission as allowed, no user confirmation will be needed to open an HTTPconnection.

Do not confuse the concept of trusted MIDlet suite with the trusted protection domain. Eachtrusted MIDlet suite is assigned to a particular protection domain depending on the authorizationmechanism.

MIDP: SATSA-PKI API Developer's Guide | 9

Version 1.0 | February 2nd, 2007

To sign your MIDlet you will need a code-signing certificate conforming to the X.509 Public-KeyInfrastructure (PKI) specification at http://www.ietf.org/rfc/rfc2459.txt. The device will use a setof root certificates to validate the MIDlet suite's certificate. Among them it is expected to find themanufacturer's root certificate and well-known CA's root certificates. Depending on the CA'spolicy, the certificate can include any number of intermediate certificates that should also beincluded in the MIDlet.

All the certificates used to sign the MIDlet are to be included in the suite's JAD file using theMIDlet-Certificate-<n>-<m> attributes. Besides the certificates, the SHA1 digest of the JAR filesigned with the suite's certificates is stored in the JAD file on the MIDlet-Jar-RSA-SHA1attribute.

The process of verifying whether a MIDlet suite is trusted is done when the suite is downloadedor installed. The application manager checks the JAD file and if it contains a MIDlet-Jar-RSA-SHA1 attribute, it will initiate the authentication and authorization procedures.

During the authentication, it reads the chain of certificates in the JAD file written in the attributesMIDlet-Certificate-<n>-<m> (where n and m are numbers indicating the certificate chain), andtries to validate the certificate with one of the root certificates.

If the certificate chain can be validated to a root certificate, the device will extract the public keyfrom the MIDlet's suite certificate and use it to decrypt the MIDlet-Jar-RSA-SHA1 attribute.The resulting value will be the SHA1 digest of the MIDlet JAR. The MIDP implementation willthen calculate the same digest value from the JAR file.

If both digests are equal, the MIDlet suite is authenticated and it will be allocated to the protectiondomain assigned to the root certificate. If one or more requested permissions on the MIDlet-Permissions attribute are not in the protection domain, the installation will not be allowed tocontinue. On the other hand, if some of the requested MIDlet-Permissions-Opt are not in theprotection domain, the installation can proceed.

2.5 Untrusted MIDletsThe MIDP 2.0 specification defines as untrusted a MIDlet suite for which the origin and integrityof the JAR file cannot be verified by the device. This does not mean that the MIDlet cannot beinstalled or executed; it just means that the access to restricted operations requires explicit userpermission. All MIDP 1.0 MIDlets are by default untrusted.

Untrusted MIDlets can call any API without permission if the API is not protected. That includesall classes in the following packages:

java.utiljava.langjava.io javax.microedition.rmsjavax.microedition.midletjavax.microedition.lcduijavax.microedition.lcdui.gamejavax.microedition.mediajavax.microedition.media.control

In case an untrusted MIDlet suite tries to invoke a protected API and does not have thepermission, for example if the user rejects the permission's prompt, a SecurityExceptionwill be thrown. The MIDlet should catch those exceptions and handle them properly.

It is also worth noticing that the Nokia's UI API is not protected. This includes the classes in thecom.nokia.mid.sound and com.nokia.mid.ui packages.

2.6 User granted permissionsUser permissions allow the user to deny permission or to grant permission to a specific API.User permissions may require an explicit approval by the user. The user can either deny thepermission or allow it. There are three interaction modes in which user permissions can begranted:

• blanket/aAlways allowed

MIDP: SATSA-PKI API Developer's Guide | 10

Version 1.0 | February 2nd, 2007

When the blanket/Always allowed interaction mode is used, the MIDlet suite acquires thepermission as long as the suite is installed, unless explicitly revoked by the user.

• session/ask first time only

The session/ask first time only mode requests the user authorization the first time the API isinvoked and its validity is guaranteed while any of the MIDlets in the same suite are running.

• oneshot/ask every time

oneshot/ask every time permissions request user approval every time the API is invoked.The protection domain determines which of the modes are available for each user permissionas well as the default mode.

Choosing the appropriate user permission interaction modes should be based on the securitypolicy and the device implementation. User permissions come with their own default interactionmodes. The user SHOULD be presented with a choice of interaction modes. The user MUSTalways be able to deny permission.

2.7 APIs and securityIn addition to MIDP 2.0 specification (JSR-118) at http://jcp.org/en/jsr/detail?id=118, TheSATSA API also provides important security features.

The Security and Trust Services API (SATSA), (JSR 177) specification at http://www.jcp.org/en/jsr/detail?id=177 is a set of optional APIs that allows using interfaces to PKI certificates,private data storage, cryptographic operations and secure environment services forauthentication, authorization, and identification for applications. Each SATSA API is optionaland may be implemented independently from each other. The following four APIs are definedin the SATSA specification:

• SATSA-APDU is an API that allows the application to communicate with a smart card (forexample, the SIM card).

• SATSA-PKI is used for generation of digital signatures and basic user credentialmanagement.

• SATSA-CRYPTO is a subset of the J2SE™ Cryptography Extension (JCE) API at http://java.sun.com/products/jce and provides basic support for encryption, decryption, computingdigests, verifying signatures, and accessing public keys.

MIDP: SATSA-PKI API Developer's Guide | 11

Version 1.0 | February 2nd, 2007

3 SATSA-PKI overviewThe SATSA-PKI optional package of the JSR-177 specification at http://www.jcp.org/en/jsr/detail?id=177 enables digital signatures to be used in applications, as well as basic usercredential management (for example, for certificates).

The API was first introduced in S60 3rd Edition. For S60 specific implementation details of theAPI, see SATSA API Implementation notes at http://www.forum.nokia.com/main/resources/technologies/java/documentation/Java_ME_developers_library.htm.

For devices that support SATSA API, see Forum Nokia, Devices at http://www.forum.nokia.com/devices/.

Digital signatures

Digital signatures are a cryptographically based signature assurance scheme. In the public keyinfrastructure (PKI), the public key used in the signature scheme is tied to a user by a digitalidentity certificate issued by a certificate authority. This means binding the relevant userinformation, such as name, address, phone number, etc., to a public key. The result of thescheme is digital signature.

Public-key digital signature schemes rely on public-key cryptography. In public-keycryptography, each user has a pair of keys: one public and one private. The public key isdistributed freely, but the private key is kept secret by the user; another requirement is that itshould be computationally infeasible to derive the private key from the public key.

Generally, digital signature schemes include three algorithms:

• A key generation algorithm• A signing algorithm• A verification algorithm

Example: Person A sends a message to Person B and attaches a digital signature to themessage. A has generated the digital signature by using his private key. When B receives themessage, B runs the verification algorithm on the message, using A's public key, together withthe signature to check whether the message was really sent by A.

CMS format

the Cryptographic Message Syntax (CMS) format is specified in RFC 2630 at http://www.ietf.org/rfc/rfc2630.txt with enhanced security services for RFC 2634 at http://www.ietf.org/rfc/rfc2634.txt. The syntax is used to digitally sign, digest, authenticate, or encrypt arbitrarymessages.

SATSA-PKI packages

The optional package contains two components:

• The javax.microedition.pki package

Consists of the classes UserCredentialManager andUserCredentialManagerException. Allows you to manage certificates stored on yourdevice (smart card) and provides the process for getting the appropriate keys stored on yourdevice for encryption. Enables you to generate certificate requests and to locally register usercredentials. The user credentials are used in conjunction with other parameters to computeformatted digital signatures.

When deployed on the MIDP 2.0 platform, the javax.microedition.pki package alsoincludes the interface Certificate (for providing a common interface to (X.509)certificates) and CertificateException (for errors occurring with Certificate), whichare defined in the MIDP 2.0 API.

• The javax.microedition.securityservice package

MIDP: SATSA-PKI API Developer's Guide | 12

Version 1.0 | February 2nd, 2007

Allows you to generate application-level digital signatures using certificates stored on youdevice (Certificate Store) that conform to the Cryptographic Message Syntax (CMS) format.

For more information on the javax.microedition.pki package, see also SATSADeveloper's Guide on the Java Sun Web page at http://72.5.124.55/j2me/docs/satsa-dg/pki.html.

MIDP: SATSA-PKI API Developer's Guide | 13

Version 1.0 | February 2nd, 2007

4 Using SATSA-PKIThis section describes how to use the SATSA-PKI API for:

• Creating signing requests and managing user credentials• Using signature services

4.1 Creating signing requests and managing user credentialsThe package javax.microedition.pki consists of the classesUserCredentialManager and UserCredentialManagerException.

The UserCredentialManager class provides methods for managing a user’s certificates,which the CMSMessageSignatureService can use to generate signatures. The class allowsyou to add certificates, remove certificates, and generate requests for new certificates. In thiscontext, certificates represent keys and link keys to specific people. Keys are stored on thesmart card permanently and it is not possible to add, change, or remove them.

For more information on the methods, see the class UserCredentialManager.

Creating signing requests

A Certificate Signing Request (CSR) is a message sent from an applicant to a certificateauthority with the purpose of applying for a digital identity certificate. Before you can make aCSR, you need a key pair on your device. The CSR should include the relevant informationabout you and your keys. If your CSR is successful, the certificate authority will send you backan identity certificate that has been digitally signed with the private key of the certificate authority.This certificate can be added to you certificate store and used when signing data with your keys.

You can make a Certificate Signing Request (CSR) by using the generateCSR method. TheCSR is signed on the smart card. The method takes parameters that define the details of therequest. For example, the implementation MUST use the algorithm, keyLen, andkeyUsage parameters to select a specific key to use in signing the certificate request. If thealgorithm is not supported, or specific key parameters cannot be fulfilled, aUserCredentialManagerException must be thrown. Other parameters for the methodinclude nameInfo for including a distinguished name, securityElementID for identifyingthe security element on which the key resides, and securityElementPrompt for guiding theuser to insert the correct security element.

If a security element can be selected and an appropriate key is available (already existing) thecertification request is generated and formatted. The certification request will be formatted asa PKCS#10 certificate request. Generation of the certificate enrollment request and the key pairmust be confirmed by the user.

Managing user credentials

You can add a user’s certificate path by using the addCredential method. To removecertificates from the certificate store (where all user's certificates are stored) use theremoveCredential method.

4.2 Using signature servicesThe package javax.microedition.securityservice consists of the classesCMSMessageSignatureService and CMSMessageSignatureServiceException,which provide signature services for cryptographic messages.

The class CMSMessageSignatureService provides a high-level cryptographic interface thatallows you to take use of the security elements (such as a smart card) available on a device.Here signature generation is defined for authentication and authorization purposes.

The class offers two methods for creating CMS-formatted signatures: sign andauthenticate.

MIDP: SATSA-PKI API Developer's Guide | 14

Version 1.0 | February 2nd, 2007

The sign method:

• Generates a signed CMS message• Is meant for higher-value transactions and authorizations• Is associated with keys marked for digital signature and non-repudiation (signature cannot

be taken back)

The authenticate method:

• Generates a signature that may be used for authentication purposes, that is, identifying theuser

• Meant to be used when a digital signature is required to authenticate a user• Associated with keys marked for digital signatures only, or a digital signature and a key

usage, apart from non-repudiation, (for example authentication)

When your application calls sign() or authenticate(), the SATSA implementationautomatically searches the device for appropriate signing keys (certified by the CAs). To makethe implementation look for specific keys, you can pass additional parameters to the methods.If the implementation cannot find appropriate keys, it displays a prompt to the user. In case morethan one appropriate signing key is found, the implementation interacts with the user to selectone of them.

The class CMSMessageSignatureServiceException is used for any error situations foundwhen generating signatures, for example when a certificate is not available or when certaintypes of signatures are not supported.

For more information on security elements and the methods, see the classCMSMessageSignatureService.

MIDP: SATSA-PKI API Developer's Guide | 15

Version 1.0 | February 2nd, 2007

5 Example: Creating digital signatures

This example demonstrates how to use a smart card (for example, the SIM card) to digitallysign data, it implements the PKI API in the Security and Trust Services API 1.0 defined inJSR-177.

Note: This example only shows how to digitally sign data, not to receive orauthenticate these signatures.

The application demonstrates how to:

1 Create a text field for entering the text to be signed.

A default text "ToBeSigned" is suggested when you open the application. The maximumlength of the field is 100 characters.

2 Choose an appropriate signing option from the Options list.

The options available are:

• AuthenSignByteHasContent for signing Byte data for authentication purposes includingcontent

• AuthenSignByteNoContent for signing Byte data for authentication purposes excludingcontent

• AuthenSignStringHasContent for signing String data for authentication purposesincluding content

• AuthenSignStringNoContent for signing String data for authentication purposesexcluding content

• CMSWithContent for creating a CMS formatted signature including content• CMSNoContent for creating a CMS formatted signature excluding content

3 Search for a certificate stored on the smart card of your device. Note that your PIN isautomatically asked when accessing the smart card.

4 Generate a signed data package or a signature using the certificate. When the signing isfinished, you can see a message on the screen saying "Already signed".

Figure 3: Basic user interface of PKI MIDlet

MIDP: SATSA-PKI API Developer's Guide | 16

Version 1.0 | February 2nd, 2007

5.1 PrerequisitesA smart card with proper keys is required to create the signatures in this example. The MIDletmust also be signed, since signing byte data is not allowed in an untrusted domain.

This example currently does not come with the certificate, so the user can not run it properly onthe device or SDK. For information on how to acquire a certificate, see section Security >Signed MIDlets > Recommended practises of the Java™ ME Developer's Library at http://www.forum.nokia.com/main/resources/technologies/java/documentation/Java_ME_developers_library.htm.

This MIDlet generates signatures using the CMSMessageSignatureService class. Theverification for these MIDlet-made signatures cannot be done in this same MIDlet, since thesignatures created by the CMSMessageSignatureService class are of CMS-format and theSignature-class verify() method doesn´t accept CMS-formatted signatures. Properverification of signatures should be performed, for example, through a server.

Note: Series 40 does not support the SATSA PKI package. Therefore thisexample cannot be run in Series 40.

5.2 Implementation of the PKI MIDletApplication classes:

• PKIMIDletA simple MIDlet generating signatures using the CMSMessageSignatureService class.

System classes:

• FormA Screen that contains a mixture of Items, and handles layout and user interaction focus.

• DisplayThe manager of the display and input devices of the system.

5.3 Developing the PKI MIDletThis example provides the source code to demonstrate how to digitally sign data.

Note: This tutorial provides the commented source code for the PKI MIDletexample. For a complete Eclipse project ZIP file, see S60 MIDP SDK at http://www.forum.nokia.com/main/resources/tools_and_sdks/index.html, from ThirdEdition onwards.

Note: This example only shows how to digitally sign data, not to receive orauthenticate these signatures.

To create the class:

1 Create the class PKIMIDLET.

2 Import the required classes./* Copyright © 2006 Nokia. */package com.nokia.midp.examples.security.pki;

// SATSA-PKIimport javax.microedition.pki.*;import javax.microedition.securityservice.*;

// CRYPTOimport java.security.*;import java.security.spec.*;import javax.crypto.*;

MIDP: SATSA-PKI API Developer's Guide | 17

Version 1.0 | February 2nd, 2007

import javax.crypto.spec.*;

// OTHERimport javax.microedition.midlet.*;import javax.microedition.lcdui.*;import java.io.*;import javax.microedition.io.*;

3 Set the class to extend MIDlet and implement CommandListener. Set the requiredvariables and constants. Set the variables for signed data, to be used with theauthenticate and sign methods later. Set also the constants for user prompts andcommands.

/** * This midlet is for generating signatures using CMSMessageSignatureService-class. * It demostrates how to * Verification for these midlet-made signatures is not done in this same midlet, * since CMSMessageSignatureService class-created Signatures are of CMS-format * and Signature-class verify()-method doesn´t accept CMS-formatted signatures. */

public class PKIMIDLET extends MIDlet implements CommandListener { private Form form; private Command exitCommand; private Command clearCommand; private Command authByteOpaqueCommand; private Command authByteDetachedCommand; private Command authStringOpaqueCommand; private Command authStringDetachedCommand; private Command signOpaqueCmd; private Command signDetachedCmd;

// signed data // authenticate(): private byte[] authByteOpaque = null; private byte[] authByteDetached = null; private byte[] authStringOpaque = null; private byte[] authStringDetached = null; // sign(): private byte[] signOpaque = null; private byte[] signDetached = null;

private TextField toBeSigned; private String stringToSign = "sign me"; //The constants private static final String AUTH_SIGN_BYTE_CONTENT = "AuthenSignByteHasContent"; private static final String AUTH_SIGN_BYTE_NO_CONTENT = "AuthenSignByteNoContent"; private static final String AUTH_SIGN_STRING_CONTENT = "AuthenSignStringHasContent"; private static final String AUTH_SIGN_STRING_NO_CONTENT = "AuthenSignStringNoContent"; private static final String CMS_CONTENT = "CMS_WithContent"; private static final String CMS_NO_CONTENT = "CMS_NoContent"; private static final String CLEAR = "Clear"; private static final String EXIT = "Exit"; private static final String SIGN_LABEL = "Sign"; private static final String SIGN_CONTENT = "ToBeSigned"; private static final String USER_PROMPT = "Going to sign."; private static final String AUTH_SIGN_MSG = "Sign for authentification purpose."; private static final String AUTH_SIGN_MSG_BYTE_WITH_CONTENT = "Going to sign bytes with content for: "; private static final String AUTH_SIGN_MSG_BYTE_WITHOUT_CONTENT = "Going to sign bytes without content for: "; private static final String AUTH_SIGN_MSG_STRING_WITH_CONTENT = "Going to sign string with content for: "; private static final String AUTH_SIGN_MSG_STRING_WITHOUT_CONTENT = "Going to sign string without content for: ";

MIDP: SATSA-PKI API Developer's Guide | 18

Version 1.0 | February 2nd, 2007

private static final String CMS_SIGN_MSG = "Generate a CMS signed message."; private static final String CMS_SIGN_MSG_WITH_CONTENT = "Going to sign with content for "; private static final String CMS_SIGN_MSG_WITHOUT_CONTENT = "Going to sign without content for "; private static final String AFTER_SIGN_MSG = "Already signed. The length of the signed message for the above "; private static final String AFTER_BYTE_WITH_CONTENT = "bytes with content is: "; private static final String AFTER_BYTE_WITHOUT_CONTENT = "bytes without content is: "; private static final String AFTER_STRING_WITH_CONTENT = "string with content is: "; private static final String AFTER_STRING_WITHOUT_CONTENT = "string without content is: "; private static final String AFTER_STRING = "string is: "; private static final String CANCEL = "Cancelled."; private static final String EXCEPTION = "Exception: "; private static final int AUTH_LENGTH = 128; private static final int SIGN_FILED_LENGTH = 100;

4 Create a new instance of the Form class. Implement the OK, Clear, and Exit commandsfor the user interface. Implement the text field for the user interface and set a default textto be "ToBeSigned".

public PKIMIDLET() { try { form = new Form("PKIMIDLET"); authByteOpaqueCommand = new Command(AUTH_SIGN_BYTE_CONTENT, Command.OK, 1); authByteDetachedCommand = new Command(AUTH_SIGN_BYTE_NO_CONTENT, Command.OK, 2); authStringOpaqueCommand = new Command(AUTH_SIGN_STRING_CONTENT, Command.OK, 3); authStringDetachedCommand = new Command(AUTH_SIGN_STRING_NO_CONTENT, Command.OK, 4); signOpaqueCmd = new Command(CMS_CONTENT, Command.OK, 5); signDetachedCmd = new Command(CMS_NO_CONTENT, Command.OK, 6); clearCommand = new Command(CLEAR, Command.OK, 7); exitCommand = new Command(EXIT, Command.EXIT, 8); form.addCommand(authByteOpaqueCommand); form.addCommand(authByteDetachedCommand); form.addCommand(authStringOpaqueCommand); form.addCommand(authStringDetachedCommand); form.addCommand(signOpaqueCmd); form.addCommand(signDetachedCmd); form.addCommand(clearCommand); form.addCommand(exitCommand); form.setCommandListener(this);

toBeSigned = new TextField(SIGN_LABEL, SIGN_CONTENT, SIGN_FILED_LENGTH, TextField.ANY); form.append(toBeSigned); } catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

5 Implement the startApp() method to handle the functionality of the class. This methodalso includes the signature creation for which details are implemented in the followingssteps.

public void startApp() { Display.getDisplay(this).setCurrent(form); }

public void destroyApp(boolean b) {} public void pauseApp() {}

public void commandAction (Command c, Displayable d) {

MIDP: SATSA-PKI API Developer's Guide | 19

Version 1.0 | February 2nd, 2007

if (c == exitCommand) { destroyApp(false); notifyDestroyed(); }

6 Generate a der-encoded signature including byte array content (opaque) for authenticationpurposes.

The authenticate method generates the signature according to the set parameters.byteDataToSign refers to the byte array that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE andCMSMessageSignatureService.SIG_INCLUDE_CONTENT are the signature optionsmeaning that both certificate and content are included in the signature. caNames (an arrayof strings) contains the names of trusted certification authorities. userPrompt tells theuser that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Certificates are looked foron the device and on the smart card. In practise, the keys must reside on the smart card,but the certificate may reside on the device. Note that the system clock is used fordetermining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when theerrors occur, the requested certificate is not available, or opaque signatures are notallowed.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature incl. byte array-content (opaque) // FOR AUTHENTICATION PURPOSES else if (c == authByteOpaqueCommand) { try { authByteOpaque = new byte[AUTH_LENGTH]; String[] caNames = null; // implementation provides search byte[] byteDataToSign = stringToSign.getBytes(); String userPrompt = USER_PROMPT; form.append(AUTH_SIGN_MSG); form.append(AUTH_SIGN_MSG_BYTE_WITH_CONTENT + "\"" + stringToSign + ".\""); authByteOpaque = CMSMessageSignatureService.authenticate( byteDataToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE |CMSMessageSignatureService.SIG_INCLUDE_CONTENT, caNames, userPrompt);

if(authByteOpaque != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_BYTE_WITH_CONTENT + authByteOpaque.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()==CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()==CMSMessageSignatureServiceException.CRYPTO_NO_OPAQUE_SIG){ form.append("Opaque signature is not supported."); } }

MIDP: SATSA-PKI API Developer's Guide | 20

Version 1.0 | February 2nd, 2007

catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } } catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

7 Generate a der-encoded signature without byte array content (detached).

The authenticate method generates the signature according to the set parameters.byteDataToSign refers to the byte array that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE is the signatureoption meaning that only the certificate and no content is included in the signature.caNames (an array of strings) contains the names of trusted certification authorities.userPrompt tells the user that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Note that the system clockis used for determining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when errorsoccur, the requested certificate is not available, or detached signatures are not supported.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature without byte array-content (detached) // FOR AUTHENTICATION PURPOSES else if (c == authByteDetachedCommand) { try { authByteDetached = null; byte[] byteDataToSign = stringToSign.getBytes(); String[] caNames = null; String userPrompt = USER_PROMPT; form.append(AUTH_SIGN_MSG); form.append(AUTH_SIGN_MSG_BYTE_WITHOUT_CONTENT + "\"" + stringToSign + ".\""); authByteDetached = CMSMessageSignatureService.authenticate( byteDataToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE, caNames, userPrompt); if(authByteDetached != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_BYTE_WITHOUT_CONTENT + authByteDetached.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_DETACHED_SIG){ form.append("Detached sigatures are not supported."); }

}

MIDP: SATSA-PKI API Developer's Guide | 21

Version 1.0 | February 2nd, 2007

catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } } catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

8 Generate a der-encoded signature including string content (opaque).

The authenticate method generates the signature according to the set parameters.stringToSign refers to the string that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE andCMSMessageSignatureService.SIG_INCLUDE_CONTENT are the signature optionsmeaning that both certificate and content are included in the signature. caNames (an arrayof strings) contains the names of trusted certification authorities. userPrompt tells theuser that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Note that the system clockis used for determining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when errorsoccur, the requested certificate is not available, or opaque signatures are not supported.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature incl. String content (opaque) // FOR AUTHENTICATION PURPOSES else if (c == authStringOpaqueCommand) { try { authStringOpaque = null; String[] caNames = null; String userPrompt = USER_PROMPT; form.append(AUTH_SIGN_MSG); form.append(AUTH_SIGN_MSG_STRING_WITH_CONTENT + "\"" + stringToSign + ".\""); authStringOpaque = CMSMessageSignatureService.authenticate( stringToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE |CMSMessageSignatureService.SIG_INCLUDE_CONTENT, caNames, userPrompt);

if(authStringOpaque != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_STRING_WITH_CONTENT + authStringOpaque.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_OPAQUE_SIG){ form.append("Opaque signature is not supported."); }

MIDP: SATSA-PKI API Developer's Guide | 22

Version 1.0 | February 2nd, 2007

} catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } }

catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

9 Generate a der-encoded signature without string content (detached).

The authenticate method generates the signature according to the set parameters.stringToSign refers to the byte array that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE is the signatureoption meaning that only a certificate and no content is included in the signature.caNames (an array of strings) contains the names of trusted certification authorities.userPrompt tells the user that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Note that the system clockis used for determining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when errorsoccur, the requested certificate is not available, or detached signatures are not supported.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature without String content (detached) // FOR AUTHENTICATION PURPOSES else if (c == authStringDetachedCommand) { try { authStringDetached = null; String[] caNames = null; String userPrompt = USER_PROMPT; form.append(AUTH_SIGN_MSG); form.append(AUTH_SIGN_MSG_STRING_WITHOUT_CONTENT + "\"" + stringToSign + ".\""); authStringDetached = CMSMessageSignatureService.authenticate( stringToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE, caNames, userPrompt);

if(authStringDetached != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_STRING_WITHOUT_CONTENT + authStringDetached.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_DETACHED_SIG){ form.append("Detached sigatures are not supported."); }

MIDP: SATSA-PKI API Developer's Guide | 23

Version 1.0 | February 2nd, 2007

} catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } } catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

10 Generate a der-encoded signature including content (opaque).

The sign method generates a CMS signed message according to the set parameters.stringToSign refers to the string that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE andCMSMessageSignatureService.SIG_INCLUDE_CONTENT are the signature optionsmeaning that both certificate and content are included in the signature. caNames (an arrayof strings) contains the names of trusted certification authorities. userPrompt tells theuser that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Note that the system clockis used for determining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when errorsoccur, the requested certificate is not available, or opaque signatures are not supported.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature incl. content (opaque) // FOR NON-REPUDIATION (authorization, signatures) else if (c == signOpaqueCmd) { try { signOpaque = null; String[] caNames = null; String userPrompt = USER_PROMPT; form.append(CMS_SIGN_MSG); form.append(CMS_SIGN_MSG_WITH_CONTENT + "\"" + stringToSign + ".\""); signOpaque = CMSMessageSignatureService.sign( stringToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE |CMSMessageSignatureService.SIG_INCLUDE_CONTENT, caNames, userPrompt);

if(signOpaque != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_STRING + signOpaque.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_OPAQUE_SIG){

MIDP: SATSA-PKI API Developer's Guide | 24

Version 1.0 | February 2nd, 2007

form.append("Opaque signature is not supported."); } } catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } }

catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

11 Generate a der-encoded signature without content (detached).

The sign method generates a CMS signed message according to the set parameters.stringToSign refers to the string that is to be signed.CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATEis the signatureoption meaning that only a certificate and no content is included in the signature.caNames (an array of strings) contains the names of trusted certification authorities.userPrompt tells the user that the application is going to sign the data.

The phrase String[] caNames = null; sets the parameter caNames to null. Thisallows that when the parameter is used with the authenticate method, theimplementation of the API automatically searches for certificates on the device and handlesthe interaction with the user for choosing the correct certificate. Note that the system clockis used for determining the validity of certificates.

CMSMessageSignatureServiceException is used to handle situations when errorsoccur, the requested certificate is not available, or detached signatures are not supported.

UserCredentialManagerException is used to indicate a situation when a securityelement cannot be found.

// getting der-encoded signature without content (detached) // FOR NON-REPUDIATION (authorization, signatures) else if (c == signDetachedCmd) { try { signDetached = null; String[] caNames = null; String userPrompt = USER_PROMPT; form.append(CMS_SIGN_MSG); form.append(CMS_SIGN_MSG_WITHOUT_CONTENT + "\"" + stringToSign + ".\""); signDetached = CMSMessageSignatureService.sign( stringToSign, CMSMessageSignatureService.SIG_INCLUDE_CERTIFICATE, caNames, userPrompt);

if(signDetached != null) { form.append(AFTER_SIGN_MSG); form.append(AFTER_STRING + signDetached.length); } else { form.append(CANCEL); } } catch (SecurityException se){ form.append("Too many incorrect pin entries."); } catch (CMSMessageSignatureServiceException cmsEx){ form.append("Error occured during signature generation."); if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_CERTIFICATE){ form.append("The certificate is not available."); } if(cmsEx.getReason()== CMSMessageSignatureServiceException.CRYPTO_NO_DETACHED_SIG){ form.append("Detached sigatures are not supported.");

MIDP: SATSA-PKI API Developer's Guide | 25

Version 1.0 | February 2nd, 2007

}

} catch (UserCredentialManagerException ucmEx){ if(ucmEx.getReason()== UserCredentialManagerException.SE_NOT_FOUND){ form.append("A security element is not found."); } } catch (Exception ex) { String cName = ex.getClass().getName(); form.append(EXCEPTION + cName + ": " + ex.getMessage()); } }

else if (c == clearCommand) { form.deleteAll(); toBeSigned = new TextField(SIGN_LABEL, SIGN_CONTENT, SIGN_FILED_LENGTH, TextField.ANY); form.append(toBeSigned); } }}

5.4 Building and running in an emulatorThe following package should be included in the jar:com.nokia.midp.examples.security.pki. No resource files are used.

After you have created all the necessary files for the project, you can build the project and runthe application in an emulator.

Note: The MIDlet used in this example was built using the Eclipse IDE. Pleasesee the instructions for building MIDlet projects for Eclipse that come with theGetting Started with Mobile Java section at http://www.forum.nokia.com/main/resources/technologies/java/documentation/Java_ME_developers_library.htmof the Java™ ME Developer's Library.

You can also construct them using command line or other IDEs of your choice.

5.5 Deploying to a deviceDeploy test packages onto your mobile device, using a USB cable, Bluetooth connection,infrared, or other hardware compatible connection. Alternatively, deploy the application usingOTA technology.

For instructions on how to do this, see the Getting Started with Mobile Java section at http://www.forum.nokia.com/main/resources/technologies/java/documentation/Java_ME_developers_library.htm of the Java™ ME Developer's Library.

MIDP: SATSA-PKI API Developer's Guide | 26

Version 1.0 | February 2nd, 2007