Cryptographic algorithm for EMV Software

Typically, cryptographic algorithms use keys to encrypt and decrypt data. The key can be imagined as a kind of secret value, similar to a password or PIN code of a bank card. In fact, the key is just a sequence of numbers. The key is a parameter of the mathematical formula of the cipher. Therefore, if you encrypt the same plaintext using different keys, you will get different cipherograms. The opposite is also true: you can get the original unencrypted text from the ciphertext only if you use the correct key. Using the key whose in ciphers allows you to distribute and publish cryptographic algorithms without the risk of losing secrecy. The confidentiality of encrypted information is ensured by using a secret key.
There are two main types of key-based ciphers: symmetric and asymmetric. In symmetric encryption algorithms, the encryption key can be determined by the value of the decryption key and vice versa. In most cases, these keys are the same, i.e. the same key is used to encrypt and decrypt data.
The most common symmetric ciphers are DES and DESede. DES, or Data Encryption Standard, is a data encryption standard that has been used worldwide for about 30 years. The DES standard provides for the encryption of 64-bit data blocks using a 64-bit key, in which the-

The decoding process according to the DESede standard

the thickets are 56 bits. The total key length is 8 bytes. The same key is used for encryption and decryption.
The DESede standard is better known as the triple DES cipher (3-DES). It provides for a chain of three alternating encryption and decryption operations
When decrypting according to the DESede standard, the order of operations is reversed, i.e. the process follows the “decryption–encryption–decryption” scheme.
Instead of the 8-byte key used in the DES standard, three keys are used in the DESede encryption process. This allows you to significantly increase the reliability of the cipher. There are several variants of the DESede standard, which differ in the choice of keys. In the first variant, three different DES keys are used. In another variant, a double-length key is used, while in the DESede encryption algorithm, keys 1 and 3 are identical. If all three keys are the same, the reliability of DESede encryption is the same as in the case of DES.

When using symmetric ciphers, it is necessary that all participants in the exchange of information securely store and transmit to each other a single secret key. If the key has become available to someone else, the entire encryption system can be disclosed.
To eliminate the disadvantages of symmetric algorithms, asymmetric ciphers were developed. These ciphers use two different keys: the public key, which is freely distributed, and the secret key, which must be stored in such a way as to prevent it from falling into the wrong hands.
As shown in Figure 10.4, a public key is used to encrypt a message, which can be accessible to everyone, but only an authorized person with the corresponding secret key can decrypt such a message. In many asymmetric encryption algorithms, the reverse process also works. This means that the message can be encrypted with a secret key and decrypted using a public key.

Asymmetric encryption and decryption algorithm

The RSA asymmetric encryption algorithm is named after its inventors: Ronald Raivest, Adi Shamir and Leonard Adleman. This is the most well-known and flexible asymmetric encryption algorithm of all that are currently in use.
But of course, nothing is given for free. The implementation of asymmetric algorithms requires much more complex calculations compared to symmetric ones, so they are usually not used to encrypt long messages. Many security protocols use a combination of symmetric and asymmetric ciphers. As an example, the SSL (Secure Socket Layer) secure connection protocol, which is supported by most web browsers, can be cited. Before starting SSL communication, all participants exchange certain data in order to agree on a session cryptographic key. Before the exchange, this data is encrypted using an asymmetric algorithm. Usually the amount of such data is small. The session key is used by a symmetric algorithm to encrypt and decrypt basic information messages. As the name of the key implies, its validity period is limited to one communication session. After the end of the connection, the key becomes invalid. To start a new session, all participants must exchange session keys again. Cryptography technology (which can use both symmetric and asymmetric ciphers) translates data into a secret format. Only authorized persons with special computing resources can decode this data. When used correctly, encryption ensures the confidentiality of information. To ensure data integrity and authentication of communication participants, along with encryption, the creation of message digests is used.

Message Digest

The message digest is calculated using secure one-way hash functions, which, according to arbitrary length data, generate a hash value that has a constant length. Hash functions are designed like this,
so that this value can be easily calculated, but the reverse calculation would be difficult. In addition, hash functions are designed in such a way
as to reduce the probability of generating the same function values for two different data streams.

Calculating the message digest

Due to these properties, the message digest is an important mechanism that allows you to ensure data integrity. Usually the sender sends a message digest along with the data. The recipient calculates the hash function value from the received data and compares it with the message digest sent. Any discrepancy indicates that the data was subjected to any influences during transmission, or that an error occurred during transmission.

Currently, two popular hash functions are widely used: MD5 and SHA-1. The MD5 algorithm was published by Ronald Rywest in 1990-1991 . It is based on an earlier algorithm, MD4. Both of these algorithms generate a 128-bit hash function value. The authentication and information integrity verification algorithm, SHA (Secure Hash Algorithm), generates a 160-bit digest. It was first published by the US National Institute of Standards and Technology in 1992. After some weaknesses were discovered in this algorithm, an improved algorithm known as SHA-1 was developed. Today, the terms SHA and SHA-1 are often used to refer to the same algorithm.
The message digest can be used to verify data integrity. However, if the hash function is known in advance, anyone can calculate its value for any data. In this case, the digest will be vulnerable to malicious attacks. The detractor can intercept the data and digest, replace the data and calculate the hash function value from the new data. The recipient will not be able to determine that the data has been changed.
To eliminate such situations, a one-way hash function based on a key was developed. The hash function value is generated not only based on the input data, but also based on the key. This scheme is called the message authentication code, or abbreviated MAC (message authentication code). Usually, the MAC value is calculated from data that is encrypted with a symmetric cipher using a specific key. To
verify the MAC’s identity, the key must be known to both the sender and the recipient.

Digital signature

The digital signature is calculated by encrypting the message digest with an asymmetric cipher. The digital signature allows you to identify the sender of the message, as well as the integrity of the data.
The sender calculates the message digest from the source data and signs it using encryption with its own secret key. An encrypted digest of a message is called a digital signature.

Digital signature verification

The sender sends the data and digital signature to the recipient. The recipient verifies the signature. To do this, he first decrypts it using the sender’s public key. After decryption, the message digest becomes available to him. Then the recipient calculates the hash function value from the received data and compares the two message digests. If both values are equal, the recipient makes sure that the data was received from a specific sender, as well as that they were not changed during transmission.

Random data

In cryptography, the value of random numbers is very high. They are usually added to the input data to ensure the uniqueness of the session during the authentication process. Random numbers are also used to generate reliable cryptographic keys. The reliability of these cryptographic procedures depends on the generation of random numbers whose values cannot be predicted.
A truly random number does not depend on any external conditions, such as temperature or supply voltage. Some computers use a hardware-based random number generator. To obtain a random number, the phenomena of instability of electrical circuits, radioactive decay, as well as other random physical processes independent of external conditions are used. But such solutions are not always available in practice. Therefore, software algorithms are mainly used in computers.

Using Cryptography in Smart Card Applications

Such algorithms allow you to generate pseudo-random numbers, which are usually well suited for most areas of use. Deterministic algorithms are used in pseudorandom number generators. Before starting the generator, it must be initialized, i.e. set the initial number. Usually, some random value is taken as the initial number
, for example, the current time. If the generation algorithm and the initial value are known, random numbers become predictable. Therefore, such numbers are called pseudorandom.

Without going into details, we can name two main directions of using cryptography in smart card applications:
· Ensuring application protection and secure data exchange between the card and the host application.
· The use of smart cards as a secure means of identification for access to other systems.

Ensuring application security

Let’s imagine the applet “electronic wallet”, which is designed for electronic payments. The first problem faced by developers-
chiki of protected applets, – authentication. For example, you need to confirm the credentials of the seller who receives the money. It is equally important to determine that the money received on the balance of the “electronic wallet” is received from a legitimate source. Mutual authentication is often required. Cryptographic authentication mechanisms can be used by both smart card applets and host applications. This is necessary in order to verify the competence of both participants in the communication session.
Secondly, it is necessary to ensure the protection of confidential data. For example, when conducting a debit or credit transaction, the information exchanged between the applet and the host application may contain the amount of money, the bank account number, the password for accessing the account, as well as other secret data.
To ensure confidentiality, before transmitting data over communication channels, they must be encrypted, and after receiving decrypted. Sometimes the data on the card should be stored in encrypted form to protect against attempts to “hack” the card.

Thirdly, it is equally important to ensure data integrity. If money
is transferred from a bank account to an “electronic wallet”, an attacker can intercept this operation and transfer half of the amount to his account (if he does not appropriate all your money, consider yourself lucky). In order to prevent such situations, when exchanging commands today, after the actual data, an authentication code calculated for the Mac is placed in the Russian Federation, as shown

Using smart cards as a secure means of identification

Smart cards are ideal for use as a means of confirming authorization, as well as as encryption modules when working as part of centralized systems, such as cell phones, television set-top boxes, as well as in various network environments. When working in such systems, cryptography is used to implement functional requirements. For example, an authentication application may contain some secret information (a cryptographic key) that is used in conjunction with a network server. When the cardholder wants to access network resources, the server generates a request, which is a sequence of random numbers, and sends this data to the card in plain text. Then the application that runs on the card encrypts the received request and sends the cipher message to the server. The server decrypts this data and compares it with the request that was generated earlier. If the data matches, the server grants the cardholder access to the network. This authentication scheme is known as “request-response”. To resist malicious attacks, algorithms that are more reliable than the simple examples described in this section are used to implement such schemes.


When developing a security strategy, it is important to evaluate the available computing resources of the card. In general, it can be said that the implementation of resource-intensive cryptographic mechanisms for working with large amounts of data in smartcards is not possible. In addition, it is important to understand that an applet using cryptography by itself does not provide any guarantee of protection. In addition to evaluating the correctness of the use of cryptographic functions, the security of the applet should be evaluated in the context of the overall security of the system infrastructure. The infrastructure of the system is the card and the host device, and in a broader sense, the entire network to which these devices are connected. Therefore, when developing an applet, many factors that relate to the system as a whole should be taken into account. Only after a thorough analysis can a decision be made, firstly, on the feasibility of using cryptography in this application, and secondly, about which cryptographic mechanisms are best suited in this situation.
Readers who are interested in the use of cryptography in smart cards can recommend books: and Guthery Jurgensen “smart card Developer kit”, and the soluble forms of a vigorous “Smart Card Reference Book” as well as Hendry “Smart Card security and applications”. In these publications, the topic of cryptography is presented in sufficient detail.

Java card

The cryptographic programming interfaces of the Java Card platform (hereinafter, for brevity, we will call them cryptographic APIs) in the Java Card 2.1 version have undergone significant changes to ensure compliance with the requirements of US export regulations and provide many extensible and flexible functionality.
The model of the Java cryptographic architecture (JCA, Java cryptography architecture) became a model for the development of cryptographic APIs of the Java Card platform[11]. The goal of this development was to ensure the best compatibility with the Java platform.

Principles of development

Cryptographic APIs are built on the following principles:
· API independence from a specific implementation and compatibility of different implementations.
· Independence and extensibility of algorithms.
Implementation independence and algorithm independence complement each other. It was necessary to provide users with programming interfaces for the use of cryptographic services, such as digital signature and message digest. At the same time, users should not delve not only into the details of the implementation, but even into the algorithms that underlie these services. Due to the compatibility of implementations, applets using cryptographic APIs can work on all variants of the Java Card platform that provide correct encryption support.
The extensibility of algorithms allows you to simply add additional cryptographic algorithms to the API and delete existing algorithms. Such changes require only minor API changes. API backward compatibility is also guaranteed.


The architecture of cryptographic APIs is designed taking into account the following mechanisms:
· Separation of the interface from the implementation.
· Active use of factory methods.

· Standardization of names of supported cryptographic algorithms.
· Definition of lightweight APIs.
The cryptographic programming interfaces of the Java card (most of which are implemented as abstract classes and interfaces) define the types of cryptographic services and the interface for accessing these services. The JCRE provider extends the API base classes to provide implementation of specific cryptographic services or implementation of an interface to provide symmetric or asymmetric encryption. For example, for an implementation hash function using the MD5 algorithm and the JCRE provider MessageDigestMD5 can create a class that is an extension of the MessageDigest class available in the API. The methods of the MessageDigestMD5 class override the methods of the base class and provide an implementation of the MD5 hashing algorithm.
If the applet does not know the name of the implementation class and its location, factory methods are used to access the object providing cryptographic services. So, to request the creation of a message digest using the MD5 algorithm, you can write something like this code:

MessageDigest md5;
md5 = MessageDigest.getInstance(MessageDigest.ALG_MD5, false);

Usually the object returned by the factory method is a descendant of the class you are requesting. In the example above, an instance of the MessageDigestMD5 class can be returned. However, when developing your programs, you may not take this into account. You can treat this object as a message digest and work with the interface methods of the base class. This is how the applet’s independence from a specific implementation is achieved.

To support factory methods, it is necessary to follow the naming convention that the applet can use to specify both the algorithm and the parameters used by this algorithm. This naming convention operates through the selection parameters. The selection parameters are the necessary constants that define the standard name for each cryptographic algorithm, as well as for each type of cryptographic keys and key lengths. In the above example of a request to create a message digest, the constant MessageDigest.ALG_MD5 is a selection parameter that defines the MD5 algorithm.

The selection options also provide a flexible way to add new encryption algorithms and additional services. As new cryptographic algorithms are developed, their support can be easily added. To do this, it is enough to include them in the implementation and add their names to the list of algorithm selection parameters. A specific JCRE implementation will support the new algorithms and provide their implementations. Only new constants are added to the API, so only minor version changes are needed to support additional algorithms. At the same time, backward compatibility of new API implementations with previous versions is maintained.

By separating the interface from the implementation, cryptographic APIs can provide an extensible set of cryptographic services, despite the small size of the code. Depending on the amount of smart card memory, a specific JCRE implementation may support all possible algorithms, some subset of them, or not support encryption at all. However, this imposes certain requirements on you as an applet developer. You should know the types of cryptographic services that support the cards for which you are writing applets. If the requested cryptographic algorithm or service is not available for this card, JCRE throws a CryptoException.

Package Structure

The cryptographic APIs of the Java Card platform are divided into two packages: and javacardx.crypto. This separation corresponds to the cryptographic architecture of JCA (Java Cryptography Architecture) and displays differences in the functional purpose of cryptographic mechanisms. Some of them do not fall under the restrictions of export control, while others implement strong encryption algorithms.
The package includes various interfaces for implementing symmetric and asymmetric keys, a class for creating keys, authentication classes that implement message digest and digital signature, as well as classes for generating random data. A summary of the interfaces and classes of the package is given in Table 10.1.

The javacardx.crypto package is an extension package. It includes the cipher class, which implements strong encryption algorithms, as well as the KeyEncryption interface for accessing data encryption keys. Classes that are included in the javacardx.crypto package are subject to export control restrictions.

This section provides code examples that illustrate the generation of a message digest, the creation of cryptographic keys, the creation and verification of a digital signature, the encryption and decryption of data in applets, as well as the use of the RandomData class to generate random data.

Calculating the message digest

The message digest is a unique and reliable feature that allows the recipient of the message to determine that it has not undergone any changes during the forwarding process.
The digest calculation begins with the creation of a message digest object. To do this, call the getInstance factory method of the MessageDigest class.

public static MessageDigest
getInstance(byte algorithm, boolean externalAccess)

The algorithm parameter determines the required algorithm using one of the algorithm selection parameters. The Java Card 2.1 API supports three possible algorithms: SHA1, MD5 and RIPE MD-160. These algorithms correspond to the selection parameters ALG_SHA, ALG_MD5 and ALG_RIPEMD160.
The second parameter, externalAccess, was introduced specifically for the Java Card environment. After the message digest object is created, it becomes available to the currently active applet and all the applets that are defined in the same package. An applet from another package can access the message digest object using the sharing interface method. If the value of the externalAccess parameter is set to false (this means that the created message digest object is not intended for external access), then only applets that run in its own context will have access to the digest object in the text, and only if one of them is the current active applet1.
If an applet needs to use an instance of a message digest object for several communication sessions with a reader, it should not call the getInstance method at the moment when it needs this object. Instead, you need to provide for the creation of an instance of the message digest object in the applet constructor and store it in a permanent area of the applet (for example, in the instance field) so that this object is available during the next communication session. This technique avoids potential memory leaks if there is no “garbage collector” in the virtual machine of the card. Let’s consider an example of the code for calculating the digest using the SHA algorithm.
public class MyApp extends Applet { private MessageDigest sha; public MyApplet() {
sha = MessageDigest.getInstance(MessageDigest.ALG_SHA, false);


Suppose you have three byte arrays, m1, m2 and m3, forming a message whose digest you want to receive. The digest can be calculated using the following calls:

// we pass to the digest object all data from the m1 sha.update array(m1, (short)0, (short)(m1.length));
// we pass 8 bytes from the m2 byte array, starting
// from offset 0
sha.update(m2, (short)0, (short)8);
// finally, we pass all the data from the m3 array to the digest object
// and store the hash function value in the digest byte array, starting
// from offset 0
sha.doFinal(m3, (short)0, (short)(m3.length), digest, (short)0);

The update method allows you to sequentially transmit the next portions of data to calculate the digest. But to transfer the last portion of data, you need to use the doFinal method. This is how we inform the digest object about

1 For readers who are interested in this topic, let’s explain in more detail: when the externalAccess parameter is set to false, message digest implementations can use applet resources, for example, temporary arrays of the CLEAR_ON_DESELECT type. Only applets that are executed in its own context have access to an array of type CLEAR_ON_DESELECT, and only if one of them is the currently active applet. We discussed the scopes of temporary. By default, the externalAccess parameter takes the value false. This allows the message digest implementation to optimize RAM usage by placing objects in the area reserved for arrays of the CLEAR_ON_DESELECT type.

that we are transmitting the last portion of data to him. After that, the system performs the final actions, for example, supplements the message to the desired size. The doFinal method returns the calculated value of the hash function in the specified output array. In our example, the hash function value is written to the beginning of the digest byte array. The doFinal method provides for the possibility of writing output data to the place of input data, so you can, for example, use the m3 byte array to get the hash function value.

sha.doFinal(m3, (short)0, (short)(m3.length), m3, (short)0);

After the completion of the doFinal method, the message digest object automatically returns to its original state. It can be used to calculate new values.
If all the source data is in a single byte array, the update method does not need to be called. You should immediately use the doFinal method. To store intermediate calculation results, the update method uses temporary memory, so it needs to be called only if the source data for calculating the digest cannot be placed in a single byte array.


Due to the fact that the update method requires additional resources and may reduce performance, it is recommended to use only the doFinal method if possible.

In the process of calculating the hash function value (before calling the doFinal method), you can call the reset method to cancel all previous calculations and return the digest object to its original state. After that, it can be used to calculate new values.
The MessageDigest class also defines two methods by which the applet can make certain requests to the message digest object. The getAlgorithm method returns a value corresponding to the code of a specific algorithm that is used in the implementation of this instance of the object. The getLength method returns the length in bytes of the hash function value calculated using this algorithm.