Пример #1
0
        /// <summary>
        /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
        /// </summary>
        /// <param name="cmdApdu">Hexadecimal  string containing the command APDU.</param>
        /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
        /// <returns></returns>
        public RespApdu Exchange(string cmdApdu, ushort?expectedSW1SW2)
        {
            byte[]   responseBuffer = this.Exchange(HexEncoding.GetBytes(cmdApdu), expectedSW1SW2);
            RespApdu respApdu       = new RespApdu(responseBuffer);

            return(respApdu);
        }
Пример #2
0
        //this method will open a reader instance and read the nfc device with
        //cmd as its input and the command to run. it will return a string of the result.
        //@params cmd - the command to run
        private string readNFC(CmdApdu cmd)
        {
            PCSCReader reader  = new PCSCReader();
            string     payload = "";

            try
            {
                reader.Connect();
                reader.ActivateCard(GS.SCard.Const.SCARD_SHARE_MODE.Exclusive, GS.SCard.Const.SCARD_PROTOCOL.Tx);

                RespApdu respApdu = reader.Exchange(cmd, 0x9000);

                if (respApdu.SW1SW2 == 0x9000)
                {
                    payload = Encoding.UTF8.GetString(respApdu.Data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                reader.Disconnect();
            }
            return(payload);
        }
Пример #3
0
        /// <summary>
        /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
        /// </summary>
        /// <param name="cmdApdu">The command ADPU.</param>
        /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
        /// <returns>The response APDU.</returns>
        public RespApdu Exchange(CmdApdu cmdApdu, ushort?expectedSW1SW2)
        {
            byte[]   responseBuffer = this.Exchange(cmdApdu.GetBytes(), expectedSW1SW2);
            RespApdu respApdu       = new RespApdu(responseBuffer);

            return(respApdu);
        }
Пример #4
0
        public byte[] RsReset()
        {
            try
            {
                RespApdu respApdu = mReader.Exchange("A4 0A 00 00 08"); // Get Random Number

                //Console.WriteLine("Random  = 0x" + HexFormatting.ToHexString(respApdu.Data, true));
                if (respApdu != null)
                {
                    baRandom  = respApdu.Data;
                    strRandom = HexFormatting.ToHexString(baRandom, true);
                }
                else
                {
                    baRandom = new byte[8];
                    Array.Clear(baRandom, 0, 8);
                }

                return(baRandom);
            }
            catch (WinSCardException ex)
            {
                //Console.WriteLine(ex.WinSCardFunctionName + " Error 0x" +
                //                   ex.Status.ToString("X08") + ": " + ex.Message);
                throw ex;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                throw ex;
            }
        }
Пример #5
0
        /// <summary>
        /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
        /// </summary>
        /// <param name="sendBuffer">The command ADPU.</param>
        /// <param name="sendLength">Length of the command ADPU.</param>
        /// <param name="responseBuffer">The response APDU.</param>
        /// <param name="responseLength">
        /// Supplies the length, in bytes, of the response APDU buffer  and
        /// receives the actual number of bytes received from the smart card.
        /// </param>
        /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
        public void Exchange(byte[] sendBuffer, int sendLength, byte[] responseBuffer, ref int responseLength, ushort?expectedSW1SW2)
        {
            if (sendBuffer == null)
            {
                throw new ArgumentNullException("snd_buf");
            }

            if (responseBuffer == null)
            {
                throw new ArgumentNullException("rec_buf");
            }

            this.SCard.Transmit(sendBuffer, sendLength, responseBuffer, ref responseLength);

            RespApdu respApdu = new RespApdu(responseBuffer, responseLength);

            if (expectedSW1SW2 != null)
            {
                // Verify for a valid response status word SW1SW2.
                if (expectedSW1SW2 != respApdu.SW1SW2)
                {
                    throw new ApduException(this.SCard.TraceSCard, 0, (ushort)expectedSW1SW2, respApdu.SW1SW2);
                }
            }
        }
Пример #6
0
        /// <summary>
        /// The SCardTransmit function sends a service request to the smart card and expects to receive data back from the card.
        /// </summary>
        /// <param name="sendBuffer">
        /// The actual data to be written to the card.
        /// </param>
        /// <param name="sendLength">
        /// The length, in bytes, of the sendBuffer parameter.
        /// </param>
        /// <param name="responseBuffer">
        /// Returned data from the card.
        /// </param>
        /// <param name="responseLength">
        /// Supplies the length, in bytes, of the responseBuffer parameter and receives the actual
        /// number of bytes received from the smart card.
        /// </param>
        public void Transmit(byte[] sendBuffer, int sendLength, byte[] responseBuffer, ref int responseLength)
        {
            SCARD_IO_REQUEST SCARD_PCI;

            SCARD_PCI.dwProtocol  = (uint)activeSCardProtocol;
            SCARD_PCI.cbPciLength = 8;

            Trace.WriteLineIf(this.scardTrace, HexFormatting.Dump("--> C-APDU: 0x", sendBuffer, sendLength, 16, ValueFormat.HexASCII));

            int ret = WinSCardAPIWrapper.SCardTransmit(phCARD, ref SCARD_PCI, sendBuffer,
                                                       sendLength,
                                                       IntPtr.Zero,
                                                       responseBuffer,
                                                       ref responseLength);

            if (ret == 0)
            {
                RespApdu respApdu = new RespApdu(responseBuffer, responseLength);
                Trace.WriteLineIf(scardTrace, respApdu.ToString());
            }
            else
            {
                throw new WinSCardException(scardTrace, "SCard.Transmit", ret);
            }
        }
Пример #7
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                RespApdu respApdu = mPcscReader.Exchange(txtAPDU.Text);

                ml.NewLine();
                ml.AddLine("Send: " + txtAPDU.Text);
                if (respApdu.Data != null && respApdu.Data.Length > 0)
                {
                    //ml.AddLine("Resp: " + HexFormatting.ToHexString(respApdu.Data, true));
                    ml.AddLine(String.Format("Resp({0}B): {1}", respApdu.Data.Length,
                                             HexFormatting.ToHexString(respApdu.Data, true)));
                }
                else
                {
                    ml.AddLine("Resp: (None)");
                }

                ml.AddLine("Status: " + respApdu.SW1SW2.Value.ToString("X4"));

                txtMessage.Text = ml.Text;
            }
            catch (WinSCardException ex)
            {
                txtMessage.Text = ml.AddLine(ex.WinSCardFunctionName + " Error 0x" +
                                             ex.Status.ToString("X08") + ": " + ex.Message);
            }
            catch (Exception ex)
            {
                txtMessage.Text = ml.AddLine(ex.Message);
            }
        }
Пример #8
0
 public void SelectAID()
 {
     try
     {
         RespApdu respApdu = mReader.Exchange("00 A4 04 00 0C A0 00 00 02 83 00 00 08 12 01 07 00"); // SELECT_AID
     }
     catch (WinSCardException ex)
     {
         //Console.WriteLine(ex.WinSCardFunctionName + " Error 0x" +
         //                   ex.Status.ToString("X08") + ": " + ex.Message);
         throw ex;
     }
     catch (Exception ex)
     {
         //Console.WriteLine(ex.Message);
         throw ex;
     }
 }
Пример #9
0
        public static async Task Read()
        {
            PCSCReader reader = new PCSCReader();

            while (true)
            {
                try
                {
                    reader.Connect();
                    reader.ActivateCard();

                    RespApdu respApdu = reader.Exchange("FF CA 00 00 00"); // Get Card UID ...

                    if (respApdu.SW1SW2 == 0x9000)
                    {
                        InvokeScanned("0x" + HexFormatting.ToHexString(respApdu.Data, false));
                        await Task.Delay(1000);
                    }
                }

                catch (WinSCardException ex)
                {
                    InvokeError(ex.WinSCardFunctionName + " Error 0x" + ex.Status.ToString("X08") + ": " + ex.Message);
                    await Task.Delay(1000);
                }

                catch (Exception ex)
                {
                    InvokeError(ex.Message);
                    await Task.Delay(1000);
                }

                finally
                {
                    reader.Disconnect();
                }
            }
        }
Пример #10
0
        public byte[] GetRandom()
        {
            try
            {
                RespApdu respApdu = mReader.Exchange("A4 0A 00 00 08"); // Get Random Number

                //Console.WriteLine("Random  = 0x" + HexFormatting.ToHexString(respApdu.Data, true));
                //if (respApdu != null && respApdu.Data != null)
                if (respApdu.SW1SW2 == 0x9000)
                {
                    baRandom  = respApdu.Data;
                    strRandom = HexFormatting.ToHexString(baRandom, true);
                }
                else
                {
                    //baRandom = new byte[8];
                    //Array.Clear(baRandom, 0, 8);
                    //return null;
                    ushort sw = respApdu.SW1SW2 ?? 0;
                    throw new Exception("GetRandom has not supported. Card's SW = " + sw.ToString("X4"));
                }
                //strRandom = HexFormatting.ToHexString(baRandom, true);

                return(baRandom);
            }
            catch (WinSCardException ex)
            {
                //Console.WriteLine(ex.WinSCardFunctionName + " Error 0x" +
                //                   ex.Status.ToString("X08") + ": " + ex.Message);
                throw ex;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                throw ex;
            }
        }
Пример #11
0
 static void set_initiator_mode()
 {
     //RespApdu get_data = reader.Exchange(APDU_commands["read_register"]);
     //string input_text = Console.ReadLine();
     RespApdu setInit = reader.Exchange(APDU_commands["Tg_Init_as_target"]);
 }
Пример #12
0
 //note 2 self ushort? and Nullable<ushort> are the same
 public RespApdu Exchange(CmdApdu cmdApdu, Nullable<ushort> expectedSW1SW2)
 {
     byte[] responseBuffer = this.Exchange(cmdApdu.GetBytes(), expectedSW1SW2);
     RespApdu respApdu = new RespApdu(responseBuffer);
     return respApdu;
 }
Пример #13
0
 /// <summary>
 /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
 /// </summary>
 /// <param name="cmdApdu">Hexadecimal  string containing the command APDU.</param>
 /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
 /// <returns></returns>
 public RespApdu Exchange(string cmdApdu, ushort? expectedSW1SW2)
 {
     byte[] responseBuffer = this.Exchange(HexEncoding.GetBytes(cmdApdu), expectedSW1SW2);
     RespApdu respApdu = new RespApdu(responseBuffer);
     return respApdu;
 }
Пример #14
0
        /// <summary>
        /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
        /// </summary>
        /// <param name="sendBuffer">The command ADPU.</param>
        /// <param name="sendLength">Length of the command ADPU.</param>
        /// <param name="responseBuffer">The response APDU.</param>
        /// <param name="responseLength">
        /// Supplies the length, in bytes, of the response APDU buffer  and 
        /// receives the actual number of bytes received from the smart card.
        /// </param>
        /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
        public void Exchange( byte[] sendBuffer, int sendLength, byte[] responseBuffer, ref int responseLength, ushort? expectedSW1SW2 )
        {
            if (sendBuffer == null)
            {
                throw new ArgumentNullException( "snd_buf" );
            }

            if (responseBuffer == null)
            {
                throw new ArgumentNullException( "rec_buf" );
            }

            this.SCard.Transmit( sendBuffer, sendLength, responseBuffer, ref responseLength );

            RespApdu respApdu = new RespApdu( responseBuffer, responseLength );

            if (expectedSW1SW2 != null)
            {
                // Verify for a valid response status word SW1SW2.
                if (expectedSW1SW2 != respApdu.SW1SW2)
                {
                    throw new ApduException(this.SCard.TraceSCard, 0, (ushort)expectedSW1SW2, respApdu.SW1SW2);
                }
            }
        }
Пример #15
0
 static void set_buzzer_on()
 {
     RespApdu tassu = reader.Exchange("FF 00 52 00 FF");
 }
Пример #16
0
        public void Transmit( byte[] sendBuffer, int sendLength, byte[] responseBuffer, ref int responseLength )
        {
            SCARD_IO_REQUEST SCARD_PCI;
            SCARD_PCI.dwProtocol = (uint)activeSCardProtocol;
            SCARD_PCI.cbPciLength = 8;

            Trace.WriteLineIf(this.scardTrace, HexFormatting.Dump("--> C-APDU: 0x", sendBuffer, sendLength, 16, ValueFormat.HexASCII));

            int ret = WinSCardAPIWrapper.SCardTransmit( phCARD,ref SCARD_PCI, sendBuffer,
                                                     sendLength,
                                                     IntPtr.Zero,
                                                     responseBuffer,
                                                     ref responseLength);

            if (ret == 0)
            {
                RespApdu respApdu = new RespApdu( responseBuffer, responseLength );
                Trace.WriteLineIf(scardTrace, respApdu.ToString());
            }
            else
            {
                throw new WinSCardException( scardTrace, "SCard.Transmit", ret );
            }
        }
Пример #17
0
        static void Main(string[] args)
        {
            ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener();

            Trace.Listeners.Add(consoleTraceListener);

            reader = new PCSCReader();
            //NdefLibrary.Ndef.NdefMessage message = new NdefLibrary.Ndef.NdefMessage();



            /*WinSCard testi = new WinSCard();
             * testi.Connect(null);*/



            string input_text = "";

            while (input_text != "joo")
            {
                try
                {
                    //reader.SCard.Connect("",SCARD_SHARE_MODE.Direct, SCARD_PROTOCOL.Tx);
                    reader.Connect();

                    //set_buzzer_on();
                    //set_target_mode();

                    reader.ActivateCard();

                    //WinSCard reader = new WinSCard();
                    //testi.Connect(null);

                    //For some reason Direct commands only work after card has been activated (the command above)
                    //Also the reader resets to normal state after it's been unplugged.
                    //TODO: check if mode changes can be made permanent
                    if (!modes_changed)
                    {
                        //Console.WriteLine("YOLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
                        //change_modes_for_reader();
                        modes_changed = true;
                    }

                    RespApdu respApdu = reader.Exchange(APDU_commands["get_card_uid"]); // Get Card UID ...

                    if (respApdu.SW1SW2 == 0x9000)
                    {
                        Console.WriteLine("UID  = 0x" + HexFormatting.ToHexString(respApdu.Data, true));
                    }

                    use_stuff_properly();
                    //RespApdu tespApdu = reader.Exchange(String.Format(APDU_commands["direct_command_prefix"],"18", "D4 86 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")); // Get Card UID ...
                    //RespApdu bespApdu = reader.Exchange(String.Format(APDU_commands["direct_command_prefix"], "18", "D4 40 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")); // Get Card UID ...

                    //message = NdefLibrary.Ndef.NdefMessage.FromByteArray();
                    //message = NdefLibrary.Ndef.NdefMessage.FromByteArray(find_ndef());
                    //parse_record(message);

                    //write_to_tag("meloonis");
                }
                catch (WinSCardException ex)
                {
                    Console.WriteLine(ex.WinSCardFunctionName + " Error 0x" +
                                      ex.Status.ToString("X08") + ": " + ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    reader.Disconnect();
                    Console.WriteLine("Please press any key...");
                    input_text = Console.ReadLine();
                }
            }
        }