public InitCardWindow(String readerName)
    {
      InitializeComponent();
      this.smartCard = new SmartCard(readerName, "1234");

      BigInteger.TryParse(this.pString, out p);
      BigInteger.TryParse(this.qString, out q);

      this.pValue.Text = this.p.ToString();
      this.qValue.Text = this.q.ToString();
      this.pinValue.Content = pin;
    }
 public BlobStoreTest()
 {
   LoggerUtils.setupLoggers();
   List<CardInfo> lst = SmartCardUtils.GetReaderNames();
   String readerName = lst[0].ReaderName;
   smartCard = new SmartCard(readerName, pin);
   CardMode mode = this.smartCard.GetCardMode();
   if (mode != CardMode.ROOT)
   {
     this.smartCard.SetCardInRootMode();
   }
   BigInteger.TryParse(pString, out p);
   BigInteger.TryParse(qString, out q);
   KeyPair pq = new KeyPair(p, q);
   String puk = this.smartCard.InitDevice(pq, pin);
 }
    /// <summary>
    /// Constructs a new SampleDevice instance.
    /// </summary>
    /// <param name="gq">The group construction.</param>
    /// <param name="gd">The device generator.</param>
    public SmartCardDevice(GroupDescription gq, GroupElement gd, SmartCardParams smartCardParam)
    {
      pin = smartCardParam.pin;
      credID = smartCardParam.credID;
      groupID = smartCardParam.groupID;
      proverID = smartCardParam.proverID;
     
      // As SnartCardDevice do not provide a way to lookup card readr names
      // we provide a small potion of logic to lookup a card and cardreader
      List<CardInfo> cardInfoList = SmartCardUtils.GetReaderNames();
      // loop until we find a card with the status of "working mode". if none found
      // throw
      String readerName = null;
      foreach (CardInfo i in cardInfoList)
      {
        if (i.CardMode == (int)CardMode.WORKING)
        {
          readerName = i.ReaderName;
          break;
        }
      }
      if (readerName == null)
      {
        // TODO create a better exception
        throw new Exception("No card founds in working mode");
      }
      bool doTimeProfile = ParseConfigManager.doTimeProfile();
      this.device = new SmartCard(readerName, pin, doTimeProfile);
      // As the group and generator is set from the java init service we will only verify
      // TODO fix to see that group 0 is set on the hw smartcard.
      //if (!this.device.IsGeneratorSet(groupID))
      //{
        // TODO Find better exception
       // throw new Exception("No generator is set on the card to use this group");
      //}

      this.Gq = gq;
      this.Gd = gd;
    }
        private static async Task HandleCard(SmartCard args)
        {
            try
            {
                var newConnection = args.CreateMiFareCard();
                lock (cardConnectionLock)
                {
                    if (currentConnection != null)
                    {
                        currentConnection.Dispose();
                        currentCardId = null;
                        currentConnection = null;
                    }
                    currentConnection = newConnection;
                }

                var cardId = await currentConnection.GetCardInfo();
               
                Debug.WriteLine("Connected to card\r\nPC/SC device class: {0}\r\nCard name: {1}", cardId.PcscDeviceClass, cardId.PcscCardName);

                if (cardId.PcscDeviceClass == DeviceClass.StorageClass
                           && (cardId.PcscCardName == CardName.MifareStandard1K || cardId.PcscCardName == CardName.MifareStandard4K))
                {

                    Debug.WriteLine("MiFare Classic card detected");

                    var uid = await currentConnection.GetUid();
                    currentCardId = uid.ByteArrayToString();
                    
                    Debug.WriteLine("UID: " + currentCardId);

                }
                else
                {
                    throw new NotImplementedException("Card type is not implemented");
                }
                

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                
            }
        }
Example #5
0
 public Pn532UsbScWrapper(SmartCard reader)
 {
     _reader = reader;
 }
Example #6
0
 public Pn532UsbScWrapper()
 {
     _nfc    = null;
     _reader = null;
 }
Example #7
0
        private async Task HandleCard(SmartCard card)
        {
            try
            {
                string uid = string.Empty;

                // Connect to the card
                using (SmartCardConnection connection = await card.ConnectAsync())
                {
                    // Try to identify what type of card it was
                    IccDetection cardIdentification = new IccDetection(card, connection);
                    await cardIdentification.DetectCardTypeAync();

                    LogMessage("Connected to card\r\nPC/SC device class: " + cardIdentification.PcscDeviceClass.ToString());
                    LogMessage("Card name: " + cardIdentification.PcscCardName.ToString());
                    LogMessage("ATR: " + BitConverter.ToString(cardIdentification.Atr));

                    if ((cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass) &&
                        (cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightC ||
                         cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralight ||
                         cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightEV1))
                    {
                        // Handle MIFARE Ultralight
                        MifareUltralight.AccessHandler mifareULAccess = new MifareUltralight.AccessHandler(connection);

                        // Each read should get us 16 bytes/4 blocks, so doing
                        // 4 reads will get us all 64 bytes/16 blocks on the card
                        for (byte i = 0; i < 4; i++)
                        {
                            byte[] response = await mifareULAccess.ReadAsync((byte)(4 * i));

                            LogMessage("Block " + (4 * i).ToString() + " to Block " + (4 * i + 3).ToString() + " " + BitConverter.ToString(response));
                        }

                        byte[] responseUid = await mifareULAccess.GetUidAsync();

                        uid = BitConverter.ToString(responseUid);
                    }
                    else if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.MifareDesfire)
                    {
                        // Handle MIFARE DESfire
                        Desfire.AccessHandler desfireAccess = new Desfire.AccessHandler(connection);
                        Desfire.CardDetails   desfire       = await desfireAccess.ReadCardDetailsAsync();

                        LogMessage("DesFire Card Details:  " + Environment.NewLine + desfire.ToString());
                    }
                    else if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass &&
                             cardIdentification.PcscCardName == Pcsc.CardName.FeliCa)
                    {
                        // Handle Felica
                        LogMessage("Felica card detected");
                        var felicaAccess = new Felica.AccessHandler(connection);
                        var uidBits      = await felicaAccess.GetUidAsync();

                        uid = BitConverter.ToString(uidBits);
                    }
                    else if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass &&
                             (cardIdentification.PcscCardName == Pcsc.CardName.MifareStandard1K || cardIdentification.PcscCardName == Pcsc.CardName.MifareStandard4K))
                    {
                        // Handle MIFARE Standard/Classic
                        LogMessage("MIFARE Standard/Classic card detected");
                        var mfStdAccess = new MifareStandard.AccessHandler(connection);
                        var uidBits     = await mfStdAccess.GetUidAsync();

                        uid = BitConverter.ToString(uidBits);
                    }
                    else if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass &&
                             (cardIdentification.PcscCardName == Pcsc.CardName.ICODE1 ||
                              cardIdentification.PcscCardName == Pcsc.CardName.ICODESLI ||
                              cardIdentification.PcscCardName == Pcsc.CardName.iCodeSL2))
                    {
                        // Handle ISO15693
                        LogMessage("ISO15693 card detected");
                        var iso15693Access = new Iso15693.AccessHandler(connection);
                        var uidBits        = await iso15693Access.GetUidAsync();

                        uid = BitConverter.ToString(uidBits);
                    }
                    else
                    {
                        // Unknown card type
                        // Note that when using the XDE emulator the card's ATR and type is not passed through, so we'll
                        // end up here even for known card types if using the XDE emulator

                        // Some cards might still let us query their UID with the PC/SC command, so let's try:
                        var apduRes = await connection.TransceiveAsync(new Pcsc.GetUid());

                        if (!apduRes.Succeeded)
                        {
                            LogMessage("Failure getting UID of card, " + apduRes.ToString());
                        }
                        else
                        {
                            uid = BitConverter.ToString(apduRes.ResponseData);
                        }
                    }
                }
                CardDataEvent?.Invoke(uid);
            }
            catch (Exception ex)
            {
                LogMessage("Exception handling card: " + ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #8
0
        JObject readCardData(SmartCard smc, string r, string pin)
        {
            try
            {
                smc = new SmartCard();
                // siamo all'interno dell'event handler del form, quindi per aggiornare la label devo eseguire il Message Loop
                Application.DoEvents();
                // avvio la connessione al lettore richiedendo l'accesso esclusivo al chip
                if (!smc.Connect(r, Share.SCARD_SHARE_EXCLUSIVE, Protocol.SCARD_PROTOCOL_T1))
                {
                    System.Diagnostics.Debug.WriteLine("Errore in connessione: " + smc.LastSCardResult.ToString("X08"));
                    label1.Text = "Errore in connessione: " + smc.LastSCardResult.ToString("X08");
                    JObject j = new JObject(); j.Add("Exception", "Errore in connessione: " + smc.LastSCardResult.ToString("X08"));
                    jsonToReturn = j;
                    return(j);
                }

                // Creo l'oggetto EAC per l'autenticazione e la lettura, passando la smart card su cui eseguire i comandi
                EAC a = new EAC(smc);
                // Verifico se il chip è SAC
                if (a.IsSAC())
                {
                    // Effettuo l'autenticazione PACE.
                    // In un caso reale prima di avvare la connessione al chip dovrei chiedere all'utente di inserire il CAN
                    txtStatus.Text += "chip SAC - PACE" + "\n";
                    a.PACE(pin);
                    // a.PACE("641230", new DateTime(2022, 12, 30), "CA00000AA");
                }
                else
                {
                    // Per fare BAC dovrei fare la scansione dell'MRZ e applicare l'OCR all'imagine ottenuta. In questo caso ritorno errore.
                    // a.BAC("641230", new DateTime(2022, 12, 30), "CA00000AA");                    //a.BAC()
                    // label1.Text = "BAC non disponibile";
                    txtStatus.Text += "chip BAC" + "\n";
                }

                // Per poter fare la chip authentication devo prima leggere il DG14
                var dg14 = a.ReadDG(DG.DG14);

                // Effettuo la chip authentication
                a.ChipAuthentication();

                ASN1Tag asn = ASN1Tag.Parse(a.ReadDG(DG.DG11));
                //creao il json da inviare alla webform
                var jsonObject = new JObject();
                jsonObject.Add("nis", "?");

                string nomeCognome = new ByteArray(asn.Child(1).Data).ToASCII.ToString();
                jsonObject.Add("surname", nomeCognome.Split(new[] { "<<" }, StringSplitOptions.None)[0]);
                jsonObject.Add("name", nomeCognome.Split(new[] { "<<" }, StringSplitOptions.None)[1]);

                string codiceFiscale = new ByteArray(asn.Child(2).Data).ToASCII.ToString();
                jsonObject.Add("fiscal_code", codiceFiscale);

                string residenza = new ByteArray(asn.Child(4).Data).ToASCII.ToString();
                jsonObject.Add("res_addr", residenza.Split('<')[0]);
                jsonObject.Add("res_place", residenza.Split('<')[1]);
                jsonObject.Add("res_prov", residenza.Split('<')[2]);

                string birth = new ByteArray(asn.Child(3).Data).ToASCII.ToString();
                jsonObject.Add("birth_place", birth.Split('<')[0]);
                jsonObject.Add("birth_prov", birth.Split('<')[1]);

                jsonObject.Add("birth_date", CF.GetDateFromFiscalCode(codiceFiscale));


                txtStatus.Text += jsonObject.ToString();

                // Leggo il DG2 contenente la foto
                var dg2 = a.ReadDG(DG.DG2);

                // Disconnessione dal chip
                smc.Disconnect(Disposition.SCARD_RESET_CARD);
                jsonToReturn = jsonObject;
                return(jsonObject);
            }
            catch (Exception e)
            {
                txtStatus.Text += "Eccezione: " + e.Message;
                JObject j = new JObject(); j.Add("Exception", e.Message);
                jsonToReturn = j;
                return(j);
            }
        }
Example #9
0
 public MifareUltralightEtcTag(SmartCard card)
 {
     m_card = card;
 } // ctor
 internal CardRemovedEventArgs(SmartCard card)
     : base(card)
 {
 }
Example #11
0
        public static bool InsertSmartCardID(string smartCardID, out string response)
        {
            try
            {
                var sc = new SmartCard();
                string hashedSmartID = PasswordHash.MD5Hash(smartCardID);
                using (var context = new PrinterMonitorDBEntities())
                {
                    // Query for the token
                    sc = context.SmartCards
                                    .Where(t => t.HashedSmartCardID == hashedSmartID)
                                    .FirstOrDefault();
                }

                if (sc != null)
                {
                    response = "Smard Card ID has been registered already";
                    return false;
                }
                else
                {
                    var smartCard = new SmartCard();
                    smartCard.Allocated = false;
                    smartCard.EncryptedSmartCardID = Crypter.Encrypt(System.Configuration.ConfigurationManager.AppSettings.Get("ekey"), smartCardID);
                    smartCard.HashedSmartCardID = PasswordHash.MD5Hash(smartCardID);

                    using (var context = new PrinterMonitorDBEntities())
                    {
                        context.SmartCards.Add(smartCard);
                        context.SaveChanges();
                    }

                    response = "Successful";
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #12
0
        /// <summary>
        /// Sample code to hande a couple of different cards based on the identification process
        /// </summary>
        /// <returns>None</returns>
        private async Task HandleCard(SmartCard card)
        {
            try
            {
                // Connect to the card
                using (SmartCardConnection connection = await card.ConnectAsync())
                {
                    // Try to identify what type of card it was
                    IccDetection cardIdentification = new IccDetection(card, connection);
                    await cardIdentification.DetectCardTypeAync();

                    LogMessage("Connected to card\r\nPC/SC device class: " + cardIdentification.PcscDeviceClass.ToString());
                    LogMessage("Card name: " + cardIdentification.PcscCardName.ToString());
                    LogMessage("ATR: " + BitConverter.ToString(cardIdentification.Atr));

                    if ((cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass) &&
                        (cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightC ||
                         cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralight ||
                         cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightEV1))
                    {
                        // Handle MIFARE Ultralight
                        MifareUltralight.AccessHandler mifareULAccess = new MifareUltralight.AccessHandler(connection);

                        await mifareULAccess.ReadCapsAsync();

                        if (!mifareULAccess.isNTag21x)
                        {
                            var ignored1 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                            {
                                var msgbox = new Windows.UI.Popups.MessageDialog("This application only works with the NXP NTAG21x line of NFC chips. Sorry.");
                                msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
                                await msgbox.ShowAsync();
                            });

                            return;
                        }

                        bool authenticated = false;

                        try
                        {
                            await mifareULAccess.AuthenticateWithPassword(PasswordStatic, PasswordAcknowledgeStatic);

                            authenticated = true;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception sending provisioning password: "******"Exception sending provisioning password: "******"ReadCount:  " + responseAccess.ToString());

                            var ignored2 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                            {
                                accessCount.Text = responseAccess.ToString();
                            });

                            accessCountEnabled = true;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception sending Getting Access Count: " + ex);
                        }

                        if (!accessCountEnabled)
                        {
                            var ignored3 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                            {
                                accessCount.Text             = " ";
                                accessCountEnable.Visibility = Visibility.Visible;
                            });

                            await mifareULAccess.EnableAccessCountAsync();
                        }

                        for (byte i = 0; i < mifareULAccess.Blocks; i++)
                        {
                            byte[] response = await mifareULAccess.ReadAsync((byte)(4 * i));

                            for (byte y = 0; y < 4; y++)
                            {
                                byte[] buf4 = new byte[4];
                                Array.Copy(response, y * 4, buf4, 0, 4);
                                LogMessage((i * 4 + y).ToString("x2") + ": " + BitConverter.ToString(buf4));
                            }
                        }

                        byte[] responseUid = await mifareULAccess.GetUidAsync();

                        string uidString = BitConverter.ToString(responseUid);
                        LogMessage("UID:  " + uidString);

                        var ignored4 = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            uid.Text            = uidString;
                            UidPanel.Visibility = Visibility.Visible;
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception handling card: " + ex.ToString());
            }
        }
Example #13
0
        public MiFareWin32CardReader(SmartCard smartCard, ICollection <SectorKeySet> keys) : base(keys)
        {
            this.smartCard = smartCard;

            initialization = Initialize();
        }
        private void _pollingTimer_Tick(object sender, EventArgs e)
        {
            int readerLen = 0,
                dwState = 0,
                dwProtocol = 0;

            _receivedBuffer = new byte[32];

            var atrLen = _receivedBuffer.Length;

            Connect();

            _returnCode = ModWinsCard.SCardStatus(_hCard, _name, ref readerLen, ref dwState, ref dwProtocol, ref _receivedBuffer[0], ref atrLen);

            if (_returnCode != ModWinsCard.SCARD_S_SUCCESS && ShouldChangeState(ReaderCardState.NO_CARD_DETECTED))
            {
                _smartCard = null;

                OnReaderCardStateChanged(new ReaderCardStateChangedEventArgs(ReaderCardState.NO_CARD_DETECTED));
            }
            else
            {
                try
                {
                    var card = new SmartCard(atrLen, _receivedBuffer);

                    if (ShouldChangeState(ReaderCardState.CARD_PRESENT) || card.Type != _smartCard.Type)
                    {
                        if (_smartCard == null)
                        {
                            _smartCard = card;
                        }
                        else
                        {
                            _smartCard = _smartCard.Type == card.Type ? _smartCard : card;
                        }

                        OnReaderCardStateChanged(new ReaderCardStateChangedEventArgs(ReaderCardState.CARD_PRESENT));
                    }
                }
                catch (Exception)
                {
                    _smartCard = null;

                    OnReaderCardStateChanged(new ReaderCardStateChangedEventArgs(ReaderCardState.NO_CARD_DETECTED));
                }
            }
        }
Example #15
0
        /*
         *
         * @throws SmartCardException
         */

        /**
         * BaseSigner interface for the requested certificate. Do not forget to logout after your crypto
         * operation finished
         * @param aCardPIN
         * @param aCert
         * @return
         * @throws SmartCardException
         */

        public SmartCardManager()
        {
            try
            {
                LOGGER.Debug("New SmartCardManager will be created");
                String terminal;

                int      index     = 0;
                String[] terminals = SmartOp.getCardTerminals();

                if (terminals == null || terminals.Length == 0)
                {
                    MesajiIsle("Kart takılı kart okuyucu bulunamadı (SmartCardManager)", 1);
                    Program.KartOkuyucuYok = 1;
                    return;
                    // throw new SmartCardException("Kart takılı kart okuyucu bulunamadı");
                }

                LOGGER.Debug("Kart okuyucu sayısı : " + terminals.Length);
                if (terminals.Length != Program.TerminalSayisi && Program.TerminalSayisi != 0)
                {
                    MesajiIsle("Kart seçildikten sonra imzalama aşamasında yeni kart okuyucu takıldı.", 1);
                    Program.KartOkuyucuYok = 1;
                    return;
                }

                // MesajiIsle("Bilgi 1 - Terminal: " + terminal, 0);
                try
                {  // karttipi bastan parametre ile gelmisse
                    if (Program.ParamCardType != "")
                    {
                        Program.ParamSlotID = SmartOp.findSlotNumber(CardTypeConverter.AsCardType(Program.ParamCardType)).ToString();
                        bsc           = new P11SmartCard(CardTypeConverter.AsCardType(Program.ParamCardType));
                        mSerialNumber = StringUtil.ToString(bsc.getSerial(Convert.ToInt64(Program.ParamSlotID)));
                        bsc.openSession(Convert.ToInt64(Program.ParamSlotID));

                        Program.CardType = Program.ParamCardType;
                    }
                    else
                    {
                        if (terminals.Length == 1)
                        {
                            terminal = terminals[index];
                        }
                        else
                        {
                            index    = askOption(null, null, terminals, "Okuyucu Listesi", new String[] { "Tamam" });
                            terminal = terminals[index];
                        }
                        // burada try catch gerek olmadan kart tipi ve slot id tesbit ediliyor...
                        // ama sadece akis icin calisiyor, safesign da calismadi
                        Pair <long, CardType> slotAndCardType = SmartOp.getSlotAndCardType(terminal);
                        //  MesajiIsle("Bilgi 2 - Terminal: " + terminal + " SmartCard Type: " + slotAndCardType.getmObj2().ToString() + " SlotID: " + slotAndCardType.getmObj1().ToString(), 0);
                        // bulunan kart type kullanilarak kart yapisi olusturuluyor
                        bsc = new P11SmartCard(slotAndCardType.getmObj2());
                        // olusturulan kart yapisi bulunan slotid kullanilarak aciliyor
                        bsc.openSession(slotAndCardType.getmObj1());
                        Program.ParamSlotID = slotAndCardType.getmObj1().ToString();
                        Program.CardType    = slotAndCardType.getmObj2().ToString();
                        Program.Terminal    = terminal;
                    }
                }
                catch
                {
                    // etugra
                    //bsc = new P11SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SAFESIGN);
                    //bsc.openSession(52481);
                    //MessageBox.Show(index.ToString() + " nolu terminal serino");
                    //MessageBox.Show(StringUtil.ToString(bsc.getSerial()));
                    //MessageBox.Show("Serino gösterdi");
                    // continue;
                    // bu slot id belirleme ve open session kismini, manuel imzalamada signerhelp icerisine aldim, yoksa
                    // burada acilan sessioni gormuyordu bir sekilde. bu kisim sertifika okuma ozelligi cozulebilirse iptal edilebilir belki...

                    long[] PresentSlots;
                    // long[] PresentSerials;
                    try
                    {
                        sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.AKIS);
                        if (Program.ParamSlotID == "")
                        {
                            FindSlotID();
                        }

                        string s = new string(sc.getSlotInfo(Convert.ToInt64(Program.ParamSlotID)).slotDescription);
                        s = new string(sc.getSlotInfo(Convert.ToInt64(Program.ParamSlotID)).manufacturerID);
                        s = sc.getSlotInfo(Convert.ToInt64(Program.ParamSlotID)).ToString();
                        // MesajiIsle("slotDescription (SlotID(" +Program.ParamSlotID+"): "+ s, 0);
                        //Program.ParamSlotIndex = index.ToString();
                        Program.CardType = sc.getCardType().ToString();
                        bsc = new P11SmartCard(sc.getCardType());
                        // MesajiIsle("Bilgi 3 - SmartCard Type: " + sc.getCardType().ToString() + " SlotID: " + Program.ParamSlotID, 0);
                        bsc.openSession(Convert.ToInt64(Program.ParamSlotID));
                    }
                    catch
                    {
                        try
                        {
                            sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SAFESIGN);
                            if (Program.ParamSlotID == "")
                            {
                                FindSlotID();
                            }

                            string s = new string(sc.getSlotInfo(Convert.ToInt64(Program.ParamSlotID)).slotDescription);
                            // MesajiIsle("slotDescription (SlotID(" +Program.ParamSlotID+"): "+ s, 0);
                            //Program.ParamSlotIndex = index.ToString();
                            Program.CardType = sc.getCardType().ToString();
                            bsc = new P11SmartCard(sc.getCardType());
                            // MesajiIsle("Bilgi 3 - SmartCard Type: " + sc.getCardType().ToString() + " SlotID: " + Program.ParamSlotID, 0);
                            bsc.openSession(Convert.ToInt64(Program.ParamSlotID));
                        }
                        catch
                        {
                            try
                            {
                                sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.GEMPLUS);
                            }
                            catch
                            {
                                try
                                {
                                    sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.TKART);
                                }
                                catch
                                {
                                    try
                                    {
                                        sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.ALADDIN);
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SEFIROT);
                                            //PresentSlots = sc.getTokenPresentSlotList(); // tokenli slot listesini al
                                            //for (m = 0; m < PresentSlots.Length; m++)
                                            //{
                                            //    ListSmartCard.Add(new P11SmartCard(sc.getCardType()));
                                            //    ListSmartCard[index].openSession(PresentSlots[m]); // etugra icin 52481
                                            //    tekkartSerialNumber = StringUtil.ToString(ListSmartCard[index].getSerial());
                                            //    // sertifika getirme islemi
                                            //    ImzaSertifikasiGetirTek(true, false, index);
                                            //    PresentSlots[m].ToString();
                                            //    index = index + 1;
                                            //}
                                        }
                                        catch
                                        { }
                                    }
                                }
                            }
                        }
                    }
                    if (sc != null)
                    {
                        PresentSlots = sc.getTokenPresentSlotList(); // tokenli slot listesini al
                        // PresentSerials = sc.getTokenSerialNo();
                        // secim kutusu haline getirerek slotid al
                        index = 0;
                        // long SlotID = 0;
                        if (PresentSlots.Length == 1)
                        {
                            Program.ParamSlotID = PresentSlots[index].ToString();
                        }
                        else
                        {
                            Program.ParamSlotID = askOptionValue(null, null, PresentSlots, "Slot Listesi", new String[] { "Tamam" });
                        }
                        // sc.getSlotInfo(slots[0]).slotDescription;
                        string s = new string(sc.getSlotInfo(Convert.ToInt64(Program.ParamSlotID)).slotDescription);
                        // MesajiIsle("slotDescription (SlotID(" +Program.ParamSlotID+"): "+ s, 0);
                        //Program.ParamSlotIndex = index.ToString();
                        Program.CardType = sc.getCardType().ToString();
                        bsc = new P11SmartCard(sc.getCardType());
                        // MesajiIsle("Bilgi 3 - SmartCard Type: " + sc.getCardType().ToString() + " SlotID: " + Program.ParamSlotID, 0);
                        bsc.openSession(Convert.ToInt64(Program.ParamSlotID));

                        //bsc.openSession(SlotID);
                        //MessageBox.Show("bsc.login(5255)");
                        //bsc.login("5255");
                        //MessageBox.Show("login ok");
                    }
                    else
                    {
                        MesajiIsle("Kart tipi belirlenemedi", 0);
                    }
                }

                mSerialNumber = StringUtil.ToString(bsc.getSerial());
                mSlotCount    = terminals.Length;
            }
            catch (SmartCardException e)
            {
                throw e;
            }
            catch (Exception exx)
            {
                MessageBox.Show("Pkcs11 exception", exx.Message);
            }
        }
Example #16
0
        static void Main()
        {
            SimulatedReaders = new Dictionary <string, ReaderSettings>();
            try
            {
                RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\VirtualSmartCard\RemoteReaders");
                foreach (var name in regKey.GetSubKeyNames())
                {
                    var readerKey = regKey.OpenSubKey(name);
                    var reader    = ReaderSettings.GetSettings(readerKey);
                    SimulatedReaders[reader.Name] = reader;
                    readerKey.Close();
                }
                regKey.Close();
            }
            catch {}


            SmartCard sc = new SmartCard();
            var       s  = sc.ListReaders();

            foreach (String r in s)
            {
                ReaderSettings settings = null;
                sc.Connect(r, SmartCard.share.SCARD_SHARE_DIRECT, SmartCard.protocol.SCARD_PROTOCOL_UNDEFINED);
                try
                {
                    byte[] isSimulated = sc.GetAttrib(0x7a009);
                    if (isSimulated != null)
                    {
                        int readerType = isSimulated[0];
                        if (readerType == 0)
                        {
                            var    pipeSettings = new PipeReaderSettings();
                            byte[] data;
                            pipeSettings.PipeName      = Encoding.ASCII.GetString((data = sc.GetAttrib(0x07a00a)), 0, data.Length - 1);
                            pipeSettings.EventPipeName = Encoding.ASCII.GetString((data = sc.GetAttrib(0x07a00b)), 0, data.Length - 1);
                            pipeSettings.Host          = ".";
                            settings = pipeSettings;
                        }
                        else if (readerType == 1)
                        {
                            var    tcpSettings = new TcpIpReaderSettings();
                            byte[] data;
                            tcpSettings.Port      = ((data = sc.GetAttrib(0x07a00c))[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24));
                            tcpSettings.EventPort = ((data = sc.GetAttrib(0x07a00d))[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24));
                            tcpSettings.Host      = "127.0.0.1";
                            settings = tcpSettings;
                        }
                    }

                    settings.Name       = r;
                    settings.IsRemote   = false;
                    SimulatedReaders[r] = settings;
                }
                catch { }

                finally
                {
                    sc.Disconnect(SmartCard.disposition.SCARD_LEAVE_CARD);
                }
            }


            ScanForCards();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Main());
        }
Example #17
0
        private async Task CardDetectionLoop(CancellationToken token)
        {

            await Task.Delay(1, token)
                      .ConfigureAwait(false); // resume on threadpool thread

            while (!token.IsCancellationRequested)
            {
                try
                {
                    var currentState = new SCARD_READERSTATE
                    {
                        RdrName = Name,
                        RdrCurrState = Constants.SCARD_STATE_UNAWARE,
                        RdrEventState = 0

                    };
                    const int readerCount = 1;
                    const int timeout = 0;

                    var retval = SafeNativeMethods.SCardGetStatusChange(hContext, timeout, ref currentState, readerCount);

                    if (retval == 0 && currentState.ATRLength > 0)
                    {
                        // Card inserted
                        if (!cardInserted)
                        {
                            cardInserted = true;

                            OnDisconnect(); // clean up if needed


                            var card = new SmartCard(hContext, Name, currentState.ATRValue);
                            if (Interlocked.CompareExchange(ref currentCard, card, null) == null)
                            {
                                // card was not inserted, now it is
                                // Raise on another thread to not block this loop
                                var evt = CardAdded;
                                if (evt != null)
                                {
                                    Task.Run(() => evt(this, new CardAddedEventArgs(card)));
                                }
                            }
                        }
                    }
                    else
                    {
                        // Card removed
                        if (cardInserted)
                        {
                            cardInserted = false;

                            // HACK: Let our tranceive method know it's gone for one buggy reader
            
                            // bug in the 5427 CK reader
                            if (Name.Contains("5427 CK"))
                            {
                                SmartCardConnectionExtension.IsFirstConnection = false;
                            }

                            OnDisconnect();
                        }
                    }

                    await Task.Delay(250, token);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception from card monitor thread: " + ex);
                }
            }
        }
 internal CardAddedEventArgs(SmartCard card)
     : base(card)
 {
 }
 internal CardEventArgs(SmartCard card)
 {
     SmartCard = card;
 }
        public MiFareWin32CardReader(SmartCard smartCard, IReadOnlyCollection<SectorKeySet> keys) : base(keys)
        {
            this.smartCard = smartCard;

            initialization = Initialize();
        }
Example #21
0
        public static bool UpdateSmartCardID(long smartCardID, long userID, bool status)
        {
            try
            {
                var sc = new SmartCard();
                var user = new User();
                using (var context = new PrinterMonitorDBEntities())
                {
                    sc = context.SmartCards
                                    .Where(t => t.ID == smartCardID)
                                    .FirstOrDefault();

                    user = context.Users
                                    .Include(u => u.SmartCard)
                                    .Where(t => t.ID == userID)
                                    .FirstOrDefault();
                }

                if (sc != null && user != null)
                {
                    sc.Allocated = status;

                    if (status)
                    {
                        if (user.SmartCard != null)
                            throw new Exception(string.Format("User {0} has a smart card allocated to it already", user.Username));

                        user.SmartCardID = smartCardID;
                    }
                    else
                    {
                        user.SmartCard = null;
                        sc.Users = null;
                        user.SmartCardID = null;
                    }

                    using (var context = new PrinterMonitorDBEntities())
                    {
                        //Transaction block
                        using (var transaction = context.Database.BeginTransaction())
                        {
                            try
                            {
                                context.Entry(user).State = EntityState.Modified;
                                context.SaveChanges();

                                context.Entry(sc).State = EntityState.Modified;
                                context.SaveChanges();

                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw ex;
                            }
                        }

                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public SetVirginMode(String readerName)
 {
     InitializeComponent();
     this.device = new SmartCard(readerName, "1234");
 }
    //public static DeviceManager deviceManager = new DeviceManager(false);

    public SmartCardTest()
    {
      List<CardInfo> lst = SmartCardUtils.GetReaderNames();
      String readerName = lst[0].ReaderName;
      smartCard = new SmartCard(readerName, "5304");
    }
Example #24
0
        /// <summary>
        /// Sample code to hande a couple of different cards based on the identification process
        /// </summary>
        /// <returns>None</returns>
        private async Task HandleCard(SmartCard card)
        {
            try
            {
                // Clear the messages
                //MainPage.Current.NotifyUser(String.Empty, NotifyType.StatusMessage, true);

                // Connect to the card
                using (SmartCardConnection connection = await card.ConnectAsync())
                {
                    // Try to identify what type of card it was
                    IccDetection cardIdentification = new IccDetection(card, connection);
                    await cardIdentification.DetectCardTypeAync();

                    //Connected to card
                    //LogMessage("Connected to card\r\nPC/SC device class: " + cardIdentification.PcscDeviceClass.ToString());

                    //Card name
                    //LogMessage("Card name: " + cardIdentification.PcscCardName.ToString());

                    //If card is "MIFARE DEFIRE" (our case)
                    if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.MifareDesfire)
                    {
                        // Handle MIFARE DESfire
                        Desfire.AccessHandler desfireAccess = new Desfire.AccessHandler(connection);

                        // Get all data from card
                        Desfire.CardDetails desfire = await desfireAccess.ReadCardDetailsAsync();

                        // Get UID from object desfire
                        var UID = BitConverter.ToString(desfire.UID);
                        //LogMessage(UID, NotifyType.StatusMessage);
                        ShowToastNotification(UID);
                        PerformAuthentication();
                        //LogMessage("DesFire Card Details:  " + Environment.NewLine + desfire.ToString());
                    }
                    else
                    {
                        // Unknown card type
                        // Note that when using the XDE emulator the card's ATR and type is not passed through, so we'll
                        // end up here even for known card types if using the XDE emulator

                        // Some cards might still let us query their UID with the PC/SC command, so let's try:
                        var apduRes = await connection.TransceiveAsync(new Pcsc.GetUid());

                        if (!apduRes.Succeeded)
                        {
                            ShowToastNotification("Failure getting UID of card, " + apduRes.ToString());
                        }
                        else
                        {
                            ShowToastNotification("UID:  " + BitConverter.ToString(apduRes.ResponseData));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowToastNotification("Exception handling card: " + ex.ToString());
            }
        }
 public SetVirginMode(String readerName)
 {
   InitializeComponent();
   this.device = new SmartCard(readerName, "1234");     
 }
Example #26
0
        /*
         *
         * @throws SmartCardException
         */

        /**
         * BaseSigner interface for the requested certificate. Do not forget to logout after your crypto
         * operation finished
         * @param aCardPIN
         * @param aCert
         * @return
         * @throws SmartCardException
         */

        public SmartCardManagerKimlikNodanSec(int desktop)
        {
            try
            {
                LOGGER.Debug("New SmartCardManager will be created");
                String[] terminals = SmartOp.getCardTerminals();

                if (terminals == null || terminals.Length == 0)
                {
                    MesajiIsle("İçinde kart takılı bir kart okuyucu bulunamadı-SmartCardManagerKimlikNodanSec", 1);
                    Program.KartOkuyucuYok = 1;
                    return;
                    // throw new SmartCardException("Kart takılı kart okuyucu bulunamadı");
                }

                LOGGER.Debug("Kart okuyucu sayısı : " + terminals.Length);
                if (terminals.Length != Program.TerminalSayisi && Program.TerminalSayisi != 0)
                {
                    MesajiIsle("Kart seçildikten sonra imzalama aşamasında yeni kart okuyucu takıldı.", 1);
                    Program.KartOkuyucuYok = 1;
                    return;
                }

                if (desktop == 0)
                {
                    //*******************************
                    // sadece parametre ile gelen slotID & karttipine session ac
                    //*******************************
                    // dbden oku
                    MesajiIsle("ParamSQLServer:" + Program.ParamSQLServer + " " + Program.ParamSlotID, 0);
                    String SqlCumlesi = "";
                    SqlCumlesi = "select * from AkilliKartlar where TCKimlikNo = '" + Program.ParamTCKimlikNo + "' and SlotID = " + Program.ParamSlotID;
                    SqlConnection SQLFormVeriBaglantisi = new SqlConnection();
                    SQLFormVeriBaglantisi.ConnectionString = "server=" + Program.ParamSQLServer + ";user="******";pwd=" + Program.ParamSQLPassword + ";database=konur;";
                    SQLFormVeriBaglantisi.Open();
                    SqlCommand    qryVeriOku = new SqlCommand(SqlCumlesi, SQLFormVeriBaglantisi);
                    SqlDataReader reader = qryVeriOku.ExecuteReader();
                    string        KayitliKartTipi = "", KayitliAdiSoyadi = "", KayitliPinKodu = "";
                    //while (
                    reader.Read();
                    KayitliKartTipi  = reader["KartTipi"].ToString().Trim();
                    KayitliAdiSoyadi = reader["AdiSoyadi"].ToString().Trim();
                    reader.Close();

                    // ikinci veri okuma kismi
                    // PIN kodunun teyidi
                    SqlCumlesi             = "select EimzaPin from TnmPersonel where TCKimlikNo = '" + Program.ParamTCKimlikNo + "' and isnull(EimzaPin,'') <> '' and CalismaDurumu = 'E' ";
                    qryVeriOku.CommandText = SqlCumlesi;
                    reader = qryVeriOku.ExecuteReader();
                    reader.Read();
                    KayitliPinKodu = reader["EimzaPin"].ToString().Trim();
                    reader.Close();

                    // baglantiyi kapat
                    SQLFormVeriBaglantisi.Close();
                    if (KayitliKartTipi == "")
                    {
                        MesajiIsle("Kart Tipi kaydı AkilliKartlar tablosunda bulunamadı", 1);
                    }
                    if (KayitliPinKodu == "")
                    {
                        MesajiIsle("PIN Kodu kaydı Personel tablosunda bulunamadı. TCKimlikNo: " + Program.ParamTCKimlikNo, 1);
                    }
                    if (KayitliPinKodu != Program.ParamPin)
                    {
                        MesajiIsle("Bulunan PIN Kodu kaydı gelen PIN kodu ile eşleşmiyor. TnmPersonel PIN: " + KayitliPinKodu + " Param.PIN: " + Program.ParamPin + " TCKimlikNo: " + Program.ParamTCKimlikNo, 1);
                    }
                    MesajiIsle("KayitliKartTipi Okundu:" + KayitliKartTipi + " " + KayitliAdiSoyadi + "SlotID: " + Program.ParamSlotID, 0);

                    // MesajiIsle("Secili SlotID:" + PTerminal, 0);

                    try
                    {
                        bsc = new P11SmartCard(CardTypeConverter.AsCardType(KayitliKartTipi));
                        MesajiIsle("new P11SmartCard ok: " + KayitliKartTipi, 0);
                        bsc.openSession(Convert.ToInt64(Program.ParamSlotID));
                    }
                    catch
                    {
                        MesajiIsle("Kartı otomatik açmada hata oluştu:" + KayitliKartTipi + " " + KayitliAdiSoyadi, 0);
                        //// etugra
                        //bsc = new P11SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SAFESIGN);
                        //bsc.openSession(52481);
                        ////MessageBox.Show(index.ToString() + " nolu terminal serino");
                        ////MessageBox.Show(StringUtil.ToString(bsc.getSerial()));
                        ////MessageBox.Show("Serino gösterdi");
                        //// continue;
                    }
                    mSerialNumber = StringUtil.ToString(bsc.getSerial());
                    mSlotCount    = terminals.Length;
                    getSignatureCertificate(true, false);

                    String Temp = mSignatureCert.ToString();

                    int startIndex1 = Temp.IndexOf("SERIALNUMBER=");
                    //TC = Temp.Substring(startIndex1 + 13, 11);

                    // adsoyad alma
                    int startIndex2 = Temp.IndexOf("CN=");
                    int endIndex = Temp.IndexOf(",", startIndex2);
                    //Ad=Temp.Substring(startIndex2 + 3, endIndex - (startIndex2 + 3));

                    if (Program.ParamTCKimlikNo == Temp.Substring(startIndex1 + 13, 11) && Program.ParamAdiSoyadi == Temp.Substring(startIndex2 + 3, endIndex - (startIndex2 + 3)))
                    {
                        MesajiIsle("Otomatik olarak dogru karta konumlandi", 0);
                    }
                    else
                    {// MesajiIsle("Dogru karta konumlanamadi. Karttaki TCNo ve Isim:" +
                     //    Temp.Substring(startIndex1 + 13, 11) +" "+ Temp.Substring(startIndex2 + 3, endIndex - (startIndex2 + 3))+
                     //    ", Recetedeki Doktor TCNo ve Isim:" + Program.ParamTCKimlikNo + " " + Program.ParamAdiSoyadi, 1);
                    }
                }
                else
                {
                    // desktop = 1 ise
                    // imzalama oncesi session acma kismi
                    //*******************************
                    // kart tipini deneyerek bul ve o kart tipine session ac
                    //*******************************
                    try
                    {
                        // sadece parametre ile gelen (giriste ilk timerda okunuyor ya) slotID & karttipine session ac
                        bsc = new P11SmartCard(CardTypeConverter.AsCardType(Program.CardType));
                        bsc.openSession(Convert.ToInt64(Program.ParamSlotID));
                        // sonra tc, serial kontrolu falan yapmak lazim programa girip oto. kart okunduktan sonra kart degismis mi diye
                        // ..
                        // ...
                    }
                    catch
                    {
                        SmartCard sc       = null;
                        string    KartTipi = ""; //, AdiSoyadi = "", TCKimlikNo = "";
                        // aslinda giriste okudugundan burada sadece giriste elde edilen terminal, slotid ve cardtype degerleri uzerinden baglanip
                        // seri no kontrolu yapmali try sc catch kisimlarini kaldirmali sadece giriste birakmali... 11.12.2015
                        try
                        {
                            sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.AKIS);
                        }
                        catch
                        {
                            try
                            {
                                sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SAFESIGN);
                            }
                            catch
                            {
                                try
                                {
                                    sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.GEMPLUS);
                                }
                                catch
                                {
                                    try
                                    {
                                        sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.TKART);
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.ALADDIN);
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                sc = new SmartCard(tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType.SEFIROT);
                                                //PresentSlots = sc.getTokenPresentSlotList(); // tokenli slot listesini al
                                                //for (m = 0; m < PresentSlots.Length; m++)
                                                //{
                                                //    ListSmartCard.Add(new P11SmartCard(sc.getCardType()));
                                                //    ListSmartCard[index].openSession(PresentSlots[m]); // etugra icin 52481
                                                //    tekkartSerialNumber = StringUtil.ToString(ListSmartCard[index].getSerial());
                                                //    // sertifika getirme islemi
                                                //    ImzaSertifikasiGetirTek(true, false, index);
                                                //    PresentSlots[m].ToString();
                                                //    index = index + 1;
                                                //}
                                            }
                                            catch
                                            { }
                                        }
                                    }
                                }
                            }
                        }

                        if (sc != null)
                        {  // slotid tesbit et
                            long[] PresentSlots;
                            // long SlotID = 0;
                            PresentSlots = sc.getTokenPresentSlotList(); // tokenli slot listesini al
                            if (PresentSlots.Length == 1)
                            {
                                Program.ParamSlotID = PresentSlots[0].ToString();
                            }
                            else
                            {
                                Program.ParamSlotID = SmartCardManager.askOptionValue(null, null, PresentSlots, "Slot Listesi", new String[] { "Tamam" });
                            }
                            KartTipi = sc.getCardType().ToString();
                            try
                            {
                                bsc = new P11SmartCard(sc.getCardType());
                                MesajiIsle("SmartCard Type: " + KartTipi + " SlotID: " + Program.ParamSlotID, 0);
                                bsc.openSession(Convert.ToInt64(Program.ParamSlotID));
                            }
                            catch
                            {
                                MesajiIsle("Kartı açmada hata oluştu. Kart Tipi: " + KartTipi + " SlotID: " + Program.ParamSlotID, 0);
                            }
                        }
                        else
                        {
                            MesajiIsle("Kart tipi belirlenemedi", 0);
                        }
                    }
                    //mSerialNumber = StringUtil.ToString(bsc.getSerial());
                    //mSlotCount = terminals.Length;
                    getSignatureCertificate(true, false);

                    String Temp = mSignatureCert.ToString();


                    // adsoyad alma (gereksiz... labela koymak istersen dursun, degilse sil...) 11.12.2015
                    //int startIndex1 = Temp.IndexOf("SERIALNUMBER=");
                    //int startIndex2 = Temp.IndexOf("CN=");
                    //int endIndex = Temp.IndexOf(",", startIndex2);
                    //KartTipi = sc.getCardType().ToString();
                    //TCKimlikNo = Temp.Substring(startIndex1 + 13, 11);
                    //AdiSoyadi = Temp.Substring(startIndex2 + 3, endIndex - (startIndex2 + 3));
                }
            }

            catch (SmartCardException e)
            {
                throw e;
            }
            catch (PKCS11Exception e)
            {
                throw new SmartCardException("Pkcs11 exception", e);
            }
            catch (IOException e)
            {
                throw new SmartCardException("Smart Card IO exception - Detay bilgilerine bakınız", e);
            }
        }