Skip to content
Advertisement

How to read data from a sector using NFC on Android

I am trying to read the data from an NFC card I have for a project. It is using Mifare classic 1k and has 16 sectors.

I am able to connect to the card and I’m trying to read the data (I know the data that I want is in the 2nd sector – 2nd Block). I can scan the card fine and it shows me the size of the card so this ensures me that the card is being scanned properly but the data I get when I Log the “data.readBlock(2)” is just the same as the key I use to authenticate it.

What I understand from the code: Card connects Auth == true I can get overall details of the card such as sector count / block count

protected void onNewIntent(Intent intent){
            super.onNewIntent(intent);
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            MifareClassic tag = MifareClassic.get(tagFromIntent) ;
            try {
                //Variables
                int sectorCount = tag.getSectorCount();
                int tagSize = tag.getSize();
                boolean auth;
                //Keys
                byte[] defaultKeys = new byte[]{};
                defaultKeys = MifareClassic.KEY_DEFAULT;
                //Connecting to tag
                tag.connect();
                //auth = true
                auth = tag.authenticateSectorWithKeyA(2, defaultKeys);
                byte[] data = tag.readBlock(2);
                Log.i("OnNewIntent", "Data in sector 2: " + Arrays.toString(data));
            } catch (IOException e) {
                e.printStackTrace();
            }

Expected = “Data in sector 2: The data in sector 2 block 2

Actual = “Data in sector 2: [B@4df9e32”

The above Actual result changes each time the card is scanned.

Advertisement

Answer

What you are getting is the object reference Java uses to keep it in memory. To get a readable version of the data instead use:

Arrays.toString(data);

By the way, you may want to change your code to check if the authentication was successful:

authSuccessful = mfc.authenticateSectorWithKeyA(sector, key);

if(authSuccessful){
    // Read the block
    creditBlock = mfc.readBlock(block);

    String bytesString = Arrays.toString(creditBlock);
    Log.i(TAG, bytesString);

} else {
    Log.e(TAG, "Auth Failed");
}

Finally, I’m pretty sure what you are trying to do is just the standard Mifare card read so avoid jumping to conclusions. As they say in medicine:

Think horses, not zebras

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement