Search code examples
c#smartcardmifarepcscwinscard

Select File APDU command failing with MiFare 1k card


I'm using PCSC-Sharp to transmit commands to a card. The specific command is:

00 A4 04 0C 0C D2 76 00 01 35 4B 41 4E 4D 30 31 00 00

So I did the following:

var contextFactory = ContextFactory.Instance;
using (var ctx = contextFactory.Establish(SCardScope.System)) {
    using (var isoReader = new IsoReader(ctx, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) {

        var apdu = new CommandApdu(IsoCase.Case4Short, isoReader.ActiveProtocol) {
            CLA = 0x00,
            Instruction = InstructionCode.SelectFile, //0xA4
            P1 = 0x04,
            P2 = 0x0C,
            Data = new byte[] { 0x0C, 0xD2, 0x76, 0x00, 0x01, 0x35,
                        0x4B, 0x41, 0x4E, 0x4D, 0x30, 0x31, 0x00, 0x00 },
            Le = 0x00,
        };

        var response = isoReader.Transmit(apdu);
        Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2);
    }
}

But on Transmit an InvalidApduException is thrown on getting SW1.

Am I missing something when converting the command string into a CommandApdu instance?


Solution

  • Mifare cards have no file system (just some numbered sectors) and understand no ISO 7816-4 APDUs, so InvalidApduException seems correct. The readers, which are able to handle MIFARE typically understand some pseudo-APDUs (CLA=0xFF, ...) which are translated accordingly. While these depend on the respective reader, some pretty established conventions exist, which you should find easily here using the tag.

    The SELECT by AID (for file-system based cards) or SELECT application (for Javacards) you are attempting is unlikely to have such a direct translation, since MIFARE cards have no similar concept.