Beispiel #1
0
        public bool SendAPDUSAM(byte[] capdu, ref byte[] rapdu)
        {
            bool Result = false;

            rapdu = new byte[128];

            try
            {
                Result = (sam.Transmit(capdu, ref rapdu) == SCardError.Success);
            }
            catch
            {
                // !!!
            }

            return(Result);
        }
Beispiel #2
0
        /// <summary>
        /// NFC Tag에 값을 쓰는 함수입니다. 현재는 ASCII 코드를 지원하고 4글자만 사용할 수 있습니다.
        /// </summary>
        /// <param name="message">4글자의 작성 메세지를 입력합니다.</param>
        /// <returns>쓰기의 성공 여부를 확인합니다.</returns>
        public bool WriteToTag(string message)
        {
            if (message.Length > 4)
            {
                throw new Exception("Only 4 letters of the message. Sorry.");
            }
            SCardReader reader = new SCardReader(SContext);

            // 카드에 연결합니다.
            SCardError err = reader.Connect(readers[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1);

            long SendPCILength = 0;

            switch (reader.ActiveProtocol)
            {
            case SCardProtocol.T0:
                SendPCILength = (long)SCardPCI.T0;
                break;

            case SCardProtocol.T1:
                SendPCILength = (long)SCardPCI.T1;
                break;

            default:
                throw new Exception("Protocol not support,");
            }

            byte[] receiveBuffer = new byte[256];

            byte[] header  = new byte[] { 0xFF, 0xD6, 0x00, 0x04, 0x04 };
            byte[] Message = StringToByte(message);


            byte[] sendMessage;

            sendMessage = new byte[header.Length + Message.Length];

            Array.Copy(header, 0, sendMessage, 0, header.Length);
            Array.Copy(Message, 0, sendMessage, 5, Message.Length);

            err = reader.Transmit(sendMessage, ref receiveBuffer);
            CheckError(err);

            return(true);
        }
Beispiel #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);
        }
Beispiel #4
0
        /// <summary>
        /// NFC 리더기로 Message를 보내는 함수입니다. MessageList 열거형으로 보낼 메세지를 선택하시고 실행하시면 APDU 통신을 통해 바로 결과를 string으로 리턴합니다.
        /// </summary>
        /// <param name="message">NFC 리더기로 보낼 MessageList를 선택하여 입력합니다.</param>
        /// <returns>APDU 통신 결과를 리턴합니다.</returns>
        public string SendMessageToReader(MessageList message)
        {
            SCardReader reader = new SCardReader(SContext);

            // 카드에 연결합니다.
            SCardError err = reader.Connect(readers[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1);

            long SendPCILength = 0;

            switch (reader.ActiveProtocol)
            {
            case SCardProtocol.T0:
                SendPCILength = (long)SCardPCI.T0;
                break;

            case SCardProtocol.T1:
                SendPCILength = (long)SCardPCI.T1;
                break;

            default:
                throw new Exception("Protocol not support,");
            }

            byte[] receiveBuffer = new byte[256];
            byte[] sendMessage   = null;

            switch (message)
            {
            case MessageList.GetBlockData:
                sendMessage = new byte[] { 0xFF, 0xB0, 0x00, 0x04, 0x04 };
                break;

            case MessageList.GetCardUID:
                sendMessage = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 };
                break;
            }

            err = reader.Transmit(sendMessage, ref receiveBuffer);
            CheckError(err);

            return(ByteToString(receiveBuffer));
        }
Beispiel #5
0
 public byte[] SendApdu(byte[] apdu)
 {
     byte[] receiveBuffer = new byte[263];
     using (SCardReader scardReader = new SCardReader((ISCardContext)this.Context))
     {
         SCardError code1 = scardReader.Connect(this.selectedReader, SCardShareMode.Shared, SCardProtocol.Any);
         if (code1 == SCardError.Success)
         {
             SCardError code2 = scardReader.Transmit(apdu, ref receiveBuffer);
             if (code2 == SCardError.Success)
             {
                 return(receiveBuffer);
             }
             PcscService.logger.Warn("Error while sending APDU to smartcard. Error message: " + SCardHelper.StringifyError(code2));
             return((byte[])null);
         }
         PcscService.logger.Warn("No card inserted or reader is reserved exclusively by another application. Error message: " + SCardHelper.StringifyError(code1));
         return((byte[])null);
     }
 }
Beispiel #6
0
        public string ReadCardUID()
        {
            // initialize the reader.
            SCardReader _reader = new SCardReader(_context);
            // connect to the reader, protocol not limited.
            SCardError _error = _reader.Connect(_port,
                                                SCardShareMode.Shared,
                                                SCardProtocol.T0 | SCardProtocol.T1);

            if (CheckError(_error))
            {
                return(string.Empty);
            }
            IntPtr _pioSendPci;

            // according to the active protocol to set the request structure.
            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];
            // transmit the data fron reader.
            _error = _reader.Transmit(_pioSendPci, Get_ID, ref _pbRecvBuffer);
            string _result = ToHexString(_pbRecvBuffer);

            if (CheckError(_error))
            {
                return(string.Empty);
            }
            return(_result);
        }
Beispiel #7
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.");
        }
Beispiel #8
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);
            }
        }
        public bool StoreId(SCardError err, SCardReader reader, IntPtr pioSendPci, string block, string str_id)
        {
            int    id      = Convert.ToInt32(str_id);
            string to_hex  = id.ToString("X8");
            string substr1 = to_hex.Substring(0, 2);
            string substr2 = to_hex.Substring(2, 2);
            string substr3 = to_hex.Substring(4, 2);
            string substr4 = to_hex.Substring(6, 2);

            byte[] pbRecvBuffer = new byte[256];
            //store value hex id into block
            byte[] cmd4 = new byte[] { (byte)0xFF, (byte)0xD7, (byte)0x00, (byte)int.Parse(block), (byte)0x05, (byte)0x00, (byte)int.Parse(substr1), (byte)int.Parse(substr2), (byte)int.Parse(substr3), (byte)int.Parse(substr4) };

            err = reader.Transmit(pioSendPci, cmd4, ref pbRecvBuffer);
            CheckErr(err);
            if (CheckRespnse(pbRecvBuffer))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #10
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);
            }
        }
Beispiel #11
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;
        }
        public void KeepWaiting(object sender, DoWorkEventArgs e)
        {
            while (!e.Cancel)
            {
                SCardError err;
                IntPtr     pioSendPci;
                try
                {
                    SCardContext hContext  = EstablishContext();
                    string[]     szReaders = RetrieveReaders(hContext);
                    // Create a reader object using the existing context
                    SCardReader reader = new SCardReader(hContext);

                    // Connect to the card
                    err = reader.Connect(szReaders[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1);
                    if (err != SCardError.Success)
                    {
                        throw new PCSCException(err, SCardHelper.StringifyError(err));
                    }
                    else
                    {
                        SmartcardState cstate = CheckCardState();
                        if (cstate == SmartcardState.CardChanged)
                        {
                            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());
                            }

                            bool authvalid = LoadAuth(err, reader, pioSendPci);
                            if (authvalid == true)
                            {
                                string block        = "10";
                                byte[] pbRecvBuffer = new byte[256];
                                //to authenticate, uses the keys stored in reader (previous step 6 ff) to do authentication. two types of authentication type A = 60 and type B = 61.
                                //FF=class, 86=ins, 00=p1, 00=p2, 05=LC, (00=(version 00 or 01), 00, 08=block no to be authenticated, 61=(key type 60 for A or 61 for B), 00=(key location or number 00~01)) = authentication data bytes.
                                // this APDU is PC/SC V2.07
                                byte[] cmd3 = new byte[] { (byte)0xFF, (byte)0x86, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x00, (byte)int.Parse(block), (byte)0x61, (byte)0x00 };

                                err = reader.Transmit(pioSendPci, cmd3, ref pbRecvBuffer);
                                CheckErr(err);

                                if (CheckRespnse(pbRecvBuffer))
                                {
                                    ReadUid(err, reader, pioSendPci, block);
                                }
                            }
                        }
                    }
                    hContext.Release();
                }
                catch (PCSCException ex)
                {
                    Console.WriteLine("Error: "
                                      + ex.Message
                                      + " (" + ex.SCardError.ToString() + ")");
                }
            }
        }
        public bool RegisterCard(string str_id)
        {
            SCardError err;
            IntPtr     pioSendPci;
            bool       status = false;

            try
            {
                bool         store_status = false;
                SCardContext hContext     = EstablishContext();
                string[]     szReaders    = RetrieveReaders(hContext);
                // Create a reader object using the existing context
                SCardReader reader = new SCardReader(hContext);

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

                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];

                bool authvalid = LoadAuth(err, reader, pioSendPci);

                if (authvalid == true)
                {
                    string block = "10";
                    //to authenticate, uses the keys stored in reader (previous step 6 ff) to do authentication. two types of authentication type A = 60 and type B = 61.
                    //FF=class, 86=ins, 00=p1, 00=p2, 05=LC, (00=(version 00 or 01), 00, 08=block no to be authenticated, 61=(key type 60 for A or 61 for B), 00=(key location or number 00~01)) = authentication data bytes.
                    // this APDU is PC/SC V2.07
                    byte[] cmd3 = new byte[] { (byte)0xFF, (byte)0x86, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x00, (byte)int.Parse(block), (byte)0x61, (byte)0x00 };

                    err = reader.Transmit(pioSendPci, cmd3, ref pbRecvBuffer);
                    CheckErr(err);

                    CheckRespnse(pbRecvBuffer);
                    store_status = StoreId(err, reader, pioSendPci, block, str_id);
                }
                if (store_status == true)
                {
                    //database update here
                    pbRecvBuffer = new byte[256];
                    byte[] cmd4 = new byte[] { (byte)0xFF, (byte)0xCA, (byte)0x00, (byte)0x00, (byte)0x00 };

                    err = reader.Transmit(pioSendPci, cmd4, ref pbRecvBuffer);
                    CheckErr(err);
                    string carduid = BitConverter.ToString(pbRecvBuffer.Take(4).ToArray()).Replace("-", string.Empty).ToUpper();
                    if (sdb.AfterCardCreate(Convert.ToInt32(str_id), carduid))
                    {
                        status = true;
                    }
                    else
                    {
                        status = false;
                        throw new Exception("Error During Saving");
                    }
                }
                hContext.Release();
                return(status);
            }
            catch (PCSCException ex)
            {
                MessageBox.Show("Error: "
                                + ex.Message
                                + " (" + ex.SCardError.ToString() + ")");
                return(false);
            }
        }
Beispiel #14
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);
                    }
                }
            }
        }
Beispiel #15
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);
                }
            }
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            try
            {
                string imie;
                string nazwisko;
                string pesel;
                string nr_indeksu;
                // Establish SCard context
                SCardContext hContext = new SCardContext();
                hContext.Establish(SCardScope.System);

                // Retrieve the list of Smartcard readers
                string[] szReaders = hContext.GetReaders();
                if (szReaders.Length <= 0)
                {
                    throw new PCSCException(SCardError.NoReadersAvailable,
                                            "Could not find any Smartcard reader.");
                }

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

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

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

                System.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[] SELECT_MF     = new byte[] { 0x00, 0xA4, 0x00, 0x0C, 0x02, 0x3F, 0x00 };
                byte[] SELECT_DF_T0  = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x07, 0xD6, 0x16, 0x00, 0x00, 0x30, 0x01, 0x01 };
                byte[] SELECT_DF_T1  = new byte[] { 0x00, 0xA4, 0x04, 0x04, 0x07, 0xD6, 0x16, 0x00, 0x00, 0x30, 0x01, 0x01 };
                byte[] SELECT_ELS_T0 = new byte[] { 0x00, 0xA4, 0x00, 0x00, 0x02, 0x00, 0x02 };
                byte[] SELECT_ELS_T1 = new byte[] { 0x00, 0xA4, 0x02, 0x04, 0x02, 0x00, 0x02 };
                byte[] READ_ELS      = new byte[] { 0x00, 0xB0, 0x00, 0x00, 0xFF };

                //--
                byte[] pbRecvBuffer = new byte[256];

                // Send SELECT command
                err = reader.Transmit(pioSendPci, SELECT_MF, ref pbRecvBuffer);
                CheckErr(err);

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

                //--
                pbRecvBuffer = new byte[256];

                // Send SELECT command
                err = reader.Transmit(pioSendPci, SELECT_DF_T0, ref pbRecvBuffer);
                CheckErr(err);

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

                //--
                pbRecvBuffer = new byte[256];

                //--
                pbRecvBuffer = new byte[256];

                // Send SELECT command
                err = reader.Transmit(pioSendPci, SELECT_ELS_T0, ref pbRecvBuffer);
                CheckErr(err);

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

                //--
                pbRecvBuffer = new byte[2048];

                // Send SELECT command
                err = reader.Transmit(pioSendPci, READ_ELS, ref pbRecvBuffer);
                CheckErr(err);
                Console.Write("read_els: ");
                nr_indeksu = "";
                pesel      = "";
                for (int i = 0; i < pbRecvBuffer.Length; i++)
                {
                    //index
                    if (pbRecvBuffer[i] == 0x06 && i < 149 && i > 120)
                    {
                        int a = i;
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 1]);
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 2]);
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 3]);
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 4]);
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 5]);
                        nr_indeksu += Convert.ToChar(pbRecvBuffer[a + 6]);
                    }
                    //koniec index

                    //nazwisko

                    //koniec nazwisko

                    //imie

                    //koniec imie

                    //pesel

                    if (pbRecvBuffer[i] == 0x0B && i > 135 && i < 155)
                    {
                        int a = i;
                        pesel += Convert.ToChar(pbRecvBuffer[a + 1]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 2]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 3]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 4]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 5]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 6]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 7]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 8]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 9]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 10]);
                        pesel += Convert.ToChar(pbRecvBuffer[a + 11]);
                    }
                    //koniec pesel
                    Console.Write(i + "\t");
                    Console.Write("{0:X2} ", pbRecvBuffer[i]);
                    Console.Write("\t" + Convert.ToChar(pbRecvBuffer[i]));
                    Console.WriteLine();
                }
                Console.WriteLine();

                //--

                hContext.Release();
                foreach (byte a in pbRecvBuffer)
                {
                    Console.Write("{0:X2}", a);
                }
                //var str = System.Text.Encoding.Default.GetString(pbRecvBuffer);
                Console.WriteLine("Nr indeksu: " + nr_indeksu);
                Console.WriteLine("Pesel: " + pesel);
                Console.ReadKey();
            }
            catch (PCSCException ex)
            {
                Console.WriteLine("Ouch: "
                                  + ex.Message
                                  + " (" + ex.SCardError.ToString() + ")");
            }
        }
        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); }
        }
Beispiel #18
0
        public bool GetSerialNumber(ref byte[] uid, ref byte uidLen, ref LIB_ERR error)
        {
            bool Result = false;

            error  = LIB_ERR.NO_ERROR;
            uidLen = 0;

            byte[] capdu = new byte[5] {
                0xFF, 0xCA, 0x00, 0x00, 0x00
            };
            byte[] rapdu = new byte[32];

            try
            {
                SCardError ret = reader.Transmit(capdu, ref rapdu);

                Result = (ret == SCardError.Success) &&
                         ((rapdu.Length == 4 + 2) || (rapdu.Length == 7 + 2)) && (rapdu[rapdu.Length - 2] == 0x90) && (rapdu[rapdu.Length - 1] == 0x00);

                if (Result)
                {
                    uidLen = Convert.ToByte(rapdu.Length - 2);

                    uid = new byte[uidLen];

                    Array.Copy(rapdu, 0, uid, 0, uidLen);
                }
                else
                {
                    error = LIB_ERR.GET_CARD_UID_FAILED;
                }
            }
            catch (Exception E)
            {
                error = LIB_ERR.GET_CARD_UID_FAILED;

                Result = false;
            }

            return(Result);
        }
Beispiel #19
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 = 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();
                }
            }
        }
Beispiel #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; }
        }
Beispiel #21
0
        public bool Transmit(byte[] sendBuffer, ref byte[] recvBuffer)
        {
            TS.TraceV("Transmit sendBuffer: \"{0}\".", Helper.ByteArrayToString(sendBuffer));

            return(crdReader.Transmit(sendBuffer, ref recvBuffer) == SCardError.Success);
        }
Beispiel #22
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();
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            try
            {
                // Establish SCard context
                SCardContext hContext = new SCardContext();
                hContext.Establish(SCardScope.System);

                // Retrieve the list of Smartcard readers
                string[] szReaders = hContext.GetReaders();
                if (szReaders.Length <= 0)
                {
                    throw new PCSCException(SCardError.NoReadersAvailable,
                                            "Could not find any Smartcard reader.");
                }

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

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

                // Connect to the card
                SCardError err = reader.Connect(szReaders[0],
                                                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_MF command
                byte[] cmd1 = { 0x00, 0xA4, 0x00, 0x00, 0x02, 0x3F, 0x00 };
                err = reader.Transmit(pioSendPci, cmd1, ref pbRecvBuffer);
                CheckErr(err);

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

                pbRecvBuffer = new byte[256];

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

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

                pbRecvBuffer = new byte[256];

                // Send SELECT_EF_PERS command
                byte[] cmd3 = { 0x00, 0xA4, 0x00, 0x00, 0x02, 0x11, 0x02 };
                err = reader.Transmit(pioSendPci, cmd3, ref pbRecvBuffer);
                CheckErr(err);

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

                pbRecvBuffer = new byte[256];

                // Send READ_BIN command
                byte[] cmd4 = { 0x00, 0xB0, 0x00, 0x00, 0x00 };
                err = reader.Transmit(pioSendPci, cmd4, ref pbRecvBuffer);
                CheckErr(err);

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

                /*
                 * pbRecvBuffer = new byte[256];
                 *
                 * // Send SELECT_DF0 command
                 * byte[] cmd2 = { 0x00, 0xA4, 0x00, 0x00, 0x02, 0x10, 0x00 };
                 * err = reader.Transmit(pioSendPci, cmd2, ref pbRecvBuffer);
                 * CheckErr(err);
                 *
                 * Console.Write("response: ");
                 * for (int i = 0; i < pbRecvBuffer.Length; i++)
                 *  Console.Write("{0:X2} ", pbRecvBuffer[i]);
                 * Console.WriteLine();
                 *
                 * pbRecvBuffer = new byte[256];
                 *
                 * // Send SELECT_EF_ID_Carta command
                 * byte[] cmd3 = { 0x00, 0xA4, 0x00, 0x00, 0x02, 0x10, 0x03 };
                 * err = reader.Transmit(pioSendPci, cmd3, ref pbRecvBuffer);
                 * CheckErr(err);
                 *
                 * Console.Write("response: ");
                 * for (int i = 0; i < pbRecvBuffer.Length; i++)
                 *  Console.Write("{0:X2} ", pbRecvBuffer[i]);
                 * Console.WriteLine();
                 *
                 * pbRecvBuffer = new byte[256];
                 *
                 * // Send READ_BIN command
                 * byte[] cmd4 = { 0x00, 0xB0, 0x00, 0x00, 0x00 };
                 * err = reader.Transmit(pioSendPci, cmd4, ref pbRecvBuffer);
                 * CheckErr(err);
                 *
                 * Console.Write("response: ");
                 * for (int i = 0; i < pbRecvBuffer.Length; i++)
                 *  Console.Write("{0:X2} ", pbRecvBuffer[i]);
                 * Console.WriteLine();
                 * Console.WriteLine(Encoding.UTF8.GetString(pbRecvBuffer));
                 */

                hContext.Release();
            }
            catch (PCSCException ex)
            {
                Console.WriteLine("Ouch: "
                                  + ex.Message
                                  + " (" + ex.SCardError.ToString() + ")");
            }
        }
Beispiel #24
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;
        }
Beispiel #25
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); }
        }
Beispiel #26
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);
        }