Search code examples
androidnfcmifare

How to Construct a value block on MifareClassic via Android NFC API


My question is that the Android NFC API has already provided "increment" and "decrement" a value block , but if I have a new MifareClassic Tag(it's not have any value block inside), how can i use the Android NFC API to construct a value block on this new tag ?


Solution

  • You should just write properly formatted data to the tag. See section 8.6.2 of the MIFARE Classic datasheet for an example.

    Example Android code to store an integer value as value block in block blockIndex:

    // connect to the tag using a Tag object from an NFC intent
    MifareClassic mifare = MifareClassic.get(tag);
    mifare.connect();
    
    // need to authenticate first to get access
    int sector = blockToSector(blockIndex);
    mifare.authenticateSectorWithKeyA(sector, keyA); // you need to know key A
    // mifare.authenticateSectorWithKeyB(sector, keyB); // in case you know key B
    
    // construct value block of value zero; "address" byte is set to 0 in this example
    byte[] zeroValue = {0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 0, 255 };
    mifare.writeBlock(blockIndex, zeroValue);
    
    // increase the value block by some amount
    mifare.increment(blockIndex, value);
    // result is stored in scratch register inside tag; now write result to block
    mifare.transfer(blockIndex);
    

    Keep in mind that the access control bits for the block need to be set correctly to allow the increment operation for the key you use to authenticate.