Ejemplo n.º 1
0
        protected ResponseApdu SendAPDU(CommandApdu apdu, SCardReader reader)
        {
            var receivePci = new SCardPCI(); // IO returned protocol control information.
            var sendPci = SCardPCI.GetPci(reader.ActiveProtocol);

            var receiveBuffer = new byte[256];
            var command = apdu.ToArray();

            SCardError sc = reader.Transmit(
                sendPci,            // Protocol Control Information (T0, T1 or Raw)
                command,            // command APDU
                receivePci,         // returning Protocol Control Information
                ref receiveBuffer); // data buffer

            if (sc != SCardError.Success)
            {
                // todo
                return null;
            }

            return new ResponseApdu(receiveBuffer, IsoCase.Case2Short, reader.ActiveProtocol);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Will try to connect to _connectedReader and read the card.
        /// </summary>
        /// <returns>Either the data from the card or the error message. Or if 'uidOnly' is true, just the UID prefixed with 'UID^' and ending with '^'</returns>
        public string ReadCard(bool uidOnly = false)
        {
            SCardContext context = new SCardContext();
            context.Establish(SCardScope.System);
            SCardReader reader = new SCardReader(context);

            SCardError result = reader.Connect(_connectedReader, SCardShareMode.Shared, SCardProtocol.Any);

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("No card is detected (or reader reserved by another application){0}{1}",
                    Environment.NewLine, SCardHelper.StringifyError(result));
            }

            string[] readerNames; SCardProtocol protocol; SCardState state; byte[] atr;
            result = reader.Status(out readerNames, out state, out protocol, out atr);

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Unable to read from card.{0}{1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            string message = string.Format("Card detected:{0}Protocol: {1}{0}State: {2}{0}ATR: {3}{0}",
                Environment.NewLine, protocol, state, BitConverter.ToString(atr ?? new byte[0]));

            CommandApdu apdu = new CommandApdu(IsoCase.Case2Short, reader.ActiveProtocol)
            {
                CLA = 0xFF,
                Instruction = InstructionCode.GetData,
                P1 = 0x00,
                P2 = 0x00,
                Le = 0
            };

            result = reader.BeginTransaction();

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Cannot start transaction.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            SCardPCI recievePci = new SCardPCI();
            IntPtr sendPci = SCardPCI.GetPci(reader.ActiveProtocol);

            byte[] recieveBuffer = new byte[256];

            result = reader.Transmit(sendPci, apdu.ToArray(), recievePci, ref recieveBuffer);

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Cannot transmit data.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            var responseApdu = new ResponseApdu(recieveBuffer, IsoCase.Case2Short, reader.ActiveProtocol);

            message += string.Format("SW1: {1}{0}SW2: {2}{0}", Environment.NewLine, responseApdu.SW1, responseApdu.SW2);

            string data = responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "--";

            if (uidOnly)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("UID^{0}^", data);
            }

            message += string.Format("UID: {0}",data);

            reader.EndTransaction(SCardReaderDisposition.Leave);
            reader.Disconnect(SCardReaderDisposition.Reset);

            context.Dispose();
            reader.Dispose();
            return message;
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Retrieves the UID of a card that is currently connected to the given
        ///     reader.
        /// </summary>
        /// <param name="readername"></param>
        /// <exception cref="Exception">Could not begin transaction.</exception>
        private byte[] UidFromConnectedCard( string readername )
        {
            SCardReader rfidReader = new SCardReader( Context );
            SCardError resultCode = rfidReader.Connect( readername, SCardShareMode.Shared, SCardProtocol.Any );

            if( resultCode != SCardError.Success ) {
                throw new Exception( "Unable to connect to RFID card / chip. Error: " + SCardHelper.StringifyError( resultCode ) );
            }

            // prepare APDU
            byte[] payload = new byte[] {
                0xFF, // the instruction class
                0xCA, // the instruction code
                0x00, // parameter to the instruction
                0x00, // parameter to the instruction
                0x00 // size of I/O transfer
            };
            byte[] receiveBuffer = new byte[10];

            resultCode = rfidReader.BeginTransaction();
            if( resultCode != SCardError.Success ) {
                throw new Exception( "Could not begin transaction." );
            }

            SCardPCI ioreq = new SCardPCI();

            IntPtr protocolControlInformation = SCardPCI.GetPci( rfidReader.ActiveProtocol );
            resultCode = rfidReader.Transmit( protocolControlInformation, payload, ioreq, ref receiveBuffer );

            if( resultCode != SCardError.Success ) {
                Log.Error( SCardHelper.StringifyError( resultCode ) );
                receiveBuffer = null;
            }

            rfidReader.EndTransaction( SCardReaderDisposition.Leave );
            rfidReader.Disconnect( SCardReaderDisposition.Reset );

            return receiveBuffer;
        }
Ejemplo n.º 4
0
        public static void Main() {
            using (var context = new SCardContext()) {
                context.Establish(SCardScope.System);

                var readerNames = context.GetReaders();
                if (readerNames == null || readerNames.Length < 1) {
                    Console.WriteLine("You need at least one reader in order to run this example.");
                    Console.ReadKey();
                    return;
                }

                var readerName = ChooseRfidReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var rfidReader = new SCardReader(context)) {

                    var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                    if (sc != SCardError.Success) {
                        Console.WriteLine("Could not connect to reader {0}:\n{1}",
                            readerName,
                            SCardHelper.StringifyError(sc));
                        Console.ReadKey();
                        return;
                    }
                    
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol) {
                        CLA = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1 = 0x00,
                        P2 = 0x00,
                        Le = 0  // We don't know the ID tag size
                    };

                    sc = rfidReader.BeginTransaction();
                    if (sc != SCardError.Success) {
                        Console.WriteLine("Could not begin transaction.");
                        Console.ReadKey();
                        return;
                    }

                    Console.WriteLine("Retrieving the UID .... ");

                    var receivePci = new SCardPCI(); // IO returned protocol control information.
                    var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol);

                    var receiveBuffer = new byte[256];
                    var command = apdu.ToArray();

                    sc = rfidReader.Transmit(
                        sendPci,            // Protocol Control Information (T0, T1 or Raw)
                        command,            // command APDU
                        receivePci,         // returning Protocol Control Information
                        ref receiveBuffer); // data buffer

                    if (sc != SCardError.Success) {
                        Console.WriteLine("Error: " + SCardHelper.StringifyError(sc));
                    }

                    var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
                    Console.Write("SW1: {0:X2}, SW2: {1:X2}\nUid: {2}", 
                        responseApdu.SW1, 
                        responseApdu.SW2, 
                        responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received");

                    rfidReader.EndTransaction(SCardReaderDisposition.Leave);
                    rfidReader.Disconnect(SCardReaderDisposition.Reset);

                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            try
            {
            SCardContext hContext = new SCardContext();
            hContext.Establish(SCardScope.System);

            var szReaders = hContext.GetReaders();

            if (szReaders.Length <= 0)
                throw new PCSCException(SCardError.NoReadersAvailable,
                    "Could not find any Smartcard reader.");

                Console.WriteLine("reader name: " + szReaders[1]);

                // Create a reader object using the existing context
                SCardReader reader = new SCardReader(hContext);

                // Connect to the card
                SCardError err = reader.Connect(szReaders[1],
                    SCardShareMode.Shared,
                    SCardProtocol.T0 | SCardProtocol.T1);
                CheckErr(err);

                IntPtr pioSendPci;
                switch (reader.ActiveProtocol)
                {
                    case SCardProtocol.T0:
                        pioSendPci = SCardPCI.T0;
                        break;
                    case SCardProtocol.T1:
                        pioSendPci = SCardPCI.T1;
                        break;
                    default:
                        throw new PCSCException(SCardError.ProtocolMismatch,
                            "Protocol not supported: "
                            + reader.ActiveProtocol.ToString());
                }

                byte[] pbRecvBuffer = new byte[256];

                // Send SELECT command
                // Select command 0x00, 0xA4, 0x04, 0x00,
                //Length  0x08
                //AID A0A1A2A3A4000301
                byte[] cmd1 = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x08, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0x00, 0x03, 0x01 };
                err = reader.Transmit(pioSendPci, cmd1, ref pbRecvBuffer);
                CheckErr(err);

                //(6A82: The application to be selected could not be found.)

                Console.Write("Select response: ");
                for (int i = 0; i < pbRecvBuffer.Length; i++)
                    Console.Write("{0:X2} ", pbRecvBuffer[i]);
                Console.WriteLine();

                pbRecvBuffer = new byte[256];

                // Send test command
                byte[] cmd2 = new byte[] { 0x00, 0x00, 0x00, 0x00 };
                err = reader.Transmit(pioSendPci, cmd2, ref pbRecvBuffer);
                CheckErr(err);

                Console.Write("Test commad response: ");
                for (int i = 0; i < pbRecvBuffer.Length; i++)
                    Console.Write("{0:X2} ", pbRecvBuffer[i]);
                Console.WriteLine();

                hContext.Release();
                
            }
            catch (PCSCException ex)
            {
                Console.WriteLine("Ouch: "
                    + ex.Message
                    + " (" + ex.SCardError.ToString() + ")");
            }
             Console.ReadLine();
        }
Ejemplo n.º 6
0
        public byte[] SendBytes(byte[] inBytes, SCardReader reader, SCardError err, SCardContext context)
        {
            try
            {
                //SCardReader reader = new SCardReader(context);
                //// Connect to the card
                //Console.WriteLine(readerName);
                //SCardError err = reader.Connect(readerName,
                //    SCardShareMode.Shared,
                //    SCardProtocol.T0 | SCardProtocol.T1);

                IntPtr pioSendPci;
                switch (reader.ActiveProtocol)
                {
                    case SCardProtocol.T0:
                        pioSendPci = SCardPCI.T0;
                        break;
                    case SCardProtocol.T1:
                        pioSendPci = SCardPCI.T1;
                        break;
                    default:
                        throw new PCSCException(SCardError.ProtocolMismatch,
                            "Protocol not supported: "
                            + reader.ActiveProtocol.ToString());
                }
                
                byte[] pbRecvBuffer = new byte[256];
                err = reader.Transmit(pioSendPci, inBytes, ref pbRecvBuffer);
                return pbRecvBuffer;
            }
            catch (PCSCException)
            {
                return null;
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            SCardContext ctx = new SCardContext();
            ctx.Establish(SCardScope.System);

            string[] readernames = ctx.GetReaders();
            if (readernames == null || readernames.Length < 1)
                throw new Exception("You need at least one reader in order to run this example.");

            // Show available readers.
            Console.WriteLine("Available readers: ");
            for (int i = 0; i < readernames.Length; i++)
                Console.WriteLine("[" + i + "] " + readernames[i]);

            int num = 0;

            if (readernames.Length > 1)
            {
                // Ask the user which one to choose.
                Console.Write("Which reader is an RFID reader? ");
                string relin = Console.ReadLine();
                if (!(int.TryParse(relin, out num))
                    || num < 0
                    || num > readernames.Length)
                {
                    Console.WriteLine("An invalid number has been entered. Exiting.");
                    return;
                }
            }

            string readername = readernames[num];

            SCardReader RFIDReader = new SCardReader(ctx);
            SCardError rc = RFIDReader.Connect(
                readername,
                SCardShareMode.Shared,
                SCardProtocol.Any);

            if (rc != SCardError.Success)
            {
                Console.WriteLine("Unable to connect to RFID card / chip. Error: " +
                    SCardHelper.StringifyError(rc));
                return;
            }

            // prepare APDU
            byte[] ucByteSend = new byte[] 
            {
                0xFF,   // the instruction class
                0xCA,   // the instruction code 
                0x00,   // parameter to the instruction
                0x00,   // parameter to the instruction
                0x00    // size of I/O transfer
            };
            byte[] ucByteReceive = new byte[10];

            Console.Out.WriteLine("Retrieving the UID .... ");

            rc = RFIDReader.BeginTransaction();
            if (rc != SCardError.Success)
                throw new Exception("Could not begin transaction.");

            SCardPCI ioreq = new SCardPCI();    /* creates an empty object (null).
                                                 * IO returned protocol control information.
                                                 */
            IntPtr sendPci = SCardPCI.GetPci(RFIDReader.ActiveProtocol);
            rc = RFIDReader.Transmit(
                sendPci,    /* Protocol control information, T0, T1 and Raw
                             * are global defined protocol header structures.
                             */
                ucByteSend, /* the actual data to be written to the card */
                ioreq,      /* The returned protocol control information */
                ref ucByteReceive);

            if (rc == SCardError.Success)
            {
                Console.Write("Uid: ");
                for (int i = 0; i < (ucByteReceive.Length); i++)
                    Console.Write("{0:X2} ", ucByteReceive[i]);
                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("Error: " + SCardHelper.StringifyError(rc));
            }

            RFIDReader.EndTransaction(SCardReaderDisposition.Leave);
            RFIDReader.Disconnect(SCardReaderDisposition.Reset);

            return;
        }
Ejemplo n.º 8
0
        ///// <summary>
        ///// Select an applet based on its AID (Application IDentifier). As for now the AID should have a length of 11 bytes.
        ///// </summary>
        ///// <param name="AID">Application Identifier. An 11 byte array that represents the applet to select</param>
        private void SelectApplet(byte[] AID)
        {
            TS.TraceI("Start SelectApplet with ID \"{0}\".", Helper.ByteArrayToString(AID));
            this.crdReader = GetReader();

            byte[] pbRecvBuffer = new byte[256];

            if (AID.Length != 0x0B)
            {
                throw new ArgumentException("Invalid length AID", "AID");
            }

            //// Send SELECT Applet command
            byte[] selectApplet = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x0B, AID[0], AID[1], AID[2], AID[3], AID[4], AID[5], AID[6], AID[7], AID[8], AID[9], AID[10], 0x00 };
            TS.TraceV("Select applet command: \"{0}\".", Helper.ByteArrayToString(selectApplet));

            /////*
            //// 00 = Class
            //// A4 = Instructie
            //// 04 = P1 = Select Dedicated File (DF)
            //// 00 = P2 = File Control Information (FCI)
            //// 0B = lc = Lengte van de AID
            //// AID
            //// 00 = End
            ////*/
            SCardError err = crdReader.Transmit(selectApplet, ref pbRecvBuffer);
            if (err != SCardError.Success)
            {
                throw new CardReaderException(err, SCardHelper.StringifyError(err));
            }

            ResponseApdu resp = new ResponseApdu(pbRecvBuffer, IsoCase.Case4Extended, this.crdReader.ActiveProtocol);
            if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00))
            {
                throw new CardReaderException("Invalid response");
            }

            TS.TraceI("End SelectApplet.");
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            // Establish Smartcard context
            SCardContext ctx = new SCardContext();
            ctx.Establish(SCardScope.System);

            string[] readernames = ctx.GetReaders();
            if (readernames == null || readernames.Length < 1)
                throw new Exception("You need at least one reader in order to run this example.");

            // we will use the first reader for the transmit test.
            string readername = readernames[0];

            SCardReader reader = new SCardReader(ctx);
            SCardError rc = reader.Connect(
                readername,
                SCardShareMode.Shared,
                SCardProtocol.Any);
            if (rc != SCardError.Success)
            {
                Console.WriteLine("Could not connect to card in reader " + readername + "\n"
                    + "Error: " + SCardHelper.StringifyError(rc));
                return;
            }

            // Build a GET CHALLENGE command
            CommandApdu apdu = new CommandApdu(
                IsoCase.Case2Short,
                reader.ActiveProtocol);

            apdu.CLA = 0x00; // Class
            apdu.INS = 0x84; // Instruction: GET CHALLENGE 
            apdu.P1 = 0x00;  // Parameter 1
            apdu.P2 = 0x00;  // Parameter 2
            apdu.Le = 0x08;  // Expected length of the returned data
            
            // convert the APDU object into an array of bytes
            byte[] cmd = apdu.ToArray();
            // prepare a buffer for response APDU -> LE + 2 bytes (SW1 SW2)
            byte[] outbuf = new byte[apdu.ExpectedResponseLength]; 

            rc = reader.Transmit(
                cmd,
                ref outbuf);

            if (rc == SCardError.Success)
            {
                Console.WriteLine("Ok.");

                if (outbuf != null)
                {
                    ResponseApdu response = new ResponseApdu(outbuf, apdu.Case, apdu.Protocol);
                    if (response.IsValid)
                    {
                        Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2);
                        if (response.HasData)
                        {
                            Console.Write("Data: ");
                            for (int i = 0; i < (response.DataSize); i++)
                                Console.Write("{0:X2} ", response.FullApdu[i]);
                            Console.WriteLine("");
                        }
                    }
                }
            }
            else
            {
                // Error
                Console.WriteLine(SCardHelper.StringifyError(rc));
            }

            return;

        }
        public string ReadSmartCard()
        {
            using (var context = new SCardContext())
            {
                context.Establish(SCardScope.System);
                string readerName = null;
                try
                {
                    string[] readerNames = context.GetReaders();
                    readerName = readerNames[0];
                }
                catch(Exception ex)
                {
                    return "error";
                }

                if (readerName == null)
                {
                    return "error";
                }

                using (var rfidReader = new SCardReader(context))
                {

                    var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                    if (sc != SCardError.Success)
                    {
                        return "error";//"Could not connect to reader {0}:\n{1}";

                    }

                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol)
                    {
                        CLA = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1 = 0x00,
                        P2 = 0x00,
                        Le = 0  // We don't know the ID tag size
                    };

                    sc = rfidReader.BeginTransaction();
                    if (sc != SCardError.Success)
                    {
                        return "none";// "Could not begin transaction.";

                    }

                    var receivePci = new SCardPCI(); // IO returned protocol control information.
                    var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol);

                    var receiveBuffer = new byte[256];
                    var command = apdu.ToArray();

                    sc = rfidReader.Transmit(
                        sendPci,            // Protocol Control Information (T0, T1 or Raw)
                        command,            // command APDU
                        receivePci,         // returning Protocol Control Information
                        ref receiveBuffer); // data buffer

                    if (sc != SCardError.Success)
                    {
                        return "none";//SCardHelper.StringifyError(sc);
                    }

                    var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);

                    rfidReader.EndTransaction(SCardReaderDisposition.Leave);
                    rfidReader.Disconnect(SCardReaderDisposition.Reset);

                    int id = responseApdu.HasData ? BitConverter.ToInt32(responseApdu.GetData(),0) : -1;
                    //int id = responseApdu.HasData ? System.Text.Encoding.UTF8.GetString(responseApdu.GetData()) : "none";

                    if (id < 0) id = id * (-1);
                    return id.ToString();

                }
            }
            return "none";
        }