Yalantis: iOS, Android And Web App Development Company

NFC in Android & Payment Cards

Near Field Communication technology is capable of bringing devices together and establishing a wireless radio connection, which makes data stream from one device into the other like magic. The only disappointment is that you can’t enforce NFC to push loads of stuff from, say, your laptop to anything else looking like it has NFC inside.

The maximum bit rate hardly reaches 424 kbit/s, which is lower, than Bluetooth. Among the strengths of NFC, we can distinguish its maximum working distance of no more than 2 centimeters. Why strength? Such proximity between NFC empowered devices minimizes unwanted interception likelihood and cares about the privacy of the data.


In case you want to find out the wonders of NFC environment spouted out of your hands, you will have to investigate the tag and the reader. So why don’t you grab your Android device and a payment card and let’s take a look at those things!

NFC Tags

To start with there is a huge variety of tags that differ from one another depending on a type of the chip used. However, they are all set according to one general pattern. Each tag has a chip that contains data, an antenna, and a sticker to hold them both. A tag is a passive device that doesn’t have a source of power. So what does the chip take the power from? While operating the reader is emitting electromagnetic waves and as soon as a tag gets into its field of action there emerges electric current which feeds the chip and enables communication.


What does the distance needed for such interaction to happen depend on?  First of all it depends on the number of windings on the tag’s antenna, simply put - the more the better. Moreover, the power of the electromagnetic field of the reader has something to add to its ability to reach far horizons. A long range reader will obviously consume more energy. That’s why the readers shoved into our phones have very little action radius. After all we need to save the battery, right?

Types of NFC chips

We can go into a long multi-page enumeration of all the chips existing on the planet and enlist all the differences between them. But let’s skip that and focus on the main essential point.

There is a standard for NFC tags introduced by an organization called NFC Forum. Some of the tags correspond to this standard, some don’t. For example, Mifare is one of the most popular trademarks owned by NXP Semiconductors, whose name covers a series of chips widely used in contactless smart cards and proximity cards. Produced by this provider tags are used for public transportation systems all over the world. These tags do not correspond to the standard of NFC Forum and use their own protocol. And here is an interesting fact. Before the Nexus 4 came out, the majority of the phones had NFC chip from the same provider that produces Mifare tags causing no troubles when interacting. But it all has changed since the Nexus 4 was pushed to the market.

Instead of NXP chips, Google, and other mobile providers started using Broadcom chips which created some sort of nuisance as these phones are incompatible with Mifare tags. If you try to communicate this tag with your Nexus 4, the only info you will be able to pull out is going to be the tag’s ID and its type with no chance to record/read the tag. This is one of the issues Android has to think of if it aims at developing NFC-friendly technology.

NFC + Android


NFC technology offers lots of possibilities for Android developers and many ideas for apps creation. So what can you actually do with NFC in Android?

  • Record/read tags
  • Transfer the data via Android Beam (P2P connection). Android Beam is essentially a software that uses NFC to enable, pair and establish Bluetooth connection to transfer the files
  • Use tag emulation (Host-Based Card Emulation) and reader emulation with Android 4.4. version. In fact, Android would let the emulation function even before the version 4.4. was introduced to the market, but in those times you would need some sort of a secure element (a sim card usually) to store the data, whereas a telephone performed a function of an antenna. What we have now is a software realization of emulation in Android phones that lets a user connect to a server to get the protected information in a secure and handy way.

Mifare Classic Public transportation cards

In order to get the insight of how NFC works with contactless cards, why don’t we rip up a Mifare Classic card used in public transportation.

This card has the following structure for storing the data: all the card memory is divided into 16 sectors, each sector falls into 4 blocks. We can apply 2 types of keys (A, B) to access the data in each of the sectors. Each key can be assigned an individual right to read or record. For example, A can only read the data and B can only record them.

This means that before performing any action with a sector, a reader should be logged in to one of the keys. The keys are kept in each sector separately and the job of the card is to check whether the key passed via the reader coincides with the one for a definite sector it wants to read the data from. Metro cards, for example, use A key only.

The data on the card are encrypted following a proprietary algorithm Crypto 1 created by NXP Semiconductors. This algorithm has long been hacked and there are tools that can pick the right key within a short time. However, each card has a unique ID kept in "0" sector together with the service information, which you cannot change.


Let’s read this card:

    public void onCreate(Bundle savedInstanceState) {

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    protected void onResume() {
        Intent nfcIntent = new Intent(this, MyActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pi = PendingIntent.getActivity(this, 0, nfcIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        nfcAdapter.enableForegroundDispatch(this, pi, new IntentFilter[]{tagDetected}, null);

    protected void onNewIntent(Intent intent) {
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            MifareClassic mifare = MifareClassic.get(tagFromIntent);
            try {
                int sectorIndex = 0;
                int blockToRead = mifare.sectorToBlock(sectorIndex);
                mifare.authenticateSectorWithKeyA(sectorIndex, MifareClassic.KEY_DEFAULT);
                mifare.authenticateSectorWithKeyB(sectorIndex, MifareClassic.KEY_DEFAULT);

                byte[] block = mifare.readBlock(blockToRead);
                StringBuilder hexString = new StringBuilder();
                for (byte aBlock : block) {
                    String hex = Integer.toHexString(0xFF & aBlock);
                    if (hex.length() == 1) {
                        // could use a for loop, but we're only dealing with a single byte
                Log.e("Block 0: ", hexString.toString());
            } catch (IOException e) {
                Log.e(TAG, "IOException while writing Mifare message...", e);
            } finally {
                if (mifare != null) {
                    try {
                    } catch (IOException e) {
                        Log.e(TAG, "Error closing tag...", e);

   Security Audit

First of all I should point out that Mifare Classic card has a headline that includes the information about the index number of the operation with the card, the number of the trips left, the date and time of the last operation, the number of the terminal that executed the operation, the number of the entry in the terminal register. The history of the last 6 trips are located to the address 0xC0, 0xD0, 0xE0, 0x100, 0x110, 0x120. Now let’s try to figure out the security issues when trying to use the data on the card.

Number of trips. Hackable or non hackable?

In fact, you may record the number of trips remained and cheat the turnstile by adding more trips to your card data storage. But it won’t work, sorry. The metro security system won’t let you do it. The thing is that all the turnstiles and recharge terminals are connected to the server station. All the server stations are synchronized with the central server which keeps track of the trips of all the cards and checks if there was a mismatch. For example, the server base has 0 trips remained but the turnstile says there are 10. In this case the card ID is getting banned.

Can you use your phone as a travel pass?

If you truly believe that it’s possible to emulate the Metro card with our telephone, I am sorry to disappoint you.The type of the tags that can be emulated in Android phone are only those corresponding to the definite standard. Mifare doesn’t correspond to this standard so we can’t use our phone as a travel pass. Again sorry, but keep reading, we still have cool stuff there. 

Cards made in China

They do wonders in China! There is a Chinese copy of Mifare Classic card, whose 0 sector with all the service information can be recorded. This way we can clone the Metro card. What will it give us? There are travel passes without a limit in the number of trips, whose cloned analogue is hard to detect even if the system has an algorithm to ban those cards.

Mifare Plus S

db_photo1385532507 (1)

Mifare Classic has been changed to Mifare Plus S, which has the same structure of memory and is compatible with Classic. The difference between them is that Plus S supports AES encryption. Here is more on Mifare Plus S:

  • Simple fixed memory structure compatible with MIFARE Classic 1K and MIFARE Classic 4K
  • Memory structure identical to MIFARE Classic 4K (sectors, blocks)
  • Supports ISO/IEC 14443 Type A UIDs (4-byte UID, 4 Byte NUID, 7-byte UID)
  • AES encryption
  • Keys can be stored as MIFARE CRYPTO1 keys (2 × 48-bit per sector) and as AES keys (2 × 128-bit per sector)

Even though Mifare Plus S emulates Classic for now so as not to remodel the entire infrastructure, the new standard is bound to hit the road pretty soon!

Contactless payment cards

These cards are different animals. They use an absolutely different chip - JavaCard. In other words this is a chip with an operation system, which means that we can write apps using a special Java version for it. There can be many apps for one chip. All the chips of contactless payment cards conform to one international EMV standard, which describes the protocol of interaction with the card. EMV (Europay, MasterCard and VISA) standard is used with the bank cards that have a chip. It was developed by mutual cooperation of Europay, MasterCard and Visa to improve the security of the financial transactions. The main difference of a card with EMV standard is that they claim PIN entry when perform any payment through the terminal (for example, in shops, restaurants). However, it is not a must. The interesting thing is that pin code is not required when you perform sales operations with this type of a card and the necessity to enter it can only depend on the Issuing Bank policy.


What can we read from this card without any difficulty?

I didn’t have much time to check all the data through my own code that’s why I tested that with other apps and got the following information: the type of a payment system, the country, the number, the date of issue, the expiration date, the last and first name of the card owner. So it’s basically everything they put on the front of your card. Is it enough to do the payment? I am afraid not.

However, all the data listed above are recorded on the magnetic stripe of the card, which means that once you read them, there is a possibility to clone the card, without the chip surely. In case you do that, remember that you will have to find out the pin code too. But it isn’t a problem for those familiar with skimming.

There is a danger of having to deal with a wireless skimming. Such a device can be stuck to an ATM and swipe your precious card data. I can’t really tell whether the banks are going to fight with this felony. By the way, you can easily find shielded wallets or a cheaper option - envelopes for cards on eBay. While the card is inside it can’t be read.

Can we emulate a payment card with a phone?

Yep! I have a feeling that Google added Host Based Card emulation to Android 4.4. for this particular reason, so that the users could push their payments via Google Wallet.

This is how the emulation of a card is done:

                <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>


<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
        <aid-filter android:name="F0010203040506"/>
        <aid-filter android:name="F0394148148100"/>
        <aid-filter android:name="63646300000000323231"/>

public class MyHostApduService extends HostApduService {
    public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) {
        String n1 = "Hi there this is working";
        return n1.getBytes();

    public void onDeactivated(int reason) {
        Log.e("NFC_Test", "onDeactivated");

Keep in mind that you can’t just take any tag and emulate it. Only those tags corresponding to are capable to enable this operation.

That’s pretty much it for now. Have fun with Android and NFC!

Read also:

How We Developed the Guillotine Menu Animation for Android

The Dark Side of Android App Widgets

Our FlipViewPager Animation on Android

See what else we can do

Check out our knowledge and capabilities

Let's talk code