Some time ago I looked at JavaCard development, but I focused on using a PC to read data from JavaCards. Here, I want to shift my focus and talk about running my own code on a blank card. Before we dive into code, we need to understand the card’s capabilities and constraints. Then we will look at setting up a development environment and create and run a Hello World application. I won’t get into any complex applications in this posting. I just want to get a working development environment.
If you want to see the completed source code for the programs discussed here, you can find them on GitHub.
JavaCards generally have a contact interface (conversationally called a “chip”, though the actual integrated circuit is a tiny grain-sized IC under the contact) or they have an inductive loop that can be used to both wirelessly power the IC and act as an antenna for communication. They may also take the form of a USB device. For our purposes, we can treat these forms of the same thing. They are all interfaces that allow bytes to be exchanged between some host machine and the card. In this post, I will use the terms “insert” and “remove” to refer to whatever means of connecting and disconnecting to the JavaElement appropriate for the hardware that you have. I will refer to all forms of these. Communication is always driven by the host. The card cannot on its own decide to drive the host. The host sends a command and the card sends a response.
The card has memory, an operating system, and support hardware for certain functionality. It implements a subset of the Java Virtual Machine (JVM). Some aspects of the stripped-down JVM remind me of C. Some classes, such as the String class is not available. But the byte type is; someone can manipulate bytes in place of strings. Some primitive types are missing. There is no long, double, float, or char. Available are int (optionally), short, and byte. Memory is usually allocated at the initialization of an application. The objects live for the life of the application. They persist between power cycles and usage of an app, only being deallocated when the card is removed. Most cards are limited to application packages of a maximum of 54k in size.
| Card | JavaCard Version | EEPROM | Interface |
| ACOSJ95K | 3.0.4 | 95K | Dual-Interface or Contactless |
| NXP J3H145 | 3.0.4 | 144k | Dual-Interface |
| Smart Cafe 3.2 72k | 2.2.1 | 72k | Contact |
| Bodno J2A040 | 2.2.1 | 36K | Contact |
The operating system is essentially burned into the card. There is no upgrading it. While you can install and uninstall applications during development, a card can also be locked to prevent such changes. Within the card are several cryptography and security-related classes for performing encryption, signing, decryption, and signature validation. Different JavaCards may call for different versions of Java on a development machine. Thankfully, these different versions can coexist on the same machine without conflict. I found that it is helpful to set up scripts or batch files to activate the toolchain for a specific JavaCard Development Kit (JCDK).
Fused or Unfused
When buying a card, if you want maximum latitude in customizing it, you want an unfused card. Once a card is fused, its lower-level settings are permanently set. This doesn’t mean that you cannot install or uninstall apps. You can still do this (if you have the keys to the card!). For development, you want unfused cards. When distributing for production, you want to fuse the cards to further protect them.
GlobalPlatform Pro – A CLI Management Tool
Many operations on the JavaCard itself are done with a tool known as GlobalPlatform Pro (gp). This is a command-line tool available as either a JAR (Java Archive) or an EXE. The EXE is essentially a packaged form of the JAR and still depends on Java. I prefer the JAR file.You can find the download for it here: https://github.com/martinpaljak/GlobalPlatformPro/releases/tag/v25.10.20
With gp, a card, and a card reader you can start to perform some basic operations and inspections. Do not use your payment card for these command. Some of these commands will brick your card if run multiple times. If you want to invoke gp as a JAR, you will need to invoke it with the java command. I have made a batch file named gp.bat with the following contents.
@echo off
java -jar C:\shares\Java\JavaCard\gp\gp.jar %*
As long as this batch file is in a folder included in the path, it will invoke gp.jar and pass to it any arguments that had been passed to the batch file.
- List Java cards attached to system:
gp -list- List readers found in system:
gp -reader - Query capabilities of card:
gp -info
- List readers found in system:
Here is a partial output listing from an invocation of gp -info on one of my cards.
Card Data:Tag 6: 1.2.840.114283.1-> Global Platform cardTag 60: 1.2.840.114283.2.2.3-> GP Version: 2.3Tag 63: 1.2.840.114283.3-> GP card is uniquely identified by the Issuer Identification Number (IIN) and Card Image Number (CIN)Tag 6: 1.2.840.114283.4.2.85-> GP SCP02 (i=55)Tag 66: 1.3.6.1.4.1.42.2.110.1.3-> JavaCard v3Card Capabilities:Supports SCP02 i=15 i=35 i=55 i=75Supported DOM privileges: SecurityDomain, DAPVerification, DelegatedManagement, CardReset, MandatedDAPVerification, TrustedPath, TokenVerification, GlobalDelete, GlobalLock, GlobalRegistry, FinalApplication, ReceiptGeneration, CipheredLoadFileDataBlockSupported APP privileges: CardLock, CardTerminate, CardReset, CVMManagement, FinalApplication, GlobalServiceSupported LFDB hash: SHA-256Supported Token Verification ciphers: RSA1024_SHA1, RSAPSS_SHA256, CMAC_AES128, CMAC_AES192, CMAC_AES256Supported Receipt Generation ciphers: DES_MAC, CMAC_AES128Supported DAP Verification ciphers: RSA1024_SHA1, RSAPSS_SHA256, CMAC_AES128, CMAC_AES192, CMAC_AES256Version: 1 (0x01) ID: 1 (0x01) type: DES3 length: 16Version: 1 (0x01) ID: 2 (0x02) type: DES3 length: 16Version: 1 (0x01) ID: 3 (0x03) type: DES3 length: 16
The gp command will also be used to install programs to a card. In the output above is the following line.
Tag 66: 1.3.6.1.4.1.42.2.110.1.3
This line is partially interpreted by gp for you in the next line.
-> JavaCard v3
This let’s you know that the card in question is a card running JavaCard 3.x. But it doesn’t tell you which of the following that the card conforms to.
- JavaCard 3.0.1
- JavaCard 3.0.4
- JavaCard 3.0.5
- JavaCard 3.1
JavaCard Development Kit to JDK Version Mapping
You must consult the documentation for the card that you have to know which system it uses. While this is an important detail, the lack of precision in the version number generally is not a number. You will generally know what type of card you purchased or can do quick experiments to figure it out if you cannot remember. Different versions of the card OS work with different versions of the Java Development Kit.
| JCDK Version | Preferred Java Version | Notes |
| Java Card 2.2.1 | JDK 1.5 or JDK 1.4 | |
| Java Card 2.2.2 | JDK 1.6 or JDK 1.5 | Common to older bank and SIMs |
| JavaCard 3.0.1 | JDK 6 | |
| Java Card 3.0.4 | JDK 7 or JDK 6 | What I am using for this post |
| JavaCard 3.0.5 | JDK 8 or JDK 7 | |
| JavaCard 3.1 | JDK 11 | |
| Java Card 3.2 Tools | JDK 17 | |
| JavaCard 26.x Tools | JDK 25 |
Management Keys
When you get blank JavaCards, they have generally all been pre-initialized with the same value for management keys. That value is generally 404142434445464748494A4B4C4D4E4F. If you take a look at that number, you will see it is just 4 followed by the hex digits from 0 to F. While this is a common default key, it isn’t guaranteed. You must consult your documentation to know what set of keys to use. There are three types of keys relevant here.
- ENC (Encryption keys) – Makes session key, encrypts sensitive information
- MAC (Message Authentication) – Used for authenticating messages and responses
- DEK (Data Encryption Keys) – Used to encrypt sensitive data including updates
For the sake of development, the common default is convenient. The tool will assume these keys and they do not need to be specified. You will wan tto change these keys when you are using production cards. What I share here isn’t production work, we don’t need to change these. But if you find yourself needing to specify keys and and don’t wish to do so repeatedly, you could define them in environment variables and modify the gp batch file to include them.
How Do Other Applications Communicate with JavaCards
Recall the host machine always starts communication. The host will send a command to the JavaCard, then it will retrieve a response back. The host may then perform processing on that response and make another request. Every command sent to the card will have a response, even if that response is to only say that a command was successful. Communication is based in exchanging Application Data Protocol Units (APDU, See ISO 7816).
Communication can occur wirelessly or through the contacts. You usually do not need to know which method of communication is being used. Though this informaion is available (For those curious, see upper nibble of APDU.getProtocol() ). Communication also occurs over one of two protocols. The T0 protocol communicates one byte at a time. T1 communicates blocks of bytes at a time. T1 is a faster protocol. For larger amounts of data, the data may be spread across several responses. When using the T1 protocol, these responses can be automatically chained, meaning that you just keep reading and the next set of bytes for a response are supplied. With T0, you must specifically send a request to get the next set of bytes before reading them. Let’s look at the structure of commands.
APDU Commands and Requests
An APDU command can be divided into up to 8 parts.
| Label | Size (Bytes) | Description |
| CLA | 1 | APDU class |
| INS | 1 | Instruction |
| P1 | 1 | Parameter 1 |
| P2 | 1 | Parameter 2 |
| LC (optional) | 1 or 0 | |
| Data (optional) | 0 to 255 bytes | |
| LE (optional) | 0 or 1 bytes |
CLA (Command Class)
Will be 0x00 for ISO commands and 0x80 for Vendor or Application commands. You will primarily be concerned with commands prefixed with 0x80. For now, you can think of this as a constant value.
INS (Instruction)
Identifies the command being requested.
P1, P2 (Parameters)
Parameters for the command. The values that could be used here are going to depend on the instruction being sent.
LC (Length Count) + Data
Tells the length of the bytes in the data section. Not all commands will use this field as they may not have data that needs to be passed to the command. This field will generally have a value between 0x00 and 0xFF (the range that someone can express with one byte).
LE (Length of Expected Response)
If the command is one that results in a response, this field states the number of bytes that are allocated for a response. If the size specified here is insufficient, then a 2-byte error response is going to be returned from your command that starts with 0x6c (with the second byte being the bytes needed).
APDU Responses
Responses are similar to requests. The data can largely be divided into three sections.
| Field Label | Size | Description |
| Data | Varies | If there is any information that isn’t expressed through a status code, it will be provided first. |
| SW1 | 1 | Status Word 1 tells the success or failure of the operation. |
| SW2 | 1 | Gives more information on a failure, such as telling the specific class of sub error or informing how large a data structure must be to hols a response. |
Many responses will only be two bytes, with he status words being the only thing that was returned.
Common APDU commands
You’ll be able to define your own APDU commands for your application. But there are also some general commands that you will use.
Select Application
This is the most essential among the commands. A JavaCard can contain several applications. You will need to select which application you want to communicate with. You will start off your session with the card by selecting your target app.
| CLA | INS | P1 | P2 | LC | DATA | LE |
| 00 | A4 | 04 | 00 | 09 | <Varies> | 00 |
The LE value displayed above may be misleading. The byte field can range from 0x00(0) to 0xFF(255). The field can also be absent for a command. When no data is expected the field will just not be absent. The value 0x00 means 256.
Get Response Bytes
When a command is executed and has only returned some of the bytes for the response, the status code will have 0x61 followed by another byte. This other byte contains the length of the additional bytes. To retrieve these additional bytes, use the Get Response command
| CLA | INS | P1 | P2 | LC |
| 0x00 | 0xC0 | 0x00 | 0x00 | byte count |
Common Status Words
- 0x9000 – Success!
- 0x61xx – More Bytes available
- 0x6Cxx – Retry using Le = xx
- 0x6700 – Wrong Length
- 0x6A82 – Application/file not found
- 0x6A84 – Not enough memory
- 0x6D00 – INS is not implemented
How Do You Send APDU Commands?
How you send APDUs is OS or OS-dependent. For this post, I am focused on Windows. If you use another operating system, you will have to use the appropriate APIs. Windows has a low bar od entry for JavaCard communication.
- iOS – sendCommand from CoreNFC
- Android – HostApduService
- Windows – SmartCard API
- Ubuntu – open-sc
- Java – Smart Card IO Namespace (javax.smartcardio)
Let’s jump into sending some commands in Windows with our first code example.
Enumerating the Connected Readers
A computer can have multiple card readers available. I have two on the computer on which I am typing this. One reader is built into the computer. The other reader is a newer USB reader that can more reliably perform certain operations. The readers are uniquely identified by name. To get a list of the readers, we need to first get a Smart Card context, and then request a list of the readers. The following code fills a string list with the names of the readers attached to a computer.
SCARDCONTEXT hContext = { 0 };std::vector<std::wstring> readerNameList;LONG result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &hContext);if (result != SCARD_S_SUCCESS){ std::wcout << ANSIColors::Red << L"Error: Failed to establish context. Error code: " << result << ANSIColors::Reset << std::endl; return 1;}LPWSTR readerList = NULL;DWORD length = SCARD_AUTOALLOCATE;result = SCardListReadersW(hContext, nullptr, reinterpret_cast<LPWSTR>(&readerList), &length);if (SCARD_S_SUCCESS != result){ std::wcout << ANSIColors::Red << L"Error: Failed to list reader groups. Error code: " << result << ANSIColors::Reset << std::endl; SCardReleaseContext(hContext); return 1;}for(const wchar_t* name = readerList; *name != L'\0'; name += wcslen(name)+1){ readerNameList.push_back(name);}SCardFreeMemory(hContext, readerList);SCardReleaseContext(hContext);
In running this code on a few machines and with a few readers, I have found that on some computers, the card reader will not be detected if there is no card in the reader. It is as though the reader stays internally disconnected until a card is present. If your reader is not detected, try placing a card in it. Also note that Code Signing hardware tokens are often implemented using JAvaCard technology. If you have one, keep it disconnected from your computer while doing JavaCard programming.
Detecting a Card
A basic question your code might want to answer is whether or not there is a card present in the reader. You’ll have to perform some polling to track when a card is inserted or removed. This is better if done on a secondary thread. In the following code, I make a routine that will monitor the reader identified by the name passed to it. The code will wait for a card to be detected. When detected, it will call the Process() method. Then it prompts the user to remove the card to continue, and the code waits. Once the card is removed, the user is instructed to insert another card to continue.
We get the state of the reader through a call to SCardGetStatusChangeW. This function will block until something with the card reader status changes. It can block infinitely. But I have it only block for a fraction of a second. This gives the code a chance to check to see if it should stop working, such as when the user is closing the program. If the call returned because of a time out, the return value from the function will be SCARD_E_TIMEOUT. In this case the code will loop back into waiting. Since the code runs in a while loop that is conditioned on the stopRequested variable, setting stopRequested to true will cause the code to stop monitoring and return.
If some status did change for the card, the return value will be SCARD_S_SUCESS. When we get a success we are interested in whether a card is currently present, and whether there was one previously present. This lets is know if the status change is from a card being inserted or removed. If the change is from the card being inserted, then we call the ProcessCard() function. This function is, for the sake of this discussion, just a placeholder for whatever work it is that you wanted done with the card.
void Run()
{
stopRequested = false;
std::wcout << L"Starting worker for reader: " << m_readerName << std::endl;
LONG result = SCardEstablishContext(SCARD_SCOPE_USER, nullptr, nullptr, &m_hContext);
if (result != SCARD_S_SUCCESS)
{
std::wcout << ANSIColors::Red << L"Error: Failed to establish context for reader " << m_readerName << L". Error code: " << result << ANSIColors::Reset << std::endl;
return;
}
SCARD_READERSTATE readerState = {};
readerState.dwCurrentState = SCARD_STATE_UNAWARE;
readerState.szReader = m_readerName.c_str();
bool cardPresent = false;
while (!stopRequested)
{
result = SCardGetStatusChangeW(m_hContext, CARD_POLL_MS, &readerState, 1);
if (result == SCARD_E_TIMEOUT)
{
continue;
}
if (result == SCARD_E_CANCELLED)
{
PrintSCardError(result);
break;
}
if (result != SCARD_S_SUCCESS)
{
PrintSCardError(result);
}
if (result != SCARD_S_SUCCESS)
{
std::wcout << ANSIColors::Red << L"Error: Failed to get status change for reader " << m_readerName << L". Error code: " << result << ANSIColors::Reset << std::endl;
continue;
}
if (result == SCARD_S_SUCCESS)
{
if (readerState.dwEventState & SCARD_STATE_PRESENT && !cardPresent)
{
//Card was just inserted
cardPresent = true;
std::wcout << ANSIColors::Green << L"Card inserted in reader: " << m_readerName << ANSIColors::Reset << std::endl;
if (readerState.dwEventState & SCARD_STATE_MUTE)
{
cardPresent = true;
std::wcout << ANSIColors::Red << L"Card in reader " << m_readerName << L" is unresponsive." << ANSIColors::Reset << std::endl;
}
else
{
ProcessCard();
}
std::wcout << ANSIColors::Cyan << L"Card is present in reader: " << m_readerName << ". Please remove to continue." << ANSIColors::Reset << std::endl;
}
else if (!(readerState.dwEventState & SCARD_STATE_PRESENT) && cardPresent)
{
//The card was removed
cardPresent = false;
std::wcout << ANSIColors::Yellow << L"Card removed from reader: " << m_readerName << ". Insert card to continue." << ANSIColors::Reset << std::endl;
}
}
}
}
Communicating with a Card
The previous code communicated about the status of the card reader. Let’s actually communicate with the card. For the next bit of sample code, use an expired EMV card (aka Chip and PIN card, Credit card with Chip). I emphasize “Expired.” While I am going to keep this restricted to safe operations, some operations if performed on a card without authorization, can trigger built-in security features that will brick a card. Once bricked, a card will never respond to any request again.I won’t be issuing any of these risky commands. But, I am cautious. Don’t use a card that you actually need.
The safe operation that we are going to perform is simply attempting to select an application. There is a list of known application IDs for payment and transit cards. When a card is detected, this code will only try to select the application. Payment cards will generally allow unauthenticated selection of an application. For the card, will will list all the apps that we detected. For the curious, we can only check for the applications whose IDs we know. We cannot enumerate the applications present without authenticaton codes (which we don’t have).
I’ve made a class for APDUs. Both the commands and responses will be passed in these classes.
class APDU{public: APDU(byte cla, byte ins, byte p1, byte p2, std::vector<uint8_t> d, byte le = 0, bool hasLe = false); void setData(std::vector<uint8_t> data); const std::vector<uint8_t> getData(); const std::vector<uint8_t> serialize(); static APDU SelectApplication(std::vector<uint8_t> AID);private: byte m_class; byte m_instruction; byte m_p1; byte m_p2; std::optional<uint8_t> length_expected; bool has_le; std::vector<uint8_t> data;};class APDUResponse{public: APDUResponse(std::vector<uint8_t> data); const bool success(); const bool moreDataExpected(); const byte lengthExpected(); const std::vector<uint8_t> responseData(); const byte sw1(); const byte sw2(); const bool isSuccess() { return (data.size() >= 2) && (data[data.size() - 2] == 0x90); }private: std::vector<uint8_t> data;};
The serialize() method on the APDU class will assemble the byte stream that needs to be sent to the card.
const std::vector<uint8_t> APDU::serialize(){ std::vector<uint8_t> serialized; serialized.push_back(m_class); serialized.push_back(m_instruction); serialized.push_back(m_p1); serialized.push_back(m_p2); if (data.size() > 0) { serialized.push_back(static_cast<uint8_t>(data.size())); //LC serialized.insert(serialized.end(), data.begin(), data.end()); } if (length_expected.has_value()) { serialized.push_back(length_expected.value()); } return serialized;}
When we send the command, we will get a response if it is successful. The response might be incomplete if it is more than the card can communicate back in a single message. We can check whether there is more to the message by looking at the last two bytes of the response. If there is more data, then the next to last byte has the value 0x61. The last byte has a count of how many more bytes we can grab in the next request. For the function I’ve made to send a command, it will also examine the response and automatically keep resubmitting a request to get the next data block until all data is retrieved.
APDUResponse APDUTransmit(SCARDHANDLE hCard, APDU& command)
{
std::vector<uint8_t> commandData;
std::vector<uint8_t> responseBuffer;
std::vector<uint8_t> fullResponseData;
bool retry = false;
LPCSCARD_IO_REQUEST pci = (m_activeProtocol == SCARD_PROTOCOL_T0) ? SCARD_PCI_T0 : SCARD_PCI_T1;
APDU targetCommand(command);
do {
retry = false;
responseBuffer.resize(258);//Response may have up to 256 bytes, plus 2 bytes for status
DWORD responseLength = static_cast<DWORD>(responseBuffer.size());
commandData = targetCommand.serialize();
LONG result = SCardTransmit(hCard, pci, commandData.data(), static_cast<DWORD>(commandData.size()), nullptr, responseBuffer.data(), &responseLength);
if (result != SCARD_S_SUCCESS)
{
PrintSCardError(result);
return APDUResponse({});
}
responseBuffer.resize(responseLength);
auto response = APDUResponse(responseBuffer);
if (response.sw1() == 0x61 /*more data*/)
{
if(responseBuffer.size() > 2)
{
fullResponseData.insert(fullResponseData.end(), responseBuffer.begin(), responseBuffer.end() - 2);
}
targetCommand = APDU(0x00, 0xc0, 0x00, 0x00, {}, response.sw2());
continue;
}
fullResponseData.insert(fullResponseData.end(), responseBuffer.begin(), responseBuffer.end());
return APDUResponse(fullResponseData);
} while (true);
}
The command for selecting applications starts with 0x00 0xA4 0x04 0x00 followed by the application ID. I’ve made a JSON file of the various AIDs to send. In my ProcessCard() function I iterate through those AIDs and attempt to select them. The labels from the successful AIDs along with the response data will be printed to the console. For those curious, I am using ANSI control codes to color the text. You can read more about them here.
void ProcessCard()
{
std::wcout << ANSIColors::Blue << L"Processing card in reader: " << m_readerName << ANSIColors::Reset << std::endl;
auto aidList = AIDInfo::getAIDList();
SCARDHANDLE hCard;
auto result = SCardConnectW(m_hContext, m_readerName.c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T1 | SCARD_PROTOCOL_T0, &hCard, &m_activeProtocol);
for (const auto& aidInfo : aidList)
{
//std::wcout << ANSIColors::Cyan << L"Checking AID: " << aidInfo->getName() << L" (" << aidInfo->getDescription() << L")" << ANSIColors::Reset << std::endl;
auto aid = aidInfo->getAIDBytes();
auto selectCommand = APDU::SelectApplication(aid);
auto response = APDUTransmit(hCard, selectCommand);
if(response.success())
{
std::wcout << ANSIColors::Green << L"Successfully selected AID: " << aidInfo->getName() << L" (" << aidInfo->getDescription() << L")" << ANSIColors::Reset << std::endl;
std::wcout << ANSIColors::Cyan << DataToHex(response.responseData()) << ANSIColors::Reset << std::endl;;
}
}
}
Here’s an example of an item in the AID list.
{
"aid": "A0000000030000",
"vendor": "Visa International",
"country": "United States",
"name": " Global Platform CardManager (VSDC)",
"description": "",
"type": ""
}
You can find a more complete list on GitHub here.
Running Your Own Code on the Card
To run your own code, you will need a card for development and a card reader. Individual cards and packs of small quantities are available on Amazon. Though their list price tends to be more expensive there. I was purchasing a larger quantity of cards and found significantly cheaper prices from other sites. SmartCardFocus ships cards from the UK. However, at the time I ordered a batch, the USA had begun to impose tarrfifs without pre-notice. The cards did not arrive to a port of entry prior to the tariffs being implemented. I ended up paying more than a 100% tarriff on them, plus fees that FedEx charges for collecting the tarriffs. That was a couple of years ago. I mention that story now because as I write this, the USA is planning on new tarriff policies. Ordering from elsewhere may be cheaper, or it may not. Account for possible chaos.
I will keep this code simple. It should run on about any JavaCard. This will be a “Hello World” application with a counter. Before writing any code, there are a few simple decisions that we can make now. We will need to decide on an AID for our JavaPackage. From that, we will derive an AID for a program within the package. This derivative AID will be composed by using the package AID as a prefix. We will also decide on a byte value that will identify the instruction that we wish to execute. I will make two instructions. One will perform an incrementing read (Increment the value and return it in a string). Another will return an authorship string.
- Package ID:
0xA0, 0xB0, 0xC0, 0x00, 0x62, 0x03, 0x01, 0x0C - App ID:
0xA0, 0xB0, 0xC0, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x01 - Increment Read: 0x20
- Author Read: 0x7E
We will only have one instruction for adjusting the counter value. Every time the instruction is invoked, the card will return “Hello World %d” where %d will be replaced with the value of the counter. The counter will increment after being invoked. This counter is persistent. If we remove the card, reinsert it, and run the program again, we will see the number continue from where it left off.
Earlier, I mentioned that some Java primitive types are not present in the JavaCard environment. One of those primitive types is String. There is no native String type available in JavaCard. Instead, you must use arrays and buffers of bytes. This isn’t a big deal to those that have had to manage strings as arrays of characters. Note that there is also no char type. Just use bytes. Since you must manage these strings yourself, it is up to you if you want to use zero-terminated strings or maintain a length field. In either case, you must ensure you don’t have any buffer over-runs or any access attempts to invalid indices. With this declared, there are a few declarations that I can begin to make in the Java program.
package net.j2i.example;import javacard.framework.*;public class CountApp extends Applet { private static final byte INCREMENT_READ = (byte) 0x20; private static final byte AUTHOR_READ = (byte) 0x7E; private static final byte[] Greeting = {'H','e','l','l','o',' ','W','o','r','l','d',' '}; private static final byte[] Author = {'J','o','e','l',' ','I','v','o','r','y',' ','J','o','h','n','s','o','n',',','j','2','i','.','n','e','t'}; //...}
- Our class derives from
Applet. We must define a method namedprocessAdpu()and we must register our application. Support methods are available on theAppletbase that assist. To register our application, we implement a static method namedinstall. Within this method, we can create a new instance of our application. Once created, this instance of the applet will last for the entire life of the card. In the constructor for our class, callingregister()will register it as the object to receive and process messages for the selectedAID.
public static void install(byte[] bArray, short bOffset, byte bLength) {
new CountApp();
}
protected CountApp() {
register();
}
- When commands are sent to the card for our application, the
processAPDU()method is called. Within this method, if the call was for the applicaiton being selected we only need to return immediately. The methodselectingApplet()will returntrueif that is whyprocessAPDU()was invoked. If the call was not from the application being selected, then we need to process the command.
The bytes sent by the host application are available for examination be calling adpu.getBuffer(). It returns the communication buffer. Rather than remember the offsets in the buffer at which specific pieces of data live, we can use members of the ISO7816 interface. This interface includes constants for those offsets.
public interface ISO7816 { static byte OFFSET_CLA = 0; static byte OFFSET_INS = 1; static byte OFFSET_P1 = 2; static byte OFFSET_P2 = 3; static byte OFFSET_LC = 4; static byte OFFSET_CDATA = 5;}
You will also find common JavaCard error codes and other useful constants within that interface.
We will use a switch statement on the instruction that we get with a default path that throws an exception. The other two instructions, the incrementing read and the instruction to show author, are primarily copying strings back to the buffer to send to the host. They use a utility function to copy those bytes. The incrementing read does some additional steps. It appends the current value of the count to the buffer and then increments the count. The card then calls apdu.setOutgoingAndSend to send the new values in the card back to the host.
public void process(APDU apdu) { if (selectingApplet()) { return; } byte[] buffer = apdu.getBuffer(); short len; switch (buffer[ISO7816.OFFSET_INS]) { case INCREMENT_READ: len = Util.arrayCopyNonAtomic(Greeting, (short) 0, buffer, (short) 0, (short) Greeting.length); len = appendShort(currentCount, buffer, len); currentCount++; apdu.setOutgoingAndSend((short) 0, len); break; case AUTHOR_READ: len = Util.arrayCopyNonAtomic(Author, (short) 0, buffer, (short) 0, (short) Author.length); apdu.setOutgoingAndSend((short) 0, len); break; default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); } }
The conversion of the number to a string must be done manually. There is no toString() method to call (as there are no intrinsic string types!). It takes a reference to a buffer, an offset into that buffer at which it should begin writing, and the number to write. Since this is only working with short values, at most the number will be 6 characters (including the sign).
private static short appendShort(short num, byte[] buf, short off) {
if (num < 0) {
buf[off++] = (byte) '-';
num = (short) -num;
}
// Count digits
short len = (short) 1;
for (short t = num; t <= (short) -10; t = (short) (t / 10)) {
len++;
}
short end = (short) (off + len);
short p = end;
do {
buf[--p] = (byte) ('0' - (num % 10)); // num % 10 is <= 0
num = (short) (num / 10);
} while (num != 0);
return end;
}
On the host side, I will extend the code sample that I used for the EMV cards. Most of what I need to do is already present in that program. I just need to attempt to select the AID and, if successful, send my custom commands and print the response.
void ProcessCustomApp(SCARDHANDLE hCard)
{
const std::vector<uint8_t> aidHex = { 0xA0, 0xB0, 0xC0, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x01 };
auto selectCommand = APDU::SelectApplication(aidHex);
auto response = APDUTransmit(hCard, selectCommand);
if (response.success())
{
std::wcout << ANSIColors::Green << L"Successfully selected custom AID." << ANSIColors::Reset << std::endl;
std::wcout << ANSIColors::Cyan << DataToHex(response.responseData()) << ANSIColors::Reset << std::endl;
auto parsedData = BerTlvParser::parse(response.responseData());
for (const auto& node : parsedData) {
PrintNode(node);
}
std::vector<APDU> targetCommandList = {
APDU(0x00, 0x20, 0x00, 0x00,{}, 0), //Increment Read
APDU(0x00, 0x7e, 0x00, 0x00,{}, 0) //Get Author
};
for (APDU a : targetCommandList)
{
while (true)
{
auto response = APDUTransmit(hCard, a); // Read Record command)
if (response.sw1() == 0x6c) {
a.setLE(response.sw2());
continue;
}
std::wcout << DataToHex(response.responseData()) << std::endl;
std::wcout << DataToString(response.responseData()) << std::endl;
break;
}
}
}
else
{
std::wcout << ANSIColors::Red << L"Failed to select custom AID." << ANSIColors::Reset << std::endl;
PrintAdpuError((response.sw1() << 8) | response.sw2());
}
}
Installing the Applet
I use two different terminal windows for compilation and installation of the Applet to the card. For the cards that I have, I need one Java version. For gp, I need a different Java version. The exact Java version that you need is going to depend on your card’s OS. See the earlier chart. I have several JDKs installed on my machine and batch files defined so that I can set my environment with a single command from the command prompt.
Compilation occurs in two steps. The first command compiles the code as one might compile any other Java source file. The second command invokes a JavaCard Development Kit command to convert the class code to the byte code format needed for the JavaCard.
javac -g -d .\ -classpath ".;%JC_HOME_TOOLS%\lib\api_classic.jar" CountApp.java converter -classdir c:\shares\Java\JavaCard\temp ^ -exportpath %JC_HOME_TOOLS%\api_export_files ^ -out CAP -applet 0xA0:0xB0:0xC0:0x00:0x62:0x03:0x01:0x0C:0x01 ^ net.j2i.example.CountApp net.j2i.example ^ 0xA0:0xB0:0xC0:0x00:0x62:0x03:0x01:0x0C 1.0
Installation of the app to the card is done with the gp command.
gp -install .\net\j2i\example\javacard\example.cap
After this completes, you can run the test program on the windows machine again and insert/remove the card several times to see the number increasing.
Closing
I’ve covered a lot to get us to the equivalent of a “Hello World” for a card running. There is much more to cover, such as performing transactions with the card so that it is in a good state even if disconnected in the middle of an operation, performing encryption, and validation. We also need to discuss keeping the keys secured so that someone doesn’t start manipulating the card in a way that interferes with what you are trying to protect.
Posts may contain products with affiliate links. When you make purchases using these links, we receive a small commission at no extra cost to you. Thank you for your support.
Mastodon: @j2inet@masto.ai
Instagram: @j2inet
Facebook: @j2inet
YouTube: @j2inet
Telegram: j2inet
Bluesky: @j2i.net




































