Exemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                readerMgr = new ReaderManagement();
                readerMgr.EstablishContext();

                //List all the available readers
SelectReader:
                reader = ListReaders();

                ////Read Card
                CardHolderPublicData card = ReadCard();
                if (card == null)
                {
                    goto SelectReader;
                }

                ////Read Biometric
                ReadBiometric();

                readerMgr.CloseContext();



                Console.Read();
            }
            catch (MiddlewareException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
                Console.Read();
            }
        }
Exemplo n.º 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);
        }
Exemplo n.º 3
0
        public CardHolderPublicDataEx ReadCard()
        {
            ReaderManagement readerMgr = new ReaderManagement();

            readerMgr.EstablishContext();
            readerMgr.DiscoverReaders();
            PCSCReader       selectedReader   = readerMgr.Readers[0];
            bool             IsConnected      = selectedReader.IsConnected();
            bool             isUAE            = ATRSetting.Is_UAE_Card(selectedReader.ATR);
            PublicDataFacade publicDataFacade = selectedReader.GetPublicDataFacade();

            // Step 6 : In order to use EIDA "secure messaging" in "local mode", the function
            // "IDCardWrapper.LoadConfiguration" shall be called to load the "secure messaging modules configurations"
            // from the sm.cfg file "C:\Program Files\EIDA Toolkit\Libs\sm.cfg"
            // Sample configuration of is described in appendix A.
            IDCardWrapper.LoadConfiguration();

            /* Step 7 : Once PCSCReader object is acquired in a CONNECTED state and with right type,
             *      application can extract the EIDA ID Card related information such as Card Serial Number, and Chip Serial Number.
             *      The retrieved information will be in binary format. By using the format conversion functions of the Toolkit,
             *      Developers can convert data from binary format to string representation. Refer to Utils class for a sample conversion implementation. */

            CardInfo cardInfo    = selectedReader.GetCardInfo();
            int      cardVersion = cardInfo.GetCardVersion();

            if (cardVersion < 2)
            {
                throw new System.Exception("خطأ : البطاقة المستخدمة ذات إصدار قديم وغير صالحة للقراءة. برجاء تحديث البطاقة");
            }

            CardHolderPublicDataEx result = publicDataFacade.ReadPublicDataEx(true, true, true, true, false, true, false, true);

            readerMgr.CloseContext();
            return(result);
        }
Exemplo n.º 4
0
 static void Main(string[] args)
 {
     PCSCReader r = new PCSCReader();
     r.NewNdefMessageDetected += r_NewNdefMessageDetected;
     Console.WriteLine("Tag mit NDEF-Message auf Leser legen, um Buzzer zu initialisieren");
     Console.ReadLine();
     r.NewNdefMessageDetected -= r_NewNdefMessageDetected;
 }
Exemplo n.º 5
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            cardReader = new PCSCReader();

            cardReader.CardInserted += new PCSCReader.CardInsertedEventHandler(cardReader_CardInserted);
            cardReader.CardRemoved  += new PCSCReader.CardRemovedEventHandler(cardReader_CardRemoved);

            foreach (string reader in cardReader.Readers)
            {
                toolStripComboBoxReaders.Items.Add(reader);
            }

            try
            {
                toolStripComboBoxReaders.SelectedIndex = 0;
            }
            catch (ArgumentOutOfRangeException)
            {
                // No smart card readers!
            }
        }
Exemplo n.º 6
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();
                }
            }
        }
Exemplo n.º 7
0
 public iPassPSAM(PCSCReader reader)
 {
     mReader = reader;
 }
Exemplo n.º 8
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            try
            {
                #region Steps 1-5

                readerMgr = new ReaderManagement();
                readerMgr.EstablishContext();

                selectedReader = selectReader();
                IsConnected    = selectedReader.IsConnected();
                isUAE          = ATRSetting.Is_UAE_Card(selectedReader.ATR);

                #endregion Steps 1-5

                #region Step 6

                /* Step 6 : In order to use EIDA "secure messaging" in "local mode", the function
                 *      "IDCardWrapper.LoadConfiguration" shall be called to load the "secure messaging modules configurations"
                 *      from the sm.cfg file "C:\Program Files\EIDA Toolkit\Libs\sm.cfg"
                 *      Sample configuration of is described in appendix A. */
                IDCardWrapper.LoadConfiguration();

                #endregion Step 6

                #region Step 7

                /* Step 7 : Once PCSCReader object is acquired in a CONNECTED state and with right type,
                 *      application can extract the EIDA ID Card related information such as Card Serial Number, and Chip Serial Number.
                 *      The retrieved information will be in binary format. By using the format conversion functions of the Toolkit,
                 *      Developers can convert data from binary format to string representation. Refer to Utils class for a sample conversion implementation. */

                CardInfo cardInfo    = selectedReader.GetCardInfo();
                byte[]   csn         = cardInfo.GetCardSerialNumber();
                byte[]   chipSN      = cardInfo.GetChipSerialNumber();
                byte[]   cplc0101    = cardInfo.GetCPLC0101();
                byte[]   cplc9f7f    = cardInfo.GetCPLC9F7F();
                byte[]   isn         = cardInfo.GetIssuerSerialNumber();
                byte[]   irn         = cardInfo.GetIssuerReferenceNumber();
                byte[]   mocSN       = cardInfo.GetMOCSerialNumber();
                byte[]   mocAppState = cardInfo.GetMOCAppletState();
                byte[]   mocAlgVer   = cardInfo.GetMOCAlgorithmVersion();
                byte[]   maxFailed   = cardInfo.GetMaxFailedMatch();
                int      cardVersion = cardInfo.GetCardVersion();
                String   csnHex      = Utils.ByteArrayToHex(csn);

                #endregion Step 7

                #region Step 8

                /* Step 8 : Reading the "Card Holder Public Data", using the "CardHolderPublicData" Class */

                publicDataFacade = selectedReader.GetPublicDataFacade();
                CardHolderPublicData publicData = publicDataFacade.ReadPublicData(true, true, true, true, false);
                byte[] fullNameBin  = publicData.FullName;
                String fullName     = Utils.ByteArrayToUTF8String(fullNameBin);
                byte[] sexBin       = publicData.Sex;
                String sex          = Utils.ByteArrayToUTF8String(sexBin);
                byte[] issueDateBin = publicData.IssueDate;
                String issueDate    = Utils.ByteArrayToStringDate(issueDateBin);
                byte[] photography  = publicData.Photography;
                pictureBox1.Image = (Image) new ImageConverter().ConvertFrom(photography);
                // use publicData.getX as needed
                //…

                #endregion Step 8

                #region Step 9

                /* Step 9 : Reading the "Card Holder Public Data" is extended to support reading additional public data fields
                 *      added in V2 cards such as address, passport information, Company name, Qualification, Field of Study, etc...  */

                CardHolderPublicDataEx publicDataEx = publicDataFacade.ReadPublicDataEx(true, true, true, true, false, true, true, true);
                byte[] fullNameBinEx          = publicDataEx.FullName;
                String fullNameEx             = Utils.ByteArrayToUTF8String(fullNameBin);
                byte[] sexBinEx               = publicDataEx.Sex;
                String sexEx                  = Utils.ByteArrayToUTF8String(sexBin);
                byte[] issueDateBinEx         = publicDataEx.IssueDate;
                String issueDateEx            = Utils.ByteArrayToStringDate(issueDateBin);
                byte[] photographyEx          = publicDataEx.Photography;
                byte[] FieldofStudyEnglishBin = publicDataEx.FieldofStudyEnglish;
                String FieldofStudyEnglish    = Utils.ByteArrayToUTF8String(FieldofStudyEnglishBin);
                byte[] FieldofStudyArabicBin  = publicDataEx.FieldofStudyArabic;
                String FieldofStudyArabic     = Utils.ByteArrayToUTF8String(FieldofStudyArabicBin);

                #endregion

                #region Step 10 "Family Book Data" (Skipped because it needs a special config in sm.cfg)
                /* Step 10 : Reading the "Family Book Data" */

                //FamilyBookDataFacade familyBookDataFacade = selectedReader.GetFamilyBookDataFacade();
                //FamilyBookData familyBookData = familyBookDataFacade.ReadFamilyBookData(false);
                //byte[] firstNameBinChild1 = familyBookData.Child1.FirstNameArabic;
                //String firstNameChild1 = Utils.ByteArrayToUTF8String(firstNameBinChild1);
                #endregion

                #region Step 11 "Verifying Card Genuine in local mode" (Skipped because it needs a special config in sm.cfg)

                /* Step 11 : Verifying Card Genuine in local mode
                 * In order to invoke isCardGenuine() function in the local mode, the sm.cfg configuration file
                 * must be configured as specified in Appendix A, according to the availability of
                 * secure messaging modules (HSM, SAM or multiple SAM, or Software SAM). */

                bool isGenuine = publicDataFacade.IsCardGenuine();

                #endregion



                readerMgr.CloseContext();
            }
            catch (MiddlewareException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader("settings.txt");
                reader_name = file.ReadLine();
                //Console.WriteLine("SETTINGSFILE CONTENT: " + reader_name);
            }
            catch (System.IO.FileNotFoundException)
            {
                System.Environment.Exit(1);
            }


            ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener();

            Trace.Listeners.Add(consoleTraceListener);
            reader = new PCSCReader();
            NdefLibrary.Ndef.NdefMessage message = new NdefLibrary.Ndef.NdefMessage();

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


                if (args[0] == "read")
                {
                    //Console.WriteLine("Initing stuff");
                    //reader.SCard.Connect(reader.SCard.ListReaders()[1], SCARD_SHARE_MODE.Direct, SCARD_PROTOCOL.Default);
                    //Console.WriteLine(reader.SCard.GetSCardCtlCode(3500));
                    reader.Connect(reader_name);
                    Console.WriteLine(reader.SCard.ListReaders()[0]);
                    reader.ActivateCard(SCARD_SHARE_MODE.Shared, SCARD_PROTOCOL.T1);
                    turn_on_antenna();

                    message = NdefLibrary.Ndef.NdefMessage.FromByteArray(find_ndef());
                    Console.WriteLine("rd: " + parse_record(message));

                    //Console.WriteLine("Please press any key...");
                    //string input_text = Console.ReadLine();
                    //turn_off_antenna();
                }
                else if (args[0] == "write" && args.Length == 2)
                {
                    Console.WriteLine("writing to tag: ", args[1]);
                    reader.Connect();
                    reader.ActivateCard(SCARD_SHARE_MODE.Shared, SCARD_PROTOCOL.T1);
                    turn_on_antenna();
                    write_to_tag(args[1]);
                    Console.WriteLine("wrote to tag:" + args[1]);
                }
                else if (args[0] == "list")
                {
                    Console.WriteLine(reader.SCard.ListReaders());
                    System.Environment.Exit(1);
                }
                else
                {
                    Console.WriteLine("Bad arguments");
                    reader.SCard.Disconnect();
                    System.Environment.Exit(1);
                }

                //WinSCard yhteys = new WinSCard();
                //yhteys.Connect(yhteys.ListReaders()[0]);
                //yhteys.Control(0, hex_string_to_byte_array(APDU_commands[]), );


                //write_to_tag(input_text = "Hassulla Tassulla kiva paijaa massua ai että kun on hassua:3");
                //reader.ActivateCard();
                //try_this();
                //set_initiator_mode();


                //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

                //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));
                 * }*/

                //message = NdefLibrary.Ndef.NdefMessage.FromByteArray(find_ndef());
                //parse_record(message);
                //set_initiator_mode();
                //string input_text = Console.ReadLine();
                //System.Environment.Exit(1);
            }
            catch (WinSCardException ex)
            {
                Console.WriteLine(ex.WinSCardFunctionName + " Error 0x" +
                                  ex.Status.ToString("X08") + ": " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //direct_command(APDU_commands["enable_picc_polling"]);
                //turn_off_antenna();
                //Console.WriteLine("Please press any key...");
                //string input_text = Console.ReadLine();
                turn_off_antenna();
                reader.SCard.Disconnect();
                System.Environment.Exit(1);
            }
        }
Exemplo n.º 10
0
        static public byte[] GetKey()
        {
            PCSCReader pcscReader = new PCSCReader();

            pcscReader.Initialize();
            string[] readList;
            readList = PCSCReader.GetPCSCReaderList();
            if (readList != null)
            {
                string len;
                len = readList.Length.ToString();
                if (pcscReader.ConnectReader(readList[0]) == true)
                {
                    byte[] key1Buf     = Encoding.Default.GetBytes(new char[] { '$', 'b', '#', 'D', '0', '*', '!', 'X', '9', 'Q', '1', 'O', 'S', '3', '7', 'c' });
                    byte[] key3Buf     = Encoding.Default.GetBytes(new char[] { '!', 'C', 'm', 'P', 'P', 'H', '3', 'b' });
                    byte[] cmdHaedText = new byte[6] {
                        0x80, 0x08, 0x00, 0x00, 0x11, 0x10
                    };
                    byte[] cmdDateText = new byte[16];//{0x12, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};

                    System.Random rand = new System.Random(unchecked ((int)DateTime.Now.Ticks));
                    rand.NextBytes(cmdDateText);
                    cmdDateText[0] = 0x12;

                    byte[] ecmdDateText = AES.Encrypt(cmdDateText, key1Buf, AES.Mode.ECB, null, AES.Padding.NONE);

                    // for(int i=0; i<ecmdDateText.Length; i++)
                    // {
                    //  Debug.Log("ecmdDateText = " + i+ "  " + ecmdDateText[i].ToString("x"));
                    // }

                    byte[] sendDataBuf = new byte[cmdHaedText.Length + ecmdDateText.Length];
                    //Debug.Log("sendDataBuf.Length = "+ sendDataBuf.Length);
                    Buffer.BlockCopy(cmdHaedText, 0, sendDataBuf, 0, cmdHaedText.Length);//这种方法仅适用于字节数组
                    Buffer.BlockCopy(ecmdDateText, 0, sendDataBuf, cmdHaedText.Length, ecmdDateText.Length);

                    // for(int i=0; i<sendDataBuf.Length; i++)
                    // {
                    //  Debug.Log("1111111111sendDataBuf = " + i+ "  " + sendDataBuf[i].ToString("X"));
                    // }


                    byte[] revBuf = new byte[100];
                    pcscReader.SendCommand(sendDataBuf, revBuf);

                    // for(int i=0; i<revBuf.Length; i++)
                    // {
                    //  Debug.Log("revBuf = " + i+ "  " + revBuf[i].ToString("X"));
                    // }
                    if (revBuf[1] == 0x19)
                    {
                        byte[] revCmdBuf = { 0x00, 0xC0, 0x00, 0x00, 0x19 };
                        pcscReader.SendCommand(revCmdBuf, revBuf);


                        // for(int i=0; i<revBuf.Length; i++)
                        // {
                        //  Debug.Log("3333333333333333333333revBuf = " + i+ "  " + revBuf[i].ToString("X"));
                        // }

                        byte[] ogameKeyBuf = new byte[24];
                        Buffer.BlockCopy(revBuf, 1, ogameKeyBuf, 0, ogameKeyBuf.Length);

                        byte[] deogameKeyBuf = MDES.DESDecrypt(ogameKeyBuf, key3Buf);


                        // for(int i=0; i<cmdDateText.Length; i++)
                        // {
                        //  Debug.Log("44444444444444444444cmdDateText = " + i+ "  " + cmdDateText[i].ToString("X"));
                        // }

                        // for(int i=0; i<deogameKeyBuf.Length; i++)
                        // {
                        //  Debug.Log("------------------------------------------gameKey = " + i+ "  " + deogameKeyBuf[i].ToString("X"));
                        // }

                        if ((deogameKeyBuf[16] == cmdDateText[0]) && (deogameKeyBuf[17] == cmdDateText[1]) && (deogameKeyBuf[18] == cmdDateText[2]) && (deogameKeyBuf[19] == cmdDateText[3]))
                        {
                            pcscReader.DisConnect();
                            byte[] gameKeyBuf = new byte[16];
                            Buffer.BlockCopy(deogameKeyBuf, 0, gameKeyBuf, 0, 16);

                            return(gameKeyBuf);
                        }

                        //byte[] retBuf = new byte[16];
                        //Buffer.BlockCopy(gameKey, 0, retBuf, 0, 16);

                        pcscReader.DisConnect();

                        return(null);
                    }
                }
            }
            pcscReader.DisConnect();
            return(null);
        }
Exemplo n.º 11
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();
                }
            }
        }