NFC Tag's sector doesn't work anymore after writing with Node.js module nfc-pcsc

Viewed 161

I am making a couple of experiments using the Node.js module nfc-pcsc, and I have no clue how this creates problems. In the following code, when the card is placed on the reader, the program writes "a", "b", "c" and "d" in the first four available sectors. After it's finished, it prints out "data written" (regardless of whether that really worked or not) and then it prints out the value of arr2, in which the program stores the number of the sectors in which it wrote the data:

const { NFC, TAG_ISO_14443_3, TAG_ISO_14443_4, KEY_TYPE_A, KEY_TYPE_B } = require('nfc-pcsc');
const nfc = new NFC();

nfc.on('reader', async reader => {
    reader.on('card', async card => {
        const arr = ['a', 'b', 'c', 'd'];
        const arr2 = [];
        let len = arr.length;
        for (let i = 4, j = 0; i < 64 && j < len; i++) {
            try {
                let data = Buffer.allocUnsafe(16).fill(0);
                data.write(arr[j]);

                await reader.authenticate(i, KEY_TYPE_B, 'ffffffffffff');
                await reader.write(i, data, 16);

                j++;
                arr2.push(i);
            } catch { }
        }
        console.log('data written');
        console.log(arr2);
    });

    reader.on('error', err => {
        console.log(err);
    });
    reader.on('end', () => {
        //
    });
});

nfc.on('error', err => {
    console.log(err);
});

So after it's finished I wanna check the results. I try to run the following code, which iterates through all of the sectors, reads their data and prints it out:

        ...
        for (let i = 4; i < 64; i++) {
            try {
                await reader.authenticate(i, KEY_TYPE_B, 'ffffffffffff');
                let data = (await reader.read(i, 16, 16)).toString();

                console.log(`Sector ${i}: ${data}`);
            } catch { }
        }
        ...

And the result? The sectors numbers that were previously stored in the arr2 variable don't appear anymore: they fail the authentication.
I have tried, however, using another code to write to only one sector, here it is:

        ...
        try {
            let data = Buffer.allocUnsafe(16).fill(0);
            data.write('a');

            await reader.authenticate(28, KEY_TYPE_B, 'ffffffffffff');
            await reader.write(28, data, 16);

            console.log('data written');
        } catch (err) {
            console.log(err);
        }
        ...

And when running the same code as before to check the results, it now worked and the sector has stayed intact. How is this possible? And also, is there any way I can recover those sectors which seem they disappeared?

0 Answers
Related