コード例 #1
0
 // Metoda pomocnicza do sprawdzania statusu połączenia
 private void CheckError(SCardError err)
 {
     if (err != SCardError.Success)
     {
         throw new PCSCException(err,
                                 SCardHelper.StringifyError(err));
     }
 }
コード例 #2
0
        static void Main(string[] args)
        {
            SCardContext ctx = new SCardContext();

            ctx.Establish(SCardScope.System);

            string[] readernames = ctx.GetReaders();
            if (readernames == null || readernames.Length < 1)
            {
                throw new Exception("You need at least one reader in order to run this example.");
            }

            // Receive the ATR of each reader by using the GetAttrib function
            foreach (string name in readernames)
            {
                SCardReader reader = new SCardReader(ctx);

                Console.Write("Trying to connect to reader.. " + name);

                // Connect to the reader, error if no card present.
                SCardError rc = reader.Connect(
                    name,
                    SCardShareMode.Shared,
                    SCardProtocol.Any);

                if (rc == SCardError.Success)
                {
                    // Reader is now connected.
                    Console.WriteLine(" done.");

                    // receive ATR string attribute
                    byte[] atr;
                    rc = reader.GetAttrib(SCardAttr.ATRString, out atr);

                    if (rc != SCardError.Success)
                    {
                        // ATR not supported?
                        Console.WriteLine("Error by trying to receive the ATR. "
                                          + SCardHelper.StringifyError(rc) + "\n");
                    }
                    else
                    {
                        Console.WriteLine("ATR: " + StringAtr(atr) + "\n");
                    }

                    // Disconnect
                    reader.Disconnect(SCardReaderDisposition.Leave);
                }
                else
                {
                    // Probably no SmartCard present.
                    Console.WriteLine(" failed. " + SCardHelper.StringifyError(rc) + "\n");
                }
            }

            ctx.Release();
            return;
        }
コード例 #3
0
        private void HandleError()
        {
            if (error == SCardError.Success)
            {
                return;
            }

            throw new PCSCException(error, SCardHelper.StringifyError(error));
        }
コード例 #4
0
ファイル: WinSCardAPI.cs プロジェクト: uheqiang/p2abcengine
 public SCardError EndTransaction(
     IntPtr hCard,
     SCardReaderDisposition dwDisposition)
 {
     return(SCardHelper.ToSCardError(
                SCardEndTransaction(
                    (IntPtr)hCard,
                    (Int32)dwDisposition)));
 }
コード例 #5
0
ファイル: WinSCardAPI.cs プロジェクト: uheqiang/p2abcengine
 public SCardError Disconnect(
     IntPtr hCard,
     SCardReaderDisposition dwDisposition)
 {
     return(SCardHelper.ToSCardError(
                SCardDisconnect(
                    (IntPtr)hCard,
                    (Int32)dwDisposition)));
 }
コード例 #6
0
ファイル: Main.cs プロジェクト: mntsss/NFC_middleware
        private void TransmitBytes()
        {
            // Create a new PC/SC context.
            var ctx = new SCardContext();

            ctx.Establish(SCardScope.System);
            // Connect to the reader
            var        rfidReader = new SCardReader(ctx);
            SCardError rc         = rfidReader.Connect(
                READER_NAME,
                SCardShareMode.Shared,
                SCardProtocol.T1);

            if (rc != SCardError.Success)
            {
                return;
            }
            // prepare APDU
            byte[] ucByteSend = new byte[]
            {
                0xFF,       // the instruction class
                0xCA,       // the instruction code
                0x00,       // parameter to the instruction
                0x00,       // parameter to the instruction
                0x00        // size of I/O transfer
            };
            rc = rfidReader.BeginTransaction();
            if (rc != SCardError.Success)
            {
                MessageBox.Show("Klaida: nutruko ryšys su skaitytuvu...");
            }
            SCardPCI ioreq = new SCardPCI();   // IO returned protocol control information.

            byte[] ucByteReceive = new byte[10];
            rc = rfidReader.Transmit(
                SCardPCI.T1, // Protocol control information, T0, T1 and Raw
                             // are global defined protocol header structures.
                ucByteSend,  // the actual data to be written to the card
                ioreq,       // The returned protocol control information
                ref ucByteReceive);
            if (rc == SCardError.Success)
            {
                var byteList = new List <byte>(ucByteReceive);
                byteList.RemoveRange(byteList.Count - 2, 2);
                ucByteReceive = byteList.ToArray();
                backgroundNFCListener.ReportProgress(0,
                                                     String.Format(BitConverter.ToString(ucByteReceive).Replace("-", "")));
            }
            else
            {
                backgroundNFCListener.ReportProgress(0,
                                                     String.Format("Klaida: " + SCardHelper.StringifyError(rc)));
            }
            rfidReader.EndTransaction(SCardReaderDisposition.Leave);
            rfidReader.Disconnect(SCardReaderDisposition.Reset);
            ctx.Release();
        }
コード例 #7
0
ファイル: RfidReader.cs プロジェクト: fossabot/ManagedIrbis
        public string ReadRfid()
        {
            string result = null;

            if (_InitRfid())
            {
                byte[] sendBuffer =
                {
                    0xFF,
                    0xCA,
                    0x00,
                    0x00,
                    0x00
                };
                byte[] receiveBuffer = new byte[10];

                SCardError errorCode = _reader.BeginTransaction();
                if (errorCode != SCardError.Success)
                {
                    throw new ApplicationException("НЕ УДАЛОСЬ НАЧАТЬ ТРАНЗАКЦИЮ");
                }
                SCardPCI ioreq   = new SCardPCI(); // создаём пустой объект
                IntPtr   sendPci = SCardPCI.GetPci(_reader.ActiveProtocol);
                errorCode = _reader.Transmit
                            (
                    sendPci,
                    sendBuffer,
                    ioreq,
                    ref receiveBuffer
                            );
                if (errorCode == SCardError.Success)
                {
                    StringBuilder builder = new StringBuilder(8);
                    for (int i = receiveBuffer.Length - 3; i >= 0; i--)
                    {
                        builder.AppendFormat("{0:X2}", receiveBuffer[i]);
                    }
                    result = builder.ToString();
                }
                else
                {
                    throw new ApplicationException
                              (string.Format(
                                  "ОШИБКА: {0}",
                                  SCardHelper.StringifyError(errorCode)
                                  ));
                }

                _reader.EndTransaction(SCardReaderDisposition.Leave);
            }

            _CloseRfid();

            return(result);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: bestpetrovich/pcsc-sharp
        public static void Main()
        {
            var context = new SCardContext();

            context.Establish(SCardScope.System);

            var readerNames = context.GetReaders();

            if (readerNames == null || readerNames.Length < 1)
            {
                Console.WriteLine("You need at least one reader in order to run this example.");
                Console.ReadKey();
                return;
            }

            // Receive the ATR of each reader by using the GetAttrib function
            foreach (var readerName in readerNames)
            {
                var reader = new SCardReader(context);

                Console.Write("Trying to connect to reader.. " + readerName);

                // Connect to the reader, error if no card present.
                var rc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);

                if (rc != SCardError.Success)
                {
                    Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n");
                }
                else
                {
                    Console.WriteLine(" done.");

                    // receive ATR string attribute
                    byte[] atr;
                    rc = reader.GetAttrib(SCardAttribute.AtrString, out atr);

                    if (rc != SCardError.Success)
                    {
                        // ATR not supported?
                        Console.WriteLine("Error by trying to receive the ATR. {0}\n", SCardHelper.StringifyError(rc));
                    }
                    else
                    {
                        Console.WriteLine("ATR: {0}\n", BitConverter.ToString(atr ?? new byte[] {}));
                    }

                    reader.Disconnect(SCardReaderDisposition.Leave);
                }
            }

            // We MUST release here since we didn't use the 'using(..)' statement
            context.Release();
            Console.ReadKey();
        }
コード例 #9
0
 static bool CheckErr(SCardError err)
 {
     if (err != SCardError.Success)
     {
         throw new PCSCException(err, SCardHelper.StringifyError(err));
     }
     else
     {
         return(true);
     }
 }
コード例 #10
0
ファイル: WinSCardAPI.cs プロジェクト: vareversat/jampay
        public SCardError Transmit(IntPtr hCard, IntPtr pioSendPci, byte[] pbSendBuffer, int pcbSendLength,
                                   IntPtr pioRecvPci, byte[] pbRecvBuffer, ref int pcbRecvLength)
        {
            var recvlen = 0;

            if (pbRecvBuffer != null)
            {
                if (pcbRecvLength > pbRecvBuffer.Length || pcbRecvLength < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(pcbRecvLength));
                }

                recvlen = pcbRecvLength;
            }
            else
            {
                if (pcbRecvLength != 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(pcbRecvLength));
                }
            }

            var sendbuflen = 0;

            if (pbSendBuffer != null)
            {
                if (pcbSendLength > pbSendBuffer.Length || pcbSendLength < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(pcbSendLength));
                }

                sendbuflen = pcbSendLength;
            }
            else
            {
                if (pcbSendLength != 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(pcbSendLength));
                }
            }

            var rc = SCardHelper.ToSCardError((SCardTransmit(
                                                   hCard,
                                                   pioSendPci,
                                                   pbSendBuffer,
                                                   sendbuflen,
                                                   pioRecvPci,
                                                   pbRecvBuffer,
                                                   ref recvlen)));

            pcbRecvLength = recvlen;

            return(rc);
        }
コード例 #11
0
        public SCardError EstablishContext(SCardScope dwScope, IntPtr pvReserved1, IntPtr pvReserved2, out IntPtr phContext)
        {
            var ctx = IntPtr.Zero;
            var rc  = SCardHelper.ToSCardError(SCardEstablishContext(
                                                   (IntPtr)dwScope,
                                                   pvReserved1,
                                                   pvReserved2,
                                                   ref ctx));

            phContext = ctx;
            return(rc);
        }
コード例 #12
0
        public SCardError Reconnect(IntPtr hCard, SCardShareMode dwShareMode, SCardProtocol dwPreferredProtocols, SCardReaderDisposition dwInitialization, out SCardProtocol pdwActiveProtocol)
        {
            var result = SCardReconnect(
                hCard,
                (int)dwShareMode,
                (int)dwPreferredProtocols,
                (int)dwInitialization,
                out var activeproto);

            pdwActiveProtocol = (SCardProtocol)activeproto;
            return(SCardHelper.ToSCardError(result));
        }
コード例 #13
0
 private string GetUid(string readerName)
 {
     using (var context = new SCardContext())
     {
         context.Establish(SCardScope.System);
         using (var rfidReader = new SCardReader(context))
         {
             var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
             if (sc != SCardError.Success)
             {
                 Debug.WriteLine($"PcscWrapper: Could not connect to reader {readerName}:\n{SCardHelper.StringifyError(sc)}");
                 return(null);
             }
             var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol)
             {
                 CLA         = 0xFF,
                 Instruction = InstructionCode.GetData,
                 P1          = 0x00,
                 P2          = 0x00,
                 Le          = 0 // We don't know the ID tag size
             };
             sc = rfidReader.BeginTransaction();
             if (sc != SCardError.Success)
             {
                 Debug.WriteLine("PcscWrapper: Could not begin transaction.");
                 return(null);
             }
             var receivePci    = new SCardPCI();  // IO returned protocol control information.
             var sendPci       = SCardPCI.GetPci(rfidReader.ActiveProtocol);
             var receiveBuffer = new byte[256];
             var command       = apdu.ToArray();
             sc = rfidReader.Transmit(
                 sendPci,                // Protocol Control Information (T0, T1 or Raw)
                 command,                // command APDU
                 receivePci,             // returning Protocol Control Information
                 ref receiveBuffer);     // data buffer
             if (sc != SCardError.Success)
             {
                 Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc));
             }
             var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
             rfidReader.EndTransaction(SCardReaderDisposition.Leave);
             rfidReader.Disconnect(SCardReaderDisposition.Reset);
             if (responseApdu.HasData)
             {
                 string uid = BitConverter.ToString(responseApdu.GetData()).Replace("-", "").ToUpper();
                 return(uid);
             }
         }
     }
     return(null);
 }
コード例 #14
0
        public SCardError EstablishContext(SCardScope dwScope, IntPtr pvReserved1, IntPtr pvReserved2,
                                           out IntPtr phContext)
        {
            var ctx = 0;
            var rc  = SCardHelper.ToSCardError(MacOsxNativeMethods.SCardEstablishContext(
                                                   (int)dwScope,
                                                   pvReserved1,
                                                   pvReserved2,
                                                   ref ctx));

            phContext = (IntPtr)ctx;
            return(rc);
        }
コード例 #15
0
ファイル: RfidReader.cs プロジェクト: fossabot/ManagedIrbis
        private bool _InitRfid()
        {
            _context = new SCardContext();
            _context.Establish(SCardScope.System);

            string[] readerNames = _context.GetReaders();
            if ((readerNames == null) || (readerNames.Length == 0))
            {
                throw new ApplicationException("Нет считывателей!");
            }

            int selected = 0;

            if (!string.IsNullOrEmpty(ReaderName))
            {
                selected = Array.IndexOf(readerNames, ReaderName);
                if (selected < 0)
                {
                    throw new ApplicationException
                          (
                              "Нет считывателя с именем "
                              + ReaderName
                          );
                }
            }

            _reader = new SCardReader(_context);
            SCardError errorCode = _reader.Connect
                                   (
                readerNames[selected],
                SCardShareMode.Shared,
                SCardProtocol.Any
                                   );

            if (errorCode == ((SCardError)(-2146434967)))
            {
                _reader = null;
                return(false);
            }
            if (errorCode != 0)
            {
                _reader.Disconnect(SCardReaderDisposition.Reset);
                _reader = null;
                throw new ApplicationException
                          (string.Format(
                              "НЕ УДАЛОСЬ ПОДКЛЮЧИТЬСЯ: {0}",
                              SCardHelper.StringifyError(errorCode)
                              ));
            }
            return(true);
        }
コード例 #16
0
        ///// <summary>
        ///// Select a special applet based on its AID (Application IDentifier) with a length of 5 bytes.
        ///// </summary>
        ///// <param name="AID">Application Identifier. A 5 byte array that represents the applet to select</param>
        public void SelectSpecialApplet(byte[] AID)
        {
            TS.TraceI("Start SelectApplet with ID \"{0}\".", Helper.ByteArrayToString(AID));
            this.crdReader = GetReader();

            byte[] pbRecvBuffer = new byte[256];

            if (AID.Length != 0x05)
            {
                throw new ArgumentException("Invalid length AID", "AID");
            }

            //// Send SELECT Applet command
            byte[] selectApplet = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x05, AID[0], AID[1], AID[2], AID[3], AID[4], 0x00 };
            TS.TraceV("Select applet command: \"{0}\".", Helper.ByteArrayToString(selectApplet));

            /////*
            //// 00 = Class
            //// A4 = Instructie
            //// 04 = P1 = Select Dedicated File (DF)
            //// 00 = P2 = File Control Information (FCI)
            //// 0B = lc = Lengte van de AID
            //// AID
            //// 00 = End
            ////*/
            SCardError err = crdReader.Transmit(selectApplet, ref pbRecvBuffer);

            if (err != SCardError.Success)
            {
                throw new CardReaderException(err, SCardHelper.StringifyError(err));
            }

            ResponseApdu resp = new ResponseApdu(pbRecvBuffer, IsoCase.Case4Extended, this.crdReader.ActiveProtocol);

            if ((resp.SW1 == 0x6A) && (resp.SW2 == 0x82))
            {
                throw new CardReaderException("Applet not found");
            }

            if ((resp.SW1 != 0x62) && (resp.SW2 != 0x83))
            {
                throw new CardReaderException("Invalid response");
            }

            /*if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00))
             * {
             *  throw new CardReaderException("Invalid response");
             * }
             */
            TS.TraceI("End SelectApplet.");
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: scottstephens/pcsc-sharp
        /// <summary>
        /// Connect to reader using <paramref name="name"/>
        /// </summary>
        /// <param name="reader">Smartcard reader instance</param>
        /// <param name="name">Requested reader name</param>
        /// <returns><c>true</c> if connection attempt was successful</returns>
        private static bool ConnectReader(ISCardReader reader, string name)
        {
            Console.Write($"Trying to connect to reader.. {name}");
            var rc = reader.Connect(name, SCardShareMode.Shared, SCardProtocol.Any);

            if (rc == SCardError.Success)
            {
                Console.WriteLine(" done.");
                return(true);
            }

            Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n");
            return(false);
        }
コード例 #18
0
        /// <summary>
        /// Will try to connect to the _connectedReader, see if there is a card present, and if so try to read the data.
        /// </summary>
        /// <returns>Either the error message or data from the card.</returns>
        public string TryToReadCard()
        {
            SCardContext context = new SCardContext();

            context.Establish(SCardScope.System);
            SCardReader reader = new SCardReader(context);

            SCardError result = SCardError.InternalError;

            try
            {
                result = reader.Connect(_connectedReader, SCardShareMode.Shared, SCardProtocol.Any);
            }
            catch (Exception)
            {
                context.Dispose();
                reader.Dispose();
                return(SCardHelper.StringifyError(result));
            }

            string message;

            if (result == SCardError.Success)
            {
                string[] readerNames; SCardProtocol protocol; SCardState state; byte[] atr;
                result = reader.Status(out readerNames, out state, out protocol, out atr);

                if (result == SCardError.Success)
                {
                    message = string.Format("Card detected:{0} Protocol: {1}{0} State: {2}{0} ATR: {3}",
                                            Environment.NewLine, protocol, state, BitConverter.ToString(atr ?? new byte[0]));
                }
                else
                {
                    message = string.Format("Unable to read from card.{0}{1}", Environment.NewLine,
                                            SCardHelper.StringifyError(result));
                }
            }
            else
            {
                message = string.Format("No card is detected (or reader reserved by another application){0} {1}",
                                        Environment.NewLine, SCardHelper.StringifyError(result));
            }

            context.Dispose();
            reader.Dispose();

            return(message);
        }
コード例 #19
0
ファイル: WinSCardAPI.cs プロジェクト: uheqiang/p2abcengine
        public SCardError ListReaders(
            IntPtr hContext,
            string[] Groups,
            out string[] Readers)
        {
            IntPtr     ctx       = (IntPtr)hContext;
            Int32      dwReaders = 0;
            SCardError rc;

            // initialize groups array
            byte[] mszGroups = null;
            if (Groups != null)
            {
                mszGroups = SCardHelper._ConvertToByteArray(Groups, textEncoding);
            }

            // determine the needed buffer size
            rc = SCardHelper.ToSCardError(
                SCardListReaders(ctx,
                                 mszGroups,
                                 null,
                                 ref dwReaders));

            if (rc != SCardError.Success)
            {
                Readers = null;
                return(rc);
            }

            // initialize array
            byte[] mszReaders = new byte[(int)dwReaders * sizeof(char)];

            rc = SCardHelper.ToSCardError(
                SCardListReaders(ctx,
                                 mszGroups,
                                 mszReaders,
                                 ref dwReaders));

            if (rc == SCardError.Success)
            {
                Readers = SCardHelper._ConvertToStringArray(mszReaders, textEncoding);
            }
            else
            {
                Readers = null;
            }

            return(rc);
        }
コード例 #20
0
        public SCardError GetAttrib(IntPtr hCard, IntPtr dwAttrId, byte[] pbAttr, out int pcbAttrLen)
        {
            var attrlen = (pbAttr != null)
                ? pbAttr.Length
                : 0;

            var rc = SCardHelper.ToSCardError(SCardGetAttrib(
                                                  hCard,
                                                  unchecked ((int)dwAttrId.ToInt64()), // On a 64-bit platform IntPtr.ToInt32() will throw an OverflowException
                                                  pbAttr,
                                                  ref attrlen));

            pcbAttrLen = attrlen;
            return(rc);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: scottstephens/pcsc-sharp
        /// <summary>
        /// Receive and print ATR string attribute
        /// </summary>
        /// <param name="reader">Connected smartcard reader instance</param>
        private static void DisplayCardAtr(ISCardReader reader)
        {
            byte[] atr;
            var    rc = reader.GetAttrib(SCardAttribute.AtrString, out atr);

            if (rc != SCardError.Success)
            {
                // ATR not supported?
                Console.WriteLine("Error by trying to receive the ATR. {0}\n", SCardHelper.StringifyError(rc));
            }
            else
            {
                Console.WriteLine("ATR: {0}\n", BitConverter.ToString(atr ?? new byte[] {}));
            }
        }
コード例 #22
0
        public SCardError Connect(IntPtr hContext, string szReader, SCardShareMode dwShareMode, SCardProtocol dwPreferredProtocols, out IntPtr phCard, out SCardProtocol pdwActiveProtocol)
        {
            var readername = SCardHelper.ConvertToByteArray(szReader, TextEncoding, Platform.Lib.CharSize);

            var result = SCardConnect(hContext,
                                      readername,
                                      (int)dwShareMode,
                                      (int)dwPreferredProtocols,
                                      out phCard,
                                      out var activeproto);

            pdwActiveProtocol = (SCardProtocol)activeproto;

            return(SCardHelper.ToSCardError(result));
        }
コード例 #23
0
        public SCardError GetAttrib(IntPtr hCard, IntPtr dwAttrId, byte[] pbAttr, out int pcbAttrLen)
        {
            var attrlen = (pbAttr != null)
                ? (IntPtr)pbAttr.Length
                : IntPtr.Zero;

            var rc = SCardHelper.ToSCardError(SCardGetAttrib(
                                                  hCard,
                                                  dwAttrId,
                                                  pbAttr,
                                                  ref attrlen));

            pcbAttrLen = (int)attrlen;
            return(rc);
        }
コード例 #24
0
        static void Main(string[] args)
        {
            var context = new SCardContext();

            context.Establish(SCardScope.System);

            var readerNames = context.GetReaders();

            if (readerNames == null || readerNames.Length < 1)
            {
                Console.WriteLine("You need at least one reader in order to run this example.");
                Console.ReadKey();
                return;
            }

            foreach (var readerName in readerNames)
            {
                var reader = new SCardReader(context);

                Console.Write("Trying to connect to reader.. " + readerName);

                var rc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                if (rc != SCardError.Success)
                {
                    Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n");
                }
                else
                {
                    Console.WriteLine(" done.");

                    byte[] attribute = null;
                    rc = reader.GetAttrib(SCardAttribute.VendorInterfaceDeviceTypeVersion, out attribute);
                    if (rc != SCardError.Success)
                    {
                        Console.WriteLine("Error by trying to receive attribute. {0}\n", SCardHelper.StringifyError(rc));
                    }
                    else
                    {
                        Console.WriteLine("Attribute value: {0}\n", BitConverter.ToString(attribute ?? new byte[] { }));
                    }

                    reader.Disconnect(SCardReaderDisposition.Leave);
                }
            }

            context.Release();
            Console.ReadKey();
        }
コード例 #25
0
ファイル: PCSCliteAPI.cs プロジェクト: RuiVarela/Nespresso
        public SCardError EstablishContext(
            SCardScope dwScope,
            IntPtr pvReserved1,
            IntPtr pvReserved2,
            ref IntPtr phContext)
        {
            IntPtr     ctx = IntPtr.Zero;
            SCardError rc  = SCardHelper.ToSCardError(SCardEstablishContext(
                                                          (IntPtr)dwScope,
                                                          (IntPtr)pvReserved1,
                                                          (IntPtr)pvReserved2,
                                                          ref ctx));

            phContext = (IntPtr)ctx;
            return(rc);
        }
コード例 #26
0
ファイル: Form1.cs プロジェクト: Szynal/PWR-W4-INF
        // Funkcja wyświetlająca ATR karty znajdującej się w czytniku
        private void DisplayCardAtr(ISCardReader reader)
        {
            byte[] atr;
            // Pobranie ATR
            var rc = reader.GetAttrib(SCardAttribute.AtrString, out atr);

            // W przypadku niepowodzenia
            if (rc != SCardError.Success)
            {
                textBoxATREquals.Text = "Nie udało się połączyć. " + SCardHelper.StringifyError(rc);
            }
            else
            {
                textBoxATREquals.Text = BitConverter.ToString(atr ?? new byte[] { });
            }
        }
コード例 #27
0
        // Łączy z kartą, wymagane by wysyłać komendy
        // wsunięcie kolejnej karty wymaga ponownego połączenia
        public bool Connect()
        {
            try
            {
                if (state <= 0)
                {
                    throw new Exception("Urządzenie nie zainicjowane.");
                }

                // Połącz się z czytnikiem
                SCardError err = reader.Connect(readerName,
                                                SCardShareMode.Exclusive,
                                                SCardProtocol.T0 | SCardProtocol.T1);
                if (err != SCardError.Success)
                {
                    throw new PCSCException(err,
                                            SCardHelper.StringifyError(err));
                }

                // Określ strukturę protokołu
                switch (reader.ActiveProtocol)
                {
                case SCardProtocol.T0:
                    protocol = SCardPCI.T0;
                    break;

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

                default:
                    throw new PCSCException(SCardError.ProtocolMismatch,
                                            "Protokół " + reader.ActiveProtocol.ToString() +
                                            "jest nieobsługiwany.");
                }

                return(true);
            }
            catch (PCSCException ex)
            {
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #28
0
        public override IOption <IReader> Content()
        {
            Debug.WriteLine("GetEnumerator Reader TreadID " + Thread.CurrentThread.ManagedThreadId);
            var cardError = _reader.Connect(_readerName, SCardShareMode.Shared, SCardProtocol.Any);

            if (cardError != SCardError.Success)
            {
                Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(cardError));
                return(new Option <IReader>());
            }
            SCardProtocol proto;
            SCardState    state;

            byte[] atr;
            var    readerNames = new[] { _readerName };
            var    sc          = _reader.Status(
                out readerNames,
                out state,
                out proto,
                out atr
                );

            if (sc != SCardError.Success)
            {
                Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(sc));
                return(new Option <IReader>());
            }

            sc = _reader.BeginTransaction();
            if (sc != SCardError.Success)
            {
                Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(sc));
                return(new Option <IReader>());
            }

            Console.WriteLine("Connected with protocol {0} in state {1}", proto, state);
            Console.WriteLine("Card ATR: {0}", BitConverter.ToString(atr));

            return(new Option <IReader>(
                       new WrappedReader(
                           //new LogedReader(
                           _reader
                           //)
                           )
                       ));
        }
コード例 #29
0
ファイル: CardReader.cs プロジェクト: vareversat/jampay
        /// <inheritdoc />
        public ReaderStatus GetStatus()
        {
            var handle = CardHandle.Handle;

            _api.Status(
                hCard: handle,
                szReaderName: out var readerNames,
                pdwState: out var dwState,
                pdwProtocol: out var dwProtocol,
                pbAtr: out var atr)
            .ThrowIfNotSuccess();

            return(new ReaderStatus(
                       readerNames: readerNames,
                       state: SCardHelper.ToState(dwState),
                       protocol: SCardHelper.ToProto(dwProtocol),
                       atr: atr));
        }
コード例 #30
0
ファイル: WinSCardAPI.cs プロジェクト: uheqiang/p2abcengine
        public SCardError GetStatusChange(
            IntPtr hContext,
            IntPtr dwTimeout,
            SCardReaderState[] rgReaderStates)
        {
            SCARD_READERSTATE[] readerstates = null;
            int cReaders = 0;

            if (rgReaderStates != null)
            {
                cReaders     = rgReaderStates.Length;
                readerstates = new SCARD_READERSTATE[cReaders];
                for (int i = 0; i < cReaders; i++)
                {
                    readerstates[i] = rgReaderStates[i].winscard_rstate;
                }
            }

            SCardError rc;
            // On a 64-bit platforms .ToInt32() will throw an OverflowException
            Int32 timeout = unchecked ((Int32)dwTimeout.ToInt64());

            rc = SCardHelper.ToSCardError(
                SCardGetStatusChange(
                    (IntPtr)hContext,
                    (Int32)timeout,
                    readerstates,
                    (Int32)cReaders));


            if (rc == SCardError.Success)
            {
                if (rgReaderStates != null)
                {
                    for (int i = 0; i < cReaders; i++)
                    {
                        /* replace with returned values */
                        rgReaderStates[i].winscard_rstate = readerstates[i];
                    }
                }
            }

            return(rc);
        }