private byte[] SendCommand(byte[] command)
        {
            byte[] responseBuffer = new byte[256];

            error = reader.Transmit(intPtr, command, ref responseBuffer);
            HandleError();

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

            if (responseApdu.SW1.Equals((byte)SW1Code.NormalDataResponse))
            {
                command        = apdu.GetResponse().Concat(new byte[] { responseApdu.SW2 }).ToArray();
                responseBuffer = new byte[258];

                error = reader.Transmit(intPtr, command, ref responseBuffer);
                HandleError();

                if (responseBuffer.Length - responseApdu.SW2 == 2)
                {
                    return(responseBuffer.Take(responseBuffer.Length - 2).ToArray());
                }
            }

            return(responseBuffer);
        }
        private static byte[] sendRequest(SCardReader rfidReader, SCardError sc, SCardPCI receivePci,
                                          IntPtr sendPci, CommandApdu apdu, ResponseApdu responseApdu, IsoCase isoCase)
        {
            sc = rfidReader.BeginTransaction();
            if (sc != SCardError.Success)
            {
                return(null);
            }

            receivePci = new SCardPCI();
            sendPci    = SCardPCI.GetPci(rfidReader.ActiveProtocol);

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

            sc = rfidReader.Transmit(
                sendPci,
                command,
                receivePci,
                ref receiveBuffer);

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

            responseApdu = new ResponseApdu(receiveBuffer, isoCase, rfidReader.ActiveProtocol);

            if (!responseApdu.HasData)
            {
                return(null);
            }

            return((byte[])responseApdu.GetData());
        }
Ejemplo n.º 3
0
        private byte[] ReadFileNextBlock(int offSet, int lenght)
        {
            TS.TraceV("Start ReadFileNextBlock, offset = \"{0}\", length = \"{1}\".", offSet, lenght);
            byte[] pbRecvBuffer = new byte[lenght + 2]; //// Last 2 bytes are sw1 + sw2
            byte[] offSetArr    = MTVReader.Converter.IntToByteArray(offSet, 2);
            byte[] lenghtArr    = MTVReader.Converter.IntToByteArray(lenght, 1);
            byte[] readFile     = new byte[] { 0x00, 0xB0, offSetArr[0], offSetArr[1], lenghtArr[0] };

            SCardError err = this.crdReader.Transmit(readFile, ref pbRecvBuffer);

            if (err != SCardError.Success)
            {
                TS.TraceV("CardReaderException: \"{0}\".", SCardHelper.StringifyError(err));
                throw new CardReaderException(err, "Unfortunately, this smart card can not be read");
            }

            ResponseApdu resp = new ResponseApdu(pbRecvBuffer, IsoCase.Case4Extended, this.crdReader.ActiveProtocol);

            if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00))
            {
                throw new CardReaderException(string.Format("Error reading next block for file at offset {0}, length {1}", offSet, lenght));
            }
            TS.TraceV("End ReadFileNextBlock.");
            return(resp.GetData());
        }
Ejemplo n.º 4
0
        public string RetrieveCardUID()
        {
            var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);

            if (sc != SCardError.Success)
            {
                MessageBox.Show("The reader did not have enough time to read, \nplease reswipe the card", "Error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return("Failed to retrieve card 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, command, receivePci, ref receiveBuffer);

            if (sc != SCardError.Success)
            {
                MessageBox.Show("Error: " + SCardHelper.StringifyError(sc));
                return("Failed to retrieve card UID");
            }
            var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);

            rfidReader.EndTransaction(SCardReaderDisposition.Leave);
            rfidReader.Disconnect(SCardReaderDisposition.Reset);
            return(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received, please reswipe the card");
        }
Ejemplo n.º 5
0
        public static void Main()
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System)) {
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    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' statement to make sure the reader will be disposed (disconnected) on exit
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) {
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1          = 0x00,
                        P2          = 0x00,
                        Le          = 0 // We don't know the ID tag size
                    };

                    using (rfidReader.Transaction(SCardReaderDisposition.Leave)) {
                        Console.WriteLine("Retrieving the UID .... ");

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

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

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

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

                    Console.ReadKey();
                }
            }
        }
        private bool SelectApplet()
        {
            byte[] command        = apdu.Select(apdu.MinistryOfInteriorAppletCommand);
            byte[] responseBuffer = new byte[256];

            error = reader.Transmit(intPtr, command, ref responseBuffer);
            HandleError();

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

            return(responseApdu.SW1.Equals((byte)SW1Code.NormalDataResponse) || responseApdu.SW1.Equals((byte)SW1Code.Normal));
        }
Ejemplo n.º 7
0
 private string GetUid(string readerName)
 {
     using (var context = new SCardContext())
     {
         context.Establish(SCardScope.System);
         using (var rfidReader = new SCardReader(context))
         {
             var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
             if (sc != SCardError.Success)
             {
                 Debug.WriteLine($"PcscWrapper: Could not connect to reader {readerName}:\n{SCardHelper.StringifyError(sc)}");
                 return(null);
             }
             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)
             {
                 Debug.WriteLine("PcscWrapper: Could not begin transaction.");
                 return(null);
             }
             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)
             {
                 Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc));
             }
             var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
             rfidReader.EndTransaction(SCardReaderDisposition.Leave);
             rfidReader.Disconnect(SCardReaderDisposition.Reset);
             if (responseApdu.HasData)
             {
                 string uid = BitConverter.ToString(responseApdu.GetData()).Replace("-", "").ToUpper();
                 return(uid);
             }
         }
     }
     return(null);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Get data writing on the card
        /// </summary>
        /// <returns></returns>
        public static byte[] GetDataFromTheCard()
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (readerNames == null)
                {
                    return(null);
                }

                var readerName = readerNames[0];
                if (readerName == null)
                {
                    return(null);
                }

                // 'using' statement to make sure the reader will be disposed (disconnected) on exit
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.ReadBinary,
                        P1          = 0x00,
                        P2          = 0x09,
                        Le          = 0x07 // We don't know the ID tag size
                    };

                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        var sendPci    = SCardPCI.GetPci(rfidReader.Protocol);
                        var receivePci = new SCardPCI(); // IO returned protocol control information.

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

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

                        var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol);
                        return(responseApdu.GetData());
                    }
                }
            }
        }
Ejemplo n.º 9
0
        ///// <summary>
        ///// Select a special applet based on its AID (Application IDentifier) with a length of 5 bytes.
        ///// </summary>
        ///// <param name="AID">Application Identifier. A 5 byte array that represents the applet to select</param>
        public void SelectSpecialApplet(byte[] AID)
        {
            TS.TraceI("Start SelectApplet with ID \"{0}\".", Helper.ByteArrayToString(AID));
            this.crdReader = GetReader();

            byte[] pbRecvBuffer = new byte[256];

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

            //// Send SELECT Applet command
            byte[] selectApplet = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x05, AID[0], AID[1], AID[2], AID[3], AID[4], 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 == 0x6A) && (resp.SW2 == 0x82))
            {
                throw new CardReaderException("Applet not found");
            }

            if ((resp.SW1 != 0x62) && (resp.SW2 != 0x83))
            {
                throw new CardReaderException("Invalid response");
            }

            /*if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00))
             * {
             *  throw new CardReaderException("Invalid response");
             * }
             */
            TS.TraceI("End SelectApplet.");
        }
Ejemplo n.º 10
0
        private bool SelectApplet()
        {
            byte[] command = _apdu.APDU_SELECT(_apdu.AID_MOI);
            byte[] pbRecvBuffer;
            pbRecvBuffer = new byte[256];
            _err         = _reader.Transmit(_pioSendPci, command, ref pbRecvBuffer);
            CheckErr(_err);
            var responseApdu = new ResponseApdu(pbRecvBuffer, IsoCase.Case2Short, _reader.ActiveProtocol);

            if (responseApdu.SW1.Equals((byte)SW1Code.NormalDataResponse) || responseApdu.SW1.Equals((byte)SW1Code.Normal))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 11
0
        private static string GetCardUID(string readerName)
        {
            using (var context = _contextFactory.Establish(SCardScope.System))
            {
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1          = 0x00,
                        P2          = 0x00,
                        Le          = 0 // We don't know the ID tag size
                    };

                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        //Console.WriteLine("Retrieving the UID .... ");

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

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

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

                        var responseApdu =
                            new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol);
                        Log.Debug("Uid: {2} SW1: {0:X2}, SW2: {1:X2}\n",
                                  responseApdu.SW1,
                                  responseApdu.SW2,
                                  responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received");
                        return(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()).Replace("-", "").ToUpper() : null);
                    }
                }
            }
        }
            public BalanceReaderEventArgs create(ResponseApdu responseApdu)
            {
                var responseData = responseApdu.GetData();

                if (responseData.Length < 6)
                {
                    return(null);
                }

                byte recordNumber = responseData[0];
                byte dataFormat   = responseData[1];
                byte digitCount   = responseData[2];
                byte decimalPoint = responseData[3];
                byte delay        = responseData[4];
                bool moreData     = responseData[5] == 1;

                byte[] data;
                if (responseData.Length > 6)
                {
                    data = responseData.Skip(6).ToArray();
                }
                else
                {
                    data = new byte[0];
                }

                switch (dataFormat)
                {
                case 1:
                    return(new AlphanumericRecordEventArgs(recordNumber, moreData, data, digitCount, delay));

                case 2:
                    return(new HexadecimalRecordEventArgs(recordNumber, moreData, data, digitCount, delay));

                case 4:
                    return(new DecimalRecordEventArgs(recordNumber, moreData, data, digitCount, decimalPoint, delay));

                case 8:
                    return(new SignedDecimalRecordEventArgs(recordNumber, moreData, data, digitCount, decimalPoint, delay));

                default:
                    return(null);
                }
            }
Ejemplo n.º 13
0
        private byte[] SendCommand(byte [] command)
        {
            byte[] pbRecvBuffer;
            pbRecvBuffer = new byte[256];
            _err         = _reader.Transmit(_pioSendPci, command, ref pbRecvBuffer);
            CheckErr(_err);
            var responseApdu = new ResponseApdu(pbRecvBuffer, IsoCase.Case2Short, _reader.ActiveProtocol);

            if (responseApdu.SW1.Equals((byte)SW1Code.NormalDataResponse))
            {
                command      = _apdu.APDU_GET_RESPONSE().Concat(new byte[] { responseApdu.SW2 }).ToArray();
                pbRecvBuffer = new byte[258];
                _err         = _reader.Transmit(_pioSendPci, command, ref pbRecvBuffer);
                if (pbRecvBuffer.Length - responseApdu.SW2 == 2)
                {
                    return(pbRecvBuffer.Take(pbRecvBuffer.Length - 2).ToArray());
                }
            }

            return(pbRecvBuffer);
        }
Ejemplo n.º 14
0
        public string GetCardUID(string cardReaderName)
        {
            try
            {
                var contextFactory = ContextFactory.Instance;
                using (var context = contextFactory.Establish(SCardScope.System))
                {
                    using (var rfidReader = new SCardReader(context))
                    {
                        var sc = rfidReader.Connect(cardReaderName, SCardShareMode.Shared, SCardProtocol.Any);
                        if (sc != SCardError.Success)
                        {
                            Debug.WriteLine(string.Format("GetCardUID: Could not connect to reader {0}:\n{1}",
                                                          cardReaderName,
                                                          SCardHelper.StringifyError(sc)));
                            return(string.Empty);
                        }

                        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)
                        {
                            Debug.WriteLine("GetCardUID: Could not begin transaction.");
                            return(string.Empty);
                        }

                        Debug.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)
                        {
                            Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc));
                            return(string.Empty);
                        }

                        var    responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
                        string cardUID      = responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received";

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

                        return(cardUID);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetCardUID exception: CardReaderName: " + cardReaderName + ". Error: " + ex.ToString());
                return(string.Empty);
            }
        }
Ejemplo n.º 15
0
        private void Button_ReadID_Click(object sender, RoutedEventArgs e)
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    textBox_Log.Text += "You need at least one reader in order to run this example." + "\r\n";
                    return;
                }

                var readerName = ChooseRfidReader(readerNames);

                if (readerName == null)
                {
                    return;
                }
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1          = 0x00,
                        P2          = 0x00,
                        Le          = 0
                    };
                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        textBox_Log.Text += "Retrieving the UID .... " + "\r\n";

                        var sendPci       = SCardPCI.GetPci(rfidReader.Protocol);
                        var receivePci    = new SCardPCI();
                        var receiveBuffer = new byte[256];
                        var command       = apdu.ToArray();

                        var bytesReceived = rfidReader.Transmit(
                            sendPci,
                            command,
                            command.Length,
                            receivePci,
                            receiveBuffer,
                            receiveBuffer.Length);
                        var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol);

                        textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString() + " ,SW2: " + responseApdu.SW2.ToString() + "\r\n";

                        if (responseApdu.HasData)
                        {
                            textBox_Log.Text += "Uid: " + BitConverter.ToString(responseApdu.GetData()) + "\r\n";
                        }
                        else
                        {
                            textBox_Log.Text += "Uid: No uid received" + "\r\n";
                        }
                    }
                }
            }
            textBox_Log.Text += "-----------------------------------------------\r\n";
        }
        public byte[] ReadNIS(string reader)
        {
            // Connection to reader
            var sc = _peripheral.Connect(reader, SCardShareMode.Shared, SCardProtocol.Any);

            if (sc != SCardError.Success)
            {
                throw new Exception(string.Format("Could not connect to reader {0}:\n{1}",
                                                  reader,
                                                  SCardHelper.StringifyError(sc)));
            }
            try
            {
                CommandApdu  apdu;
                ResponseApdu rapdu;
                byte[]       receiveBuffer;

                /* 00 A4 - 04 0C 0D - A0 00 00 00 30 80 00 00 00 09 81 60 01 Selezione Applet CIE  */
                receiveBuffer = new byte[2];
                apdu          = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol)
                {
                    CLA  = 0x00,
                    INS  = 0XA4,
                    P1   = 0x04,
                    P2   = 0x0C,
                    Le   = 0x0D,
                    Data = new byte[] { (byte)0xA0, 0x00, 0x00, 0x00, 0x30, (byte)0x80, 0x00, 0x00, 0x00, 0x09, (byte)0x81, 0x60, 0x01 }
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);

                /* 00 A4 - 04 0C 06 - A0 00 00 00 00 39 Selezione DF_CIE */
                receiveBuffer = new byte[2];
                apdu          = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol)
                {
                    CLA  = 0x00,
                    INS  = 0XA4,
                    P1   = 0x04,
                    P2   = 0x0C,
                    Le   = 0x00,
                    Data = new byte[] { (byte)0xA0, 0x00, 0x00, 0x00, 0x00, 0x39 }
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);

                /* 00 B0 - 81 00 00 Lettura NIS */
                receiveBuffer = new byte[14];
                apdu          = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol)
                {
                    CLA = 0x00,
                    INS = 0XB0,
                    P1  = 0x81,
                    P2  = 0x00,
                    Le  = 0x00
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);
                rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol);
                var NIS_ID = rapdu.GetData();

                /* 00 B0 - 85 00 00 Lettura chiave pubblica - 1*/
                receiveBuffer = new byte[233];
                apdu          = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol)
                {
                    CLA = 0x00,
                    INS = 0XB0,
                    P1  = 0x85,
                    P2  = 0x00,
                    Le  = 0x00
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);
                rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol);
                var pubkey1 = rapdu.GetData();

                /* 00 B0 - 85 E7 00 - Lettura chiave pubblica - 2 */
                receiveBuffer = new byte[233];
                apdu          = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol)
                {
                    CLA = 0x00,
                    INS = 0XB0,
                    P1  = 0x85,
                    P2  = 0xE7,
                    Le  = 0x00
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);
                rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol);
                var pubkey2 = rapdu.GetData();
                //Combine pubkey1 and pubkey2 to obtain ASN1 structure that contain 2 children, modulus and exponent
                //that is used to create RSA crypto service provider
                var pubKeyAsn1 = ASN1Tag.Parse(pubkey1.Combine(pubkey2));

                /* 00 22 - 41 A4 06 - 80 01 02 84 01 83 - Selezione chiave int-auth */
                receiveBuffer = new byte[2];
                apdu          = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol)
                {
                    CLA  = 0x00,
                    INS  = 0x22,
                    P1   = 0x41,
                    P2   = 0xA4,
                    Le   = 0x02,
                    Data = new byte[] { 0x80, 0x01, 0x02, 0x84, 0x01, 0x83 }
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);

                /* Generate random to perform sign and verify */
                var challenge = ByteArrayOperations.GenerateRandomByteArray(8);

                /* 00 88 - 00 00 08 - hashChallenge 00 int-auth*/
                receiveBuffer = new byte[258];
                apdu          = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol)
                {
                    CLA  = 0x00,
                    INS  = 0x88,
                    P1   = 0x00,
                    P2   = 0x00,
                    Le   = 0x00,
                    Data = challenge
                };
                sc = _peripheral.Transmit(
                    SCardPCI.GetPci(_peripheral.ActiveProtocol),
                    apdu.ToArray(),
                    new SCardPCI(),
                    ref receiveBuffer);
                rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, _peripheral.ActiveProtocol);
                var signedData = rapdu.GetData();

                //Verify challenge with public key
                using (var rsa = RSA.Create())
                {
                    var modulus = pubKeyAsn1.Child(0, 0x02).Data; // modulus. 02 Verify that result is a INTEGER
                    var exp     = pubKeyAsn1.Child(1, 0x02).Data; // exp. 02 Verify that result is a INTEGER
                    if (!rsa.PureVerify(challenge, signedData, modulus, exp))
                    {
                        throw new Exception("Unable to verify challenge");
                    }
                }

                //Read SOD data record
                var    idx  = 0;
                var    size = 0xe4;
                byte[] data;
                byte[] sodIASData = new byte[0];
                bool   sodLoaded  = false;
                while (!sodLoaded)
                {
                    var hexS = idx.ToString("X4");
                    receiveBuffer = new byte[233];
                    apdu          = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol)
                    {
                        CLA  = 0x00,
                        INS  = 0xB1,
                        P1   = 0x00,
                        P2   = 0x06,
                        Le   = 0x00,
                        Data = new byte[] {
                            0x54,
                            0x02,
                            byte.Parse(hexS.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                            byte.Parse(hexS.Substring(2, 2), System.Globalization.NumberStyles.HexNumber)
                        }
                    };
                    sc = _peripheral.Transmit(
                        SCardPCI.GetPci(_peripheral.ActiveProtocol),
                        apdu.ToArray(),
                        new SCardPCI(),
                        ref receiveBuffer);
                    rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, _peripheral.ActiveProtocol);
                    data  = rapdu.GetData();
                    var offset = 2;
                    if (data[1] > 0x80)
                    {
                        offset = 2 + (data[1] - 0x80);
                    }
                    var buf = data.SubArray(offset, data.Length - offset);
                    sodIASData = sodIASData.Combine(buf);
                    idx       += size;
                    if (data[2] != 0xe4)
                    {
                        sodLoaded = true;
                    }
                }
                //Create IAS ASN1 object
                var ias     = IASSod.Create(sodIASData);
                var isValid = ias.Verify(NIS_ID);

                //Verify integrity of data
                if (isValid)
                {
                    return(NIS_ID);
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally { _peripheral.Disconnect(SCardReaderDisposition.Reset); }
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            if (Process.GetProcesses().Count(
                    p => p.ProcessName.ToLower() ==
                    Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.SetupInformation.ApplicationName.ToLower())
                    ) > 1)
            {
                Console.WriteLine("Only a single instance can run in a time");
                return;
            }

            var    monitorFactory = MonitorFactory.Instance;
            var    monitor        = monitorFactory.Create(SCardScope.System);
            var    readerName     = "ACS ACR122 0";
            string cardUID        = null;

            monitor.StatusChanged += (sender, states) =>
            {
                if (states.NewState == SCRState.Empty)
                {
                    cardUID = null;
                    Console.Clear();
                    Console.WriteLine("[Status] Card Remove");
                }
                else if (states.NewState == SCRState.Present)
                {
                    if (states.NewState == SCRState.InUse)
                    {
                        Console.WriteLine($"[Status] {states.NewState}");
                        return;
                    }
                    Console.WriteLine($"[Status] {states.NewState}");

                    using (var context = ContextFactory.Instance.Establish(SCardScope.System))
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(cardUID))
                            {
                                return;
                            }
                            using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                            {
                                var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                                {
                                    CLA         = 0xFF,
                                    Instruction = InstructionCode.GetData,
                                    P1          = 0x00,
                                    P2          = 0x00,
                                    Le          = 0
                                };

                                using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                                {
                                    //Console.WriteLine("Retrieving the UID .... ");

                                    var sendPci    = SCardPCI.GetPci(rfidReader.Protocol);
                                    var receivePci = new SCardPCI();

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

                                    var bytesReceived = rfidReader.Transmit(
                                        sendPci,
                                        command,
                                        command.Length,
                                        receivePci,
                                        receiveBuffer,
                                        receiveBuffer.Length);
                                    var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol);
                                    if (responseApdu.HasData)
                                    {
                                        cardUID = BitConverter.ToString(responseApdu.GetData()).Replace("-", string.Empty);
                                        string cardNo = CCardUtil.CardCode(cardUID);
                                        if (string.IsNullOrEmpty(cardNo))
                                        {
                                            Console.WriteLine("[Card] Unsupported Card");
                                            return;
                                        }
                                        Console.WriteLine("[Card] ID:" + cardNo);
                                        InputSimulator s = new InputSimulator();
                                        s.Keyboard.TextEntry(cardNo);
                                        Thread.Sleep(10);
                                        s.Keyboard.KeyDown(VirtualKeyCode.RETURN);
                                        Thread.Sleep(10);
                                        s.Keyboard.KeyUp(VirtualKeyCode.RETURN);
                                        Thread.Sleep(10);
                                    }
                                    else
                                    {
                                        cardUID = null;
                                        Console.WriteLine("[Card] No uid received");
                                    }
                                }
                            }
                        }
                        catch (PCSC.Exceptions.ReaderUnavailableException)
                        {
                            cardUID = null;
                            Console.WriteLine("[Card] Reader Unavailable");
                        }
                    }
                }
            };

            monitor.Start(readerName);

            Console.ReadKey();

            monitor.Cancel();
            monitor.Dispose();
        }
Ejemplo n.º 18
0
        // Obsługa przycisku wysłania komend
        private void ButtonTransmitCommand_Click(object sender, EventArgs e)
        {
            // Utworzenie sesji połączenia
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                // Pobranie nazw czytników
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    MessageBox.Show("Brak podłączonych urządzeń");
                    return;
                }

                // Przypisanie nazwy czytnika
                var readerName = readerNames[0];
                if (readerName == null)
                {
                    return;
                }

                using (var rfidReader = new SCardReader(context))
                {
                    //przypisanie połaczenia za pośrednictwerm RFID
                    var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                    if (sc != SCardError.Success) // W przypadku niepowodzenia
                    {
                        MessageBox.Show("Brak połączenia" +
                                        readerName +
                                        SCardHelper.StringifyError(sc));

                        return;
                    }
                    // pobranie komendy z pola tekstowego
                    byte[] command = Encoding.ASCII.GetBytes(textBoxCommand.Text);

                    sc = rfidReader.BeginTransaction();
                    if (sc != SCardError.Success)
                    {
                        MessageBox.Show("");
                        return;
                    }

                    var receivePci    = new SCardPCI(); // IO zwraca protocol control information.
                    var sendPci       = SCardPCI.GetPci(rfidReader.ActiveProtocol);
                    var receiveBuffer = new byte[256];

                    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)
                    {
                        MessageBox.Show("BŁĄD: " + SCardHelper.StringifyError(sc));
                    }
                    // OPOWIEDZ APDU
                    var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);

                    textBoxAnswer.Text = responseApdu.SW1.ToString() + " " + responseApdu.SW2 + (responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "");

                    rfidReader.EndTransaction(SCardReaderDisposition.Leave);
                    rfidReader.Disconnect(SCardReaderDisposition.Reset);
                }
            }
        }
Ejemplo n.º 19
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.º 20
0
        public static void GetUID(string readerName)
        {
            try
            {
                var c = Console.ForegroundColor;
                //Console.Write("Scan: ");
                Console.ForegroundColor = ConsoleColor.DarkGreen;

                using (var ctx = _contextFactory.Establish(SCardScope.System))
                {
                    using (var rfidReader = new SCardReader(ctx)) // 'using' statement to make sure the reader will be disposed (disconnected) on exit
                    {
                        var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                        if (sc != SCardError.Success)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.Write($"{SCardHelper.StringifyError(sc)}");
                        }
                        else
                        {
                            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.ForegroundColor = ConsoleColor.Red;
                                Console.Write("Could not begin transaction.");
                            }
                            else
                            {
                                var receiveBuffer = new byte[256];
                                var adpuSunst     = new byte[256];

                                sc = rfidReader.Transmit(
                                    SCardPCI.GetPci(rfidReader.ActiveProtocol), // Protocol Control Information (T0, T1 or Raw)
                                    apdu.ToArray(),                             // command APDU
                                    new SCardPCI(),                             // returning Protocol Control Information
                                    ref receiveBuffer);                         // data buffer

                                if (sc != SCardError.Success)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.Write("\tError: " + SCardHelper.StringifyError(sc));
                                }

                                var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.Write($"{(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"),-22}  ");

                                Console.ForegroundColor = ConsoleColor.DarkGreen;
                                Console.Write($"{responseApdu.SW1:X2}    {responseApdu.SW2:X2}    ");

                                DisplayCardAtr(reader: rfidReader);

                                rfidReader.EndTransaction(SCardReaderDisposition.Leave);
                                rfidReader.Disconnect(SCardReaderDisposition.Reset);
                            }
                        }
                    }
                }
                Console.ForegroundColor = c;
            }
            catch (Exception ex) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n{ex}\n"); Console.ForegroundColor = c; }
        }
Ejemplo n.º 21
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();
                }
            }
        }
        private static string getPanNumber1(SCardContext context, string readerName)
        {
            var rfidReader = new SCardReader(context);

            byte[] readRecord = new byte[0];
            byte   x          = 0x00;
            var    sc         = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);

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

            //----------------Get AID---------------------------
            var apdu = new CommandApdu(IsoCase.Case4Short, rfidReader.ActiveProtocol)
            {
                CLA  = 0x00,
                INS  = 0xA4,
                P1   = 0x04,
                P2   = 0x00,
                Le   = 0x00,
                Data = selectAid
            };

            var receivePci    = new SCardPCI();
            var sendPci       = SCardPCI.GetPci(rfidReader.ActiveProtocol);
            var receiveBuffer = new byte[256];
            var responseApdu  = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, rfidReader.ActiveProtocol);


            String aid;

            byte[] aidByte = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case4Short);

            if (aidByte == null)
            {
                return(null);
            }

            String pAid   = ByteArrayToHexString(aidByte);
            int    aidInd = pAid.LastIndexOf("4F07");

            aid = pAid.Substring(aidInd + 4, 14);

            //------------------------ end ------------------------------

            if (aid.Equals("A0000000041010"))
            {
                readRecord = selectMCAID;
                x          = 0x14;
            }
            else if (aid.Equals("A0000000031010"))
            {
                readRecord = selectVisaAID;
                x          = 0x1C;
            }

            //----------------selectMCAID---------------------------

            apdu = new CommandApdu(IsoCase.Case4Short, rfidReader.ActiveProtocol)
            {
                CLA  = 0x00,
                INS  = 0xA4,
                P1   = 0x04,
                P2   = 0x00,
                Le   = 0x00,
                Data = readRecord
            };

            byte[] selectTAypeCard = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case4Short);
            if (selectTAypeCard == null)
            {
                return(null);
            }
            //------------------------ end ------------------------------

            apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol)
            {
                CLA = 0x00,
                INS = 0xB2,
                P1  = 0x01,
                P2  = x,
                Le  = 0x00
            };

            String pan;

            byte[] a = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case2Short);   //(byte[])responseApdu.GetData();

            if (a == null)
            {
                return(null);
            }
            String p      = ByteArrayToHexString(a);
            int    panInd = p.LastIndexOf("5A08");

            pan = p.Substring(panInd + 4, 16);

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

            return(pan);
        }
Ejemplo n.º 23
0
        private void Button_ReadCardType_Click(object sender, RoutedEventArgs e)
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    textBox_Log.Text += "You need at least one reader in order to run this example." + "\r\n";
                    return;
                }

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

                // 'using' statement to make sure the reader will be disposed (disconnected) on exit
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.GetData,
                        P1          = 0xF3,
                        P2          = 0x00,
                        Le          = 0 // We don't know the ID tag size
                    };

                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        textBox_Log.Text += "Retrieving the UID .... " + "\r\n";

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

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

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

                        var responseApdu =
                            new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol);
                        textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString()
                                            + ", SW2: " + responseApdu.SW2.ToString()
                                            + "\r\n";
                        if (responseApdu.HasData)
                        {
                            textBox_Log.Text += "CardType: " + BitConverter.ToString(responseApdu.GetData()) + "\r\n";
                        }
                        else
                        {
                            textBox_Log.Text += "Uid: No uid received" + "\r\n";
                        }
                    }
                }
            }
            textBox_Log.Text += "-----------------------------------------------\r\n";
        }
Ejemplo n.º 24
0
        public byte[] ReadFile(byte[] AID, byte[] FileID)
        {
            TS.TraceI("Readfile with AID \"{0}\" and FileID \"{1}\".", Helper.ByteArrayToString(AID), Helper.ByteArrayToString(FileID));
            SelectApplet(AID);

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

            if (this.crdReader == null)
            {
                throw new CardReaderException("No valid reader available");
            }

            byte[] pbRecvBuffer = new byte[256];

            //// Send SELECT File
            byte[] selectFile = new byte[] { 0x00, 0xA4, 0x02, 0x04, 0x02, FileID[0], FileID[1], 0x00 };
            TS.TraceV("Select file with command: \"{0}\".", Helper.ByteArrayToString(selectFile));

            /*
             *  00 = Class
             *  A4 = Instructie
             *  02 = P1 (select EF under current DF)
             *  04 = P2 (return FCP data)
             *  02 = Lc
             *  XX = Data
             *  XX = Data
             *  00 = Le
             */
            SCardError err = this.crdReader.Transmit(selectFile, 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))
            {
                return(null);
            }

            byte[] fileInfo = resp.GetData();

            if (fileInfo == null)
            {
                throw new CardReaderException(string.Format(
                                                  "No data available reading FileID \"{0}\" with AID \"{1}\".", Helper.ByteArrayToString(FileID), Helper.ByteArrayToString(AID)));
            }

            TLVList myanswer = TLV.Parse(new MemoryStream(fileInfo));

            TLV fileLengthTLV = myanswer.getTag("1,62|1,80");

            if (fileLengthTLV == null)
            {
                throw new CardReaderException("Missing tag: 1,62|1,80");
            }

            int fileLength = Helper.ByteArrayToInt(fileLengthTLV.Value);

            TS.TraceV("File length = \"{0}\".", fileLength);

            //// Read the remaining bytes for this file
            byte[]    fileData  = new byte[fileLength];
            int       bytesRead = 0;
            const int blockSize = 255;

            TS.TraceV("Start reading file with blocksize \"{0}\".", blockSize);
            while (bytesRead < fileLength)
            {
                int lngth = blockSize;
                if (fileLength - bytesRead < blockSize)
                {
                    //// Cannot read an entire block anymore; adjust length of data to read
                    lngth = fileLength - bytesRead;
                    if (lngth == 0)
                    {
                        break;
                    }
                }

                byte[] nextBlock = ReadFileNextBlock(bytesRead, lngth);
                Buffer.BlockCopy(nextBlock, 0, fileData, bytesRead, nextBlock.Length);
                bytesRead += nextBlock.Length;

                TS.TraceV("\"{0}\" bytes read.", bytesRead);
            }
            TS.TraceI("File read.");
            return(fileData);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 不要なものも含まれているので実装時は選別
        /// 現在は履歴を一件ずつ解析、表示しているが処理金額比較などを行う為
        /// データクラスを作成して、一度すべて読み込んでから解析を行う事
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_SuicaRead_Click(object sender, RoutedEventArgs e)
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    textBox_Log.Text += "You need at least one reader in order to run this example.\r\n";
                    return;
                }
                var readerName = ChooseRfidReader(readerNames);
                if (readerName == null)
                {
                    return;
                }

                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    byte[] dataIn         = { 0x0f, 0x09 };
                    var    apduSelectFile = new CommandApdu(IsoCase.Case4Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.SelectFile,
                        P1          = 0x00,
                        P2          = 0x01,
                        Data        = dataIn,
                        Le          = 0
                    };
                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        textBox_Log.Text += "SelectFile .... \r\n";

                        var sendPci       = SCardPCI.GetPci(rfidReader.Protocol);
                        var receivePci    = new SCardPCI();
                        var receiveBuffer = new byte[256];
                        var command       = apduSelectFile.ToArray();

                        var bytesReceivedSelectedFile = rfidReader.Transmit(sendPci, command, command.Length, receivePci, receiveBuffer, receiveBuffer.Length);
                        var responseApdu = new ResponseApdu(receiveBuffer, bytesReceivedSelectedFile, IsoCase.Case2Short, rfidReader.Protocol);

                        textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString()
                                            + ", SW2: " + responseApdu.SW2.ToString() + "\r\n"
                                                                 + "Length: " + responseApdu.Length.ToString() + "\r\n";

                        for (int i = 0; i < 20; ++i)
                        {
                            var apduReadBinary = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                            {
                                CLA         = 0xFF,
                                Instruction = InstructionCode.ReadBinary,
                                P1          = 0x00,
                                P2          = (byte)i,
                                Le          = 0
                            };
                            textBox_Log.Text += "Read Binary .... \r\n";

                            var commandReadBinary = apduReadBinary.ToArray();

                            var bytesReceivedReadBinary2 =
                                rfidReader.Transmit(sendPci, commandReadBinary, commandReadBinary.Length, receivePci, receiveBuffer, receiveBuffer.Length);
                            var responseApdu2 = new ResponseApdu(receiveBuffer, bytesReceivedReadBinary2, IsoCase.Case2Extended, rfidReader.Protocol);

                            textBox_Log.Text += "SW1: " + responseApdu2.SW1.ToString()
                                                + ", SW2: " + responseApdu2.SW2.ToString()
                                                + "\r\n"
                                                + "Length: " + responseApdu2.Length.ToString() + "\r\n";

                            //parse_tag(receiveBuffer);
                            DataManager.GetInstance().AddHistryList(receiveBuffer);

                            textBox_Log.Text += "\r\n";
                        }
                        //履歴DB、CSVに書き込み
                        DataManager.GetInstance().WriteUserHistoryDB();
                        foreach (var s in DataManager.GetInstance().GetHistoryList())
                        {
                            ShowResultData(s);
                        }
                    }
                }
            }
            textBox_Log.Text += "-----------------------------------------------\r\n";
        }
Ejemplo n.º 26
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;
        }
Ejemplo n.º 27
0
        private void Monitor_CardInserted(object sender, CardStatusEventArgs e)
        {
            using (var context = _contextFactory.Establish(SCardScope.System))
            {
                // 'using' statement to make sure the reader will be disposed (disconnected) on exit
                using (var rfidReader = new SCardReader(context))
                {
                    var sc = rfidReader.Connect(e.ReaderName, SCardShareMode.Shared, SCardProtocol.Any);
                    if (sc != SCardError.Success)
                    {
                        Debug.WriteLine("Could not connect to reader {0}:\n{1}",
                                        e.ReaderName,
                                        SCardHelper.StringifyError(sc));
                        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)
                    {
                        Debug.WriteLine("Could not begin transaction.");
                        return;
                    }

                    Debug.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)
                    {
                        Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc));
                    }

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

                    Debug.WriteLine("\nRaw UID: " + (responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"));

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

                    if (responseApdu.HasData)
                    {
                        SendRco(UidToRco(responseApdu.GetData()), BitConverter.ToString(responseApdu.GetData()), e.ReaderName);
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public static (bool Success, string Report) GetUid(IContextFactory contextFactory, string readerName)
        {
            try
            {
                using (var ctx = contextFactory.Establish(SCardScope.System))
                {
                    using (var rfidReader = new SCardReader(ctx))
                    {
                        try
                        {
                            var rc = rfidReader.SetAttrib(SCardAttribute.AsyncProtocolTypes, new[] { (byte)1 }); //

                            var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                            if (sc != SCardError.Success)
                            {
                                return(false, SCardHelper.StringifyError(sc));
                            }
                            else
                            {
                                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(false, "Could not begin transaction.");
                                }
                                else
                                {
                                    var receiveBuffer = new byte[256];

                                    sc = rfidReader.Transmit(
                                        SCardPCI.GetPci(rfidReader.ActiveProtocol), // Protocol Control Information (T0, T1 or Raw)
                                        apdu.ToArray(),                             // command APDU
                                        new SCardPCI(),                             // returning Protocol Control Information
                                        ref receiveBuffer);                         // data buffer

                                    if (sc != SCardError.Success)
                                    {
                                        return(false, SCardHelper.StringifyError(sc));
                                    }

                                    var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
                                    if (responseApdu.HasData)
                                    {
                                        if (!(responseApdu.SW1 == 0x90 && responseApdu.SW2 == 0))
                                        {
                                            return(false, "Not 90-00");
                                        }

                                        var uid = responseApdu.GetData();

                                        return(true, BitConverter.ToString(uid).Replace("-", ""));
                                    }
                                    else
                                    {
                                        return(false, "ResponseApdu has no data");
                                    }
                                }
                            }
                        }
                        catch (Exception ex) { return(false, ex.Message); }
                        finally
                        {
                            rfidReader.EndTransaction(SCardReaderDisposition.Leave);
                            rfidReader.Disconnect(SCardReaderDisposition.Reset);
                        }
                    }
                }
            }
            catch (Exception ex) { return(false, ex.Message); }
        }
Ejemplo n.º 29
0
Archivo: Form1.cs Proyecto: nuhehe/-
        private void button1_Click(object sender, EventArgs e)
        {
            var contextFactory = ContextFactory.Instance;

            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (NoReaderFound(readerNames))
                {
                    textBox_Log.Text += "You need at least one reader in order to run this example.\r\n";
                    return;
                }

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

                // 'using' statement to make sure the reader will be disposed (disconnected) on exit
                using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    //① SelectFileで指定
                    // Case4で設定します
                    byte[] dataIn = { 0x0f, 0x09 };

                    var apduSelectFile = new CommandApdu(IsoCase.Case4Short, rfidReader.Protocol)
                    {
                        CLA         = 0xFF,
                        Instruction = InstructionCode.SelectFile,
                        P1          = 0x00,
                        P2          = 0x01,
                        // Lcは自動計算
                        Data = dataIn,
                        Le   = 0 //
                    };


                    using (rfidReader.Transaction(SCardReaderDisposition.Leave))
                    {
                        textBox_Log.Text += "SelectFile .... \r\n";

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

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

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

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


                        textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString()
                                            + ", SW2: " + responseApdu.SW2.ToString() + "\r\n"
                                            + "Length: " + responseApdu.Length.ToString() + "\r\n";

                        for (int i = 0; i < 20; ++i)
                        {
                            //② ReadBinaryとブロック指定
                            //176 = 0xB0
                            var apduReadBinary = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol)
                            {
                                CLA         = 0xFF,
                                Instruction = InstructionCode.ReadBinary,
                                P1          = 0x00,
                                P2          = (byte)i,
                                Le          = 0 //
                            };

                            //textBox_Log.Text += "Read Binary .... \r\n";

                            var commandReadBinary = apduReadBinary.ToArray();

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

                            var responseApdu2 =
                                new ResponseApdu(receiveBuffer, bytesReceivedReadBinary2, IsoCase.Case2Extended, rfidReader.Protocol);

                            /*textBox_Log.Text += "SW1: " + responseApdu2.SW1.ToString()
                             + ", SW2: " + responseApdu2.SW2.ToString()
                             + "\r\n"
                             + "Length: " + responseApdu2.Length.ToString() + "\r\n";
                             */

                            parse_tag(receiveBuffer);

                            // ③ここにデータ解析関数を実行

                            //textBox_Log.Text += "\r\n";
                        }
                    }
                }
            }
            textBox_Log.Text += "-----------------------------------------------\r\n";
        }