Search code examples
pythonauthenticationraspberry-pirfidmifare

Changing authentication key of a sector in MIFARE Classic


According to Evan's answer in this page, in order to change the authentication key of a sector we need to overwrite the key in the 4th block (final block) of that sector.

The default key is always 'FF FF FF FF FF FF' which is a six bytes key. Now if I try to change it using the write method from the pi-rc522 library, it raises an Index Error because each block has to be 16 bytes, but the authentication key is only 6 bytes long.

Where am I going wrong?

The device is RC522 and I am using Raspbian on Raspberry Pi 3.


Solution

  • You can only write whole blocks on MIFARE Classic cards. Consequently, you need to write the complete sector trailer and not just key A (the first 6 bytes).

    The complete sector trailer looks like this:

    +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
    | KEY A                       | ACCESS BITS  | GP | KEY B                       |
    +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
    

    If you want all blocks of the sector to be readable/writable with key A only (i.e. no key B is used), you could used the access bits FF 07 80. Thus, if you want to set key A to 11 22 33 44 55 66, you could use this value for the trailer block:

    +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
    | KEY A                       | ACCESS BITS  | GP | KEY B                       |
    | 11   22   33   44   55   66 | FF   07   80 | 00 | 00   00   00   00   00   00 |
    +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
    

    Finally, be careful with what you write into the sector trailer. The access bits are protected by a redundancy mechanism. If you write invalid access bits into the trailer block, the whole sector is irreversibly blocked.