Ady Wicaksono Daily Activities

Archive for the ‘Java Programming’ Category

Display Text using javacard on SIM card

with 13 comments

TS 31.111 define USIM Application Toolkit for SIMCard, one feature defined there
is proactive command. What’s is proactive command? Proactive command is
a mechanism whereby the UICC/SIM Card can initiate actions to be taken by the ME
(mobile equipment). These actions include:

– displaying text from the UICC to the ME;
– sending a short message;
– setting up a voice call to a number held by the UICC;
– setting up a data call to a number and bearer capabilities held by the UICC;
– sending a SS control or USSD string;
– playing tone in earpiece;
– initiating a dialogue with the user;
– USIM initialization request and notification of changes to EF(s);
– providing local information from the ME to the UICC;
– providing information about the additional card reader(s) (if class “a” is supported);
– managing timers running physically in the ME;
– running an AT command received from the UICC, and returning the result to the UICC
(if class “b” is supported);
– sending DTMF;
– requesting the ME to launch the browser corresponding to a URL. (if class “c” is supported);
– establishing and managing a bearer independent protocol (if class “e” is supported).

OK, I will start sharing some javacard application that do a display text proactive command
it will be our helloworld smartcard application :). Details of proactive command for
displaying text is defined like this:

This command instructs the ME to display a text message, and/or an icon. It allows the UICC to
define the priority of that message, and the text string format.

Two types of priority are defined:
– display normal priority text and/or icon on screen;
– display high priority text and/or icon on screen.

The text string can be in one of three formats:
– packed format in SMS default alphabet
– unpacked format in SMS default alphabet
– UCS2 alphabet format

NOTE: The text string may contain up to 240 bytes.

TLV (Type Length Value) format of Display Text is defined like this:

display-text-proactive-command.png

So how to implement it? Here it is:

package proactive_cmd;

/*
 * Imported packages
 */
import sim.toolkit.*;
import sim.access.*;
import javacard.framework.*;

public class display_text extends javacard.framework.Applet implements
		ToolkitInterface, ToolkitConstants {
	// Mandatory variables
	private SIMView gsmFile;
	private ToolkitRegistry reg;

	// Main Menu
	private byte idMenu1;
	private byte[] Menu1;

	/**
	 * Constructor of the applet
	 */
	public display_text() {
		// Get the GSM application reference
		gsmFile = SIMSystem.getTheSIMView();

		// Get the reference of the applet ToolkitRegistry object
		reg = ToolkitRegistry.getEntry();

		Menu1 = new byte[] {
				(byte) 'D', (byte) 'i', (byte) 's', (byte) 'p',
				(byte) 'l', (byte) 'a', (byte) 'y', (byte) ' ',
				(byte) 'T', (byte) 'e', (byte) 'x', (byte) 't' };
		// Define the applet Menu Entry
		idMenu1 = reg.initMenuEntry(Menu1, (short) 0, (short) Menu1.length,
				PRO_CMD_SELECT_ITEM, false, (byte) 0, (short) 0);
	}

	/**
	 * Method called by the JCRE at the installation of the applet
	 * @param bArray the byte array containing the AID bytes
	 * @param bOffset the start of AID bytes in bArray
	 * @param bLength the length of the AID bytes in bArray
	 */
	public static void install(byte[] bArray, short bOffset, byte bLength) {
		// Create the Java SIM toolkit applet
		display_text StkCommandsExampleApplet = new display_text();
		// Register this applet
		StkCommandsExampleApplet.register(bArray, (short) (bOffset + 1),
				(byte) bArray[bOffset]);
	}

	/**
	 * Method called by the SIM Toolkit Framework
	 * @param event the byte representation of the event triggered
	 */
	public void processToolkit(byte event) {
		EnvelopeHandler envHdlr = EnvelopeHandler.getTheHandler();

		// Manage the request following the MENU SELECTION event type
		if (event == EVENT_MENU_SELECTION) {
			// Get the selected item
			byte selectedItemId = envHdlr.getItemIdentifier();

			// Perform the required service following the Menu1 selected item
			if (selectedItemId == idMenu1) {
				menu1Action();
			}
		}
	}

	/**
	 * Method called by the JCRE, once selected
	 * @param apdu the incoming APDU object
	 */
	public void process(APDU apdu) {
		// ignore the applet select command dispached to the process
		if (selectingApplet()) {
			return;
		}
	}

	/**
	 * Manage the Menu1 selection
	 */
	private void menu1Action() {
		// Get the received envelope
		ProactiveHandler proHdlr = ProactiveHandler.getTheHandler();

		// Display the "Menu1" message text
		// Initialize the display text command
		proHdlr.initDisplayText((byte) 0x00, DCS_8_BIT_DATA, Menu1, (short) 0,
					(short) (Menu1.length));
		proHdlr.send();
		return;
	}
}

The bold font is the code to display text using proactive command. The result on my Nokia 3660 is like this:

display-text-proactive-command.jpg

If we try to trace the APDU, it will be like this

D0 18 81 03 01 21 00 82 02 81 02 8D 0D 04 44 69 73 70 6C 61 79 20 54 65 78 74

Details:

0xD0: this is proactive command tag
0x18 : length of these bytes “81 03 01 21 00 82 02 81 02 8D 0D 04 44 69 73 70 6C 61 79 20 54 65 78 74” which is 24 bytes
0x81: Command details tag, see picture below

command-details.png

0x03: length of value of command details tag “01 21 00”
0x01: command number
0x21 0x00: Display text (normal priority, clear message after a delay)
0x82: Device identities tag, see below

device-identities.png

0x02: Length of device identities values which is “81 02”
0x81: means source is UICC or SIMCard
0x02: means destination is display which is on mobile phone
0x8D: Text string tag, see picture below

text-string-tag.png

0x0D: length of text string tag value, which is “04 44 69 73 70 6C 61 79 20 54 65 78 74”
0x04: DCS or data coding scheme (defined in TS 23.038)
44 69 73 70 6C 61 79 20 54 65 78 74: hex representation of string “Display text”, use hex2string tools to convert from string to hex vice versa

Uh.. complicated.. yes telco stuff is complicated, that’s why it’s expensive hehehehe

Advertisements

Written by adywicaksono

February 9, 2008 at 3:20 pm

SSL Connection with Java

with one comment

Here is an example Java code to create SSL connection between you and HTTPS
(taken from http://www.cafeaulait.org/slides/iw2000/whatsnew/04.html)

import java.net.*;
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class HTTPSClient {
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println("Usage: java HTTPSClient host");
			return;
		}

		int port = 443; // default https port
		String host = args[0];

		try{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

			Writer out = new OutputStreamWriter(socket.getOutputStream());
			// https requires the full URL in the GET line
			out.write("GET / HTTP/1.0\\r\\\n");
			out.write("\\r\\n");
			out.flush();

			// read response
			BufferedReader in = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
			int c;
			while ((c = in.read()) != -1) {
				System.out.write(c);
			}

			out.close();
			in.close();
			socket.close();
		}catch (IOException e) {
			System.err.println(e);
		}
	}
}

You can compile & run it:

$ javac HTTPSClient.java
$ java HTTPSClient login.yahoo.com

But wait, if HTTPS server give you certificate which is signed by “unknown” Certificate Authority ( I mean not signed by approved CA like Thawte, Verisign) then you will get this error

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

or something like it

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found

However, I found the fast solutions (I forget where was it, but I started from Google)
so all certificates (signed and unsigned) become accepted and the exception disappears.
Of course this is not recommended for a production system but quite useful for testing :).

import java.net.*;
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class HTTPSClient {
	public static void main(String[] args) {
		if (args.length == 0) {
		   System.out.println("Usage: java HTTPSClient host");
		   return;
		}

		int port = 443; // default https port
		String host = args[0];

		
		TrustManager[] trustAll = new javax.net.ssl.TrustManager[]{
		  new javax.net.ssl.X509TrustManager(){
			  public java.security.cert.X509Certificate[] getAcceptedIssuers(){
				return null;
			  }
			  public void checkClientTrusted(java.security.cert.X509Certificate[] certs,String authType){}
			  public void checkServerTrusted(java.security.cert.X509Certificate[] certs,String authType){}
		  }
		};
		
		try {
		
			javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
			sc.init(null, trustAll, new java.security.SecureRandom());
		
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			SSLSocketFactory factory = (SSLSocketFactory) sc.getSocketFactory();
			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

			Writer out = new OutputStreamWriter(socket.getOutputStream());
			out.write("GET / HTTP/1.0\\r\\n");
			out.write("\\r\\n");
			out.flush();

			// read response
			BufferedReader in = new BufferedReader(
			new InputStreamReader(socket.getInputStream()));
			int c;
			while ((c = in.read()) != -1) {
				System.out.write(c);
			}
			out.close();
			in.close();
			socket.close();
		}catch (Exception e) {
			System.err.println(e);
		}
	}
}

Written by adywicaksono

July 15, 2007 at 4:20 pm