Luca
Luca

Reputation: 43

How can I write to a MIFARE Classic tag?

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);
}

Upvotes: 1

Views: 3905

Answers (1)

Michael Roland
Michael Roland

Reputation: 40849

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.

Upvotes: 1

Related Questions