Пример #1
0
        private void WaitChangeStatus(object sender, DoWorkEventArgs e)
        {
            while (!e.Cancel)
            {
                int nErrCode = Card.SCardGetStatusChange(hContext, 1000, ref states[0], 1);

                //Check if the state changed from the last time.
                if ((this.states[0].RdrEventState & 2) == 2)
                {
                    //Check what changed.
                    SmartcardState state = SmartcardState.None;

                    if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
                    {
                        //The card was inserted.
                        state = SmartcardState.Inserted;
                    }// if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)

                    else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
                    {
                        //The card was ejected.
                        state = SmartcardState.Ejected;
                    }// else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)

                    string stats = "";

                    if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
                    {
                        switch (state)
                        {
                        case SmartcardState.Inserted:
                        {
                            stats = "Card State: Card INSERTED";
                            MessageBox.Show(stats + ", " + getUID());        //Displays the card's changed state

                            // timeInOut();//Card Read&Write Functions
                            break;
                        }        //case SmartcardState.Inserted:

                        case SmartcardState.Ejected:
                        {
                            stats = "Card State: Card EJECTED";
                            MessageBox.Show(stats);
                            break;
                        }        //case SmartcardState.Ejected:

                        default:
                        {
                            stats = "Card State: UNKNOWN STATE";
                            MessageBox.Show(stats);
                            break;
                        }        // default:
                        }//switch (state)
                    }//if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)

                    //Update the current state for the next time they are checked.
                    this.states[0].RdrCurrState = this.states[0].RdrEventState;
                } // if ((this.states[0].RdrEventState & 2) == 2)
            }     //while (!e.Cancel)
        }         //private void WaitChangeStatus(object sender, DoWorkEventArgs e)
Пример #2
0
    private void WaitChangeStatus(object sender, DoWorkEventArgs e)
    {
        while (!e.Cancel)
        {
            int nErrCode = Card.SCardGetStatusChange(hContext, 1000, ref states[0], 1);

            if (nErrCode == Card.SCARD_E_SERVICE_STOPPED)
            {
                DeviceDisconnected();
                e.Cancel = true;
            }

            //Check if the state changed from the last time.
            if ((this.states[0].RdrEventState & 2) == 2)
            {
                //Check what changed.
                SmartcardState state = SmartcardState.None;
                if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
                {
                    //The card was inserted.
                    state = SmartcardState.Inserted;
                }
                else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
                {
                    //The card was ejected.
                    state = SmartcardState.Ejected;
                }
                if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
                {
                    switch (state)
                    {
                    case SmartcardState.Inserted:
                    {
                        //MessageBox.Show("Card inserted");
                        CardInserted();
                        break;
                    }

                    case SmartcardState.Ejected:
                    {
                        //MessageBox.Show("Card ejected");
                        CardEjected();
                        break;
                    }

                    default:
                    {
                        //MessageBox.Show("Some other state...");
                        break;
                    }
                    }
                }
                //Update the current state for the next time they are checked.
                this.states[0].RdrCurrState = this.states[0].RdrEventState;
            }
        }
    }
Пример #3
0
        private void WaitChangeStatus(object sender, DoWorkEventArgs e)
        {
            while (!e.Cancel)
            {
                int nErrCode = Card.SCardGetStatusChange(hContext, 1000, ref states[0], 1);
                //Check if the state changed from the last time.
                if ((this.states[0].RdrEventState & 2) == 2)
                {
                    //Check what changed.
                    SmartcardState state = SmartcardState.None;
                    if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
                    {
                        //The card was inserted.
                        state = SmartcardState.Inserted;
                    }
                    else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
                    {
                        //The card was ejected.
                        state = SmartcardState.Ejected;
                    }
                    if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
                    {
                        switch (state)
                        {
                        case SmartcardState.Inserted:
                        {
                            //Console.WriteLine("Card inserted");
                            RunMain();
                            break;
                        }

                        case SmartcardState.Ejected:
                        {
                            Console.WriteLine("\nCard ejected\n");
                            break;
                        }

                        default:
                        {
                            Console.WriteLine("Some other state...");
                            break;
                        }
                        }
                    }
                    //Update the current state for the next time they are checked.
                    this.states[0].RdrCurrState = this.states[0].RdrEventState;
                }
            }
        }
        /// <summary>Aqui se responde al Evento 'OnReaderChangeStatus' del Lector de Tarjetas.</summary>
        /// <param name="pState">Objeto del tipo SmartcardLibrary.SmartcardState que el Estado del Lector.</param>
        private void OnReaderChangeStatus(SmartcardState pState)
        {
            try
            {
                switch (pState)
                {
                case SmartcardState.None:
                    this.label3.Text = "Lector Listo";
                    break;

                case SmartcardState.Inserted:
                    //Me Conecto a la Tarjeta para recuperar informacion
                    //this.manager.CardConnect(this.readerName);
                    this.label3.Text    = "Tarjeta Insertada.";
                    this.panel1.Visible = false;
                    this.panel2.Visible = true;

                    Leer_Cedula_WithContact();
                    break;

                case SmartcardState.Ejected:
                    this.label3.Text    = "Tarjeta Retirada";
                    this.panel1.Visible = true;
                    this.panel2.Visible = false;

                    this.lbApellido1.Text       = null;
                    this.lbApellido2.Text       = null;
                    this.lbNombres.Text         = null;
                    this.lbNacionalidad.Text    = null;
                    this.lbLugarNacimiento.Text = null;
                    this.lbFechaNacimiento.Text = null;

                    this.lbNroCedula.Text = null;

                    this.lbFechaExpedida.Text = null;
                    this.lbFechaVence.Text    = null;
                    this.pictureFoto.Image    = null;

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Error Inesperado", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #5
0
 public SmartcardState CheckCardState()
 {
     using (var ctx = new SCardContext())
     {
         ctx.Establish(SCardScope.System); var readerNames = ctx.GetReaders(); // Get the current status for all readers.
         var            states = ctx.GetReaderStatus(readerNames);
         SmartcardState cstate = SmartcardState.CardNotChanged;
         foreach (var state in states)
         {
             if (cardcnt != state.CardChangeEventCnt)
             {
                 cardcnt = state.CardChangeEventCnt;
                 cstate  = SmartcardState.CardChanged;
             }
             else
             {
                 cardcnt = state.CardChangeEventCnt;
                 cstate  = SmartcardState.CardNotChanged;
             }
         }
         return(cstate);
     }
 }
Пример #6
0
        private void WaitChangeStatus(object sender, DoWorkEventArgs e)
        {
            while (!e.Cancel)
            {
                SmartcardErrorCode result;

                //Obtain a lock when we use the context pointer,
                //which may be modified in the Dispose() method.
                lock (this)
                {
                    if (!this.HasContext)
                    {
                        return;
                    }

                    //This thread will be executed every 1000ms.
                    //The thread also blocks for 1000ms, meaning
                    //that the application may keep on running for
                    //one extra second after the user has closed
                    //the Main Form.
                    result =
                        (SmartcardErrorCode)UnsafeNativeMethods.GetStatusChange(
                            this._context, 1000, this._states, this._states.Length);
                }

                if ((result == SmartcardErrorCode.Timeout))
                {
                    // Time out has passed, but there is no new info. Just go on with the loop
                    continue;
                }

                for (int i = 0; i <= this._states.Length - 1; i++)
                {
                    //Check if the state changed from the last time.
                    if ((this._states[i].EventState & CardState.Changed) == CardState.Changed)
                    {
                        //Check what changed.
                        SmartcardState state = SmartcardState.None;
                        if ((this._states[i].EventState & CardState.Present) == CardState.Present &&
                            (this._states[i].CurrentState & CardState.Present) != CardState.Present)
                        {
                            //The card was inserted.
                            state = SmartcardState.Inserted;
                        }
                        else if ((this._states[i].EventState & CardState.Empty) == CardState.Empty &&
                                 (this._states[i].CurrentState & CardState.Empty) != CardState.Empty)
                        {
                            //The card was ejected.
                            state = SmartcardState.Ejected;
                        }
                        if (state != SmartcardState.None && this._states[i].CurrentState != CardState.None)
                        {
                            switch (state)
                            {
                            case SmartcardState.Inserted:
                            {
                                MessageBox.Show("Card inserted");
                                break;
                            }

                            case SmartcardState.Ejected:
                            {
                                MessageBox.Show("Card ejected");
                                break;
                            }

                            default:
                            {
                                MessageBox.Show("Some other state...");
                                break;
                            }
                            }
                        }
                        //Update the current state for the next time they are checked.
                        this._states[i].CurrentState = this._states[i].EventState;
                    }
                }
            }
        }
Пример #7
0
        public void KeepWaiting(object sender, DoWorkEventArgs e)
        {
            while (!e.Cancel)
            {
                SCardError err;
                IntPtr     pioSendPci;
                try
                {
                    SCardContext hContext  = EstablishContext();
                    string[]     szReaders = RetrieveReaders(hContext);
                    // Create a reader object using the existing context
                    SCardReader reader = new SCardReader(hContext);

                    // Connect to the card
                    err = reader.Connect(szReaders[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1);
                    if (err != SCardError.Success)
                    {
                        throw new PCSCException(err, SCardHelper.StringifyError(err));
                    }
                    else
                    {
                        SmartcardState cstate = CheckCardState();
                        if (cstate == SmartcardState.CardChanged)
                        {
                            switch (reader.ActiveProtocol)
                            {
                            case SCardProtocol.T0:
                                pioSendPci = SCardPCI.T0;
                                break;

                            case SCardProtocol.T1:
                                pioSendPci = SCardPCI.T1;
                                break;

                            default:
                                throw new PCSCException(SCardError.ProtocolMismatch,
                                                        "Protocol not supported: "
                                                        + reader.ActiveProtocol.ToString());
                            }

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

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

                                if (CheckRespnse(pbRecvBuffer))
                                {
                                    ReadUid(err, reader, pioSendPci, block);
                                }
                            }
                        }
                    }
                    hContext.Release();
                }
                catch (PCSCException ex)
                {
                    Console.WriteLine("Error: "
                                      + ex.Message
                                      + " (" + ex.SCardError.ToString() + ")");
                }
            }
        }
Пример #8
0
        /// <summary>Aqui se responde al Evento 'OnReaderChangeStatus' del Lector de Tarjetas.</summary>
        /// <param name="pState">Objeto del tipo SmartcardLibrary.SmartcardState que el Estado del Lector.</param>
        private void OnReaderChangeStatus(SmartcardState pState)
        {
            try
            {
                switch (pState)
                {
                case SmartcardState.None:
                    this.listBox1.Items.Add("Lector Listo");
                    break;

                case SmartcardState.Inserted:
                    //Me Conecto a la Tarjeta para recuperar informacion
                    this.manager.CardConnect(this.readerName);
                    if (!this.manager.IsPresentCard())                             //<-Reviso si aún está presente la tarjeta
                    {
                        this.listBox1.Items.Add("Tarjeta No Detectada.");
                    }
                    else
                    {
                        this.listBox1.Items.Add("Tarjeta Insertada:");

                        //El UID en formato Hexadecimal (Real).
                        //Cutcsa(Fase II) reconoce los mismos codigos pero invertidos,
                        //Esto se debe a que Cutcsa sólo reconoce el Formato Entero(Int32).
                        //Los Pases Libres hay que invertirlos

                        //El UID en formato Long(Int64) vendría a ser el valor Real del UID:
                        string hexNor  = this.manager.GetCardUID(true, false).Replace(" ", "");
                        Int64  UID_nor = Int64.Parse(hexNor, System.Globalization.NumberStyles.HexNumber);

                        this.listBox1.Items.Add(string.Format("	ATR: {0}", this.manager.ATR[0]));
                        this.listBox1.Items.Add(string.Format("	{0}", this.manager.ATR[1]));
                        if (this.manager.ATR.Count > 2)
                        {
                            this.listBox1.Items.Add(string.Format("	{0}", this.manager.ATR[2]));
                        }
                        if (this.manager.ATR.Count > 3)
                        {
                            this.listBox1.Items.Add(string.Format("	{0}", this.manager.ATR[3]));
                        }

                        this.listBox1.Items.Add(string.Format("	UID Real -> {0} = {1}", hexNor, UID_nor));

                        //El UID en formato Int(Int32) es el valor reconocido x Cutcsa (pases libres):
                        string hexInv  = this.manager.GetCardUID(true, true).Replace(" ", "");
                        Int32  UID_inv = Int32.Parse(hexInv, System.Globalization.NumberStyles.HexNumber);
                        //Se debe a que quien programo originalmente los pases libres se equivoco al hacer la conversion de Hex a Entero
                        //Usó Int32 envez de usar Int64, x lo cual el valor real seria este:
                        UID_nor = Int64.Parse(hexInv, System.Globalization.NumberStyles.HexNumber);

                        this.listBox1.Items.Add(string.Format("	UID Inv.  -> {0} = {1} -> Cutcsa: {2}", hexInv, UID_nor, UID_inv));
                    }
                    break;

                case SmartcardState.Ejected:
                    this.listBox1.Items.Add("Tarjeta Retirada");
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Error Inesperado", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }