Search code examples
androidkotlinformatnfcmifare

What is the best way to clear MifareClassic sector on Android?


Is there better way to clear a sector on a MIFARE Classic card than to write it with all zeros?

Here is an example of my current code:

for (i in 0 until sectorCount) {
    if (!authenticateSectorWithKeyA(i, key) && !authenticateSectorWithKeyA(i, MifareClassic.KEY_DEFAULT)) {
        break
    }

    val idx = sectorToBlock(i)

    for (j in 0 until getBlockCountInSector(i)) {
        val index = idx + j
        when (index) {
            0 -> cardId = getCardId(readBlock(idx + j))
            1 -> {} //Todo: Write specail data
            4 -> {} //Todo: Write specail data
            5 -> {} //Todo: Write specail data
            else -> {
                if ((index + 1) % 4 != 0) {
                    writeBlock(index, ByteArray(16).apply { fill(0.toByte()) })
                }
            }
        }
    }
}

Solution

  • Clearing the sector by filling all data blocks with zeros is perfectly fine. There is no other way to erase data on MIFARE Classic cards.

    Just make sure that you don't overwrite the sector trailer (last block in every sector) with zeros since that would lead to invalid access bits (which would in turn render the sector permanently inaccessible). I assume that's what you try to achieve with

    if ((index + 1) % 4 != 0)
    

    but be aware that e.g. MIFARE Classic 4K has larger sectors where the trailer isn't the 4th data block of the sector.