1

How can I write to a MIFARE Classic tag?

I have written this code, but writeBlock results in the error "java.io.IOException: transceive failed".

How can this be solved?

MifareClassic mfc = MifareClassic.get(mytag);
boolean auth = false;
mfc.connect();
auth = mfc.authenticateSectorWithKeyA(1,MifareClassic.KEY_DEFAULT);
if (auth) {
    String text = "Hello, World!";
    byte[] value  = text.getBytes();
    byte[] toWrite = new byte[MifareClassic.BLOCK_SIZE];        

    for (int i=0; i<MifareClassic.BLOCK_SIZE; i++) {
        if (i < value.length) toWrite[i] = value[i];
        else toWrite[i] = 0;
    }           

    mfc.writeBlock(2, toWrite);
}
Michael Roland
  • 39,663
  • 10
  • 99
  • 206
Luca
  • 43
  • 1
  • 7

1 Answers1

1

First of all, you are authenticating to the wrong sector. Here, you authenticate to sector 1 with key A:

auth = mfc.authenticateSectorWithKeyA(1, MifareClassic.KEY_DEFAULT);

As you get past the if (auth), I assume that authentication with KEY_DEFAULTas key A for sector 1 is successful.

But then, you are trying to write to block 2, which is in sector 0:

mfc.writeBlock(2, toWrite);

As you are authenticated to sector 1, writing to sector 0 will fail. You can only write to blocks in the sector that you last authenticated to. For sector 1, this would be blocks 4 to 7. Note that you run into the same problem if you authenticate to sector 2 and try to write block 4 (which is in sector 1).

If I read the comments below your post correctly, you also tried to authenticate to sector 1 and access block 4 resulting in the same error. If that was the case, the access conditions of sector 1 prohibit write operations for key A.

Michael Roland
  • 39,663
  • 10
  • 99
  • 206
  • thank you, now I have modify auth = mfc.authenticateSectorWithKeyA(2,MifareClassic.KEY_DEFAULT); and mfc.writeBlock(8, toWrite); the dialog that I have written the tag appear. But if I read the tag, this is empty. The phone that I use is "Samsung Mini 2" – Luca Apr 16 '14 at 13:54
  • The tag is not written. after mfc.writeBlock(8, toWrite); I have insert an "Alert dialog" that appear. But the tag is not write. Is still empty – Luca Apr 17 '14 at 07:10
  • @Luca you already wrote that. This inofmration is not helpful. Please describe (step-by-step) how you verify that there is not data on the tag. – Michael Roland Apr 17 '14 at 19:00
  • I'm sorry. I have download NFC Tag Info, and verify the data of card, and it is empty. Also tap to my smartphone, the text not appear – Luca Apr 18 '14 at 07:30
  • The text (if you write it to the card that way) won't just "magically" appear when you tap the tag to your phone. However, NFC TagInfo will read the correct value (i.e. the one that's actually on the card) if it has read access. What output does NFC TagInfo give you for block 8 (sector 2/block 0), block 11 (sector 2/block 3) and what access conditions does it list for sector 2? – Michael Roland Apr 18 '14 at 09:47