예제 #1
1
        public static void Main()
        {
            using (var ctx = new SCardContext()) {
                ctx.Establish(SCardScope.System);

                var readerNames = ctx.GetReaders();
                var readerStates = ctx.GetReaderStatus(readerNames);

                foreach (var state in readerStates) {
                    Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    Console.WriteLine("Reader: {0}\n" +
                        "CurrentState: {1}\n" +
                        "EventState: {2}\n" +
                        "CurrentStateValue: {3}\n" +
                        "EventStateValue: {4}\n" +
                        "UserData: {5}\n" +
                        "CardChangeEventCnt: {6}\n" +
                        "ATR: {7}",

                        state.ReaderName,
                        state.CurrentState,
                        state.EventState,
                        state.CurrentStateValue,
                        state.EventStateValue,
                        state.UserData,
                        state.CardChangeEventCnt,
                        BitConverter.ToString(state.Atr ?? new byte[0]));

                    state.Dispose();
                }

                ctx.Release();
            }
            Console.ReadKey();
        }
예제 #2
1
        private static void Main() {
            // Establish Smartcard context
            using (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;
                }

                var readerName = ChooseReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var isoReader = new IsoReader(context, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) {
                    
                    // Build a GET CHALLENGE command 
                    var apdu = new CommandApdu(IsoCase.Case2Short, isoReader.ActiveProtocol) {
                        CLA = 0x00, // Class
                        Instruction = InstructionCode.GetChallenge,
                        P1 = 0x00,  // Parameter 1
                        P2 = 0x00,  // Parameter 2
                        Le = 0x08   // Expected length of the returned data
                    };

                    Console.WriteLine("Send APDU with \"GET CHALLENGE\" command: {0}", BitConverter.ToString(apdu.ToArray()));
                    var response = isoReader.Transmit(apdu);

                    Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2);

                    if (!response.HasData) {
                        Console.WriteLine("No data. (Card does not understand \"GET CHALLENGE\")");
                    } else {
                        var data = response.GetData();
                        Console.WriteLine("Challenge: {0}", BitConverter.ToString(data));
                    }
                }
            }
            Console.ReadKey();
        }
예제 #3
0
        static void Main(string[] args)
        {
            SCardContext context = new SCardContext();
            context.Establish(SCardScope.System);

            Console.Out.WriteLine("Context is valid? -> " + context.IsValid());

            // list all (smart card) readers
            Console.Out.WriteLine("Currently connected readers: ");
            string[] readers = context.GetReaders();
            foreach (string reader in readers)
                Console.WriteLine("\t" + reader);

            // list all configured reader groups
            Console.Out.WriteLine("\nCurrently configured readers groups: ");
            string[] groups = context.GetReaderGroups();
            foreach (string group in groups)
                Console.WriteLine("\t" + group);

            // list readers for each group
            foreach (string group in groups)
            {
                Console.WriteLine("\nGroup " + group + " contains ");
                foreach (string reader in context.GetReaders(new string[] { group }))
                    Console.WriteLine("\t" + reader);
            }

            context.Release();
            Console.Out.WriteLine("Context is valid? -> " + context.IsValid());
            return;
        }
예제 #4
0
        public static void Main() {
            using (var context = new SCardContext()) {
                context.Establish(SCardScope.System);

                Console.WriteLine("Context is valid? -> " + context.IsValid());

                // list all (smart card) readers
                Console.WriteLine("Currently connected readers: ");
                var readerNames = context.GetReaders();
                foreach (var readerName in readerNames) {
                    Console.WriteLine("\t" + readerName);
                }

                // list all configured reader groups
                Console.WriteLine("\nCurrently configured readers groups: ");
                var groupNames = context.GetReaderGroups();
                foreach (var groupName in groupNames) {
                    Console.WriteLine("\t" + groupName);
                }

                // list readers for each group
                foreach (var groupName in groupNames) {
                    Console.WriteLine("\nGroup " + groupName + " contains ");
                    foreach (var readerName in context.GetReaders(new[] { groupName })) {
                        Console.WriteLine("\t" + readerName);
                    }
                }

                context.Release();
                Console.WriteLine("Context is valid? -> " + context.IsValid());
                Console.ReadKey();
            }
        }
예제 #5
0
파일: CardReader.cs 프로젝트: darko0201/eVR
        public CardReader(CardRemovedEvent removedEvent, CardInsertedEvent insertedEvent)
        {
            TS.TraceI("Constructing CardReader object.");
            _systemCardContext = OpenSystemWideCardContext();

            if (removedEvent != null || insertedEvent != null)
            {
                _monitor = new SCardMonitor(_systemCardContext);
                if (removedEvent != null)
                {
                    TS.TraceV("Monitoring removedEvent");
                    _monitor.CardRemoved += new CardRemovedEvent(removedEvent);
                }
                if (insertedEvent != null)
                {
                    TS.TraceV("Monitoring insertedEvent");
                    _monitor.CardInserted += new CardInsertedEvent(insertedEvent);
                }

                readerNames = GetReaderNames();

                foreach (string s in readerNames)
                {
                    TS.TraceV("Reader detected: \"{0}\".", s);
                }

                this.StartMonitor();
                TS.TraceI("Monitor started.");
            }
            TS.TraceI("CardReader object constructed.");
        }
예제 #6
0
        public string GetReaderStatus()
        {
            SCardContext context = new SCardContext();
            context.Establish(SCardScope.System);

            if (context.GetReaders().All(r => r != _connectedReader)) // Check to see if the context has _connectedReader as a reader before we use it.
            {
                context.Dispose();
                return string.Format("{0} cannot be found in the list of connected readers", _connectedReader);
            }

            var state = context.GetReaderStatus(_connectedReader);

            if (state == null)
            {
                context.Dispose();
                return string.Format("Cannot get the reader status of {0}.", _connectedReader);
            }

            context.Dispose();

            return string.Format("Name: {1}{0}Current State: {2}{0}Event State: {3}{0}" +
                                 "Current State Value: {4}{0}Event State Value: {5}{0}" +
                                 "User Data: {6}{0}Card Change Event Count: {7}{0}" +
                                 "ATR: {8}{0}", Environment.NewLine, state.ReaderName, state.CurrentState,
                                 state.EventState, state.CurrentStateValue, state.EventStateValue, state.UserData,
                                 state.CardChangeEventCnt, state.Atr.Length == 0 ? "0" : BitConverter.ToString(state.Atr));
        }
예제 #7
0
        public static void connect()
        {
            hContext = new SCardContext();
            hContext.Establish(SCardScope.System);

            string[] readerList = hContext.GetReaders();
            Boolean noReaders = readerList.Length <= 0;
            if (noReaders)
            {
                throw new PCSCException(SCardError.NoReadersAvailable, "Blad czytnika");
            }

            Console.WriteLine("Nazwa czytnika: " + readerList[0]);

            reader = new SCardReader(hContext);

            err = reader.Connect(readerList[0],
                SCardShareMode.Shared,
                SCardProtocol.T0 | SCardProtocol.T1);
            checkError(err);

            switch (reader.ActiveProtocol)
            {
                case SCardProtocol.T0:
                    protocol = SCardPCI.T0;
                    break;
                case SCardProtocol.T1:
                    protocol = SCardPCI.T1;
                    break;
                default:
                    throw new PCSCException(SCardError.ProtocolMismatch, "nieobslugiwany protokol: "+ reader.ActiveProtocol.ToString());
            }
        }
예제 #8
0
        static void Main()
        {
            using (var context = new SCardContext()) {

                context.Establish(SCardScope.System);

                // retrieve all reader names
                var readerNames = context.GetReaders();

                if (readerNames == null || readerNames.Length < 1) {
                    Console.WriteLine("No readers found.");
                    Console.ReadKey();
                    return;
                }

                // get the card status of each reader that is currently connected
                foreach (var readerName in readerNames) {
                    using (var reader = new SCardReader(context)) {
                        Console.WriteLine("Trying to connect to reader {0}.",  readerName);

                        var sc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                        if (sc == SCardError.Success) {
                            DisplayReaderStatus(reader);
                        } else {
                            Console.WriteLine("No card inserted or reader is reserved exclusively by another application.");
                            Console.WriteLine("Error message: {0}\n", SCardHelper.StringifyError(sc));
                        }
                    }
                }

                Console.ReadKey();
            }
        }
예제 #9
0
파일: CardReader.cs 프로젝트: edjo23/shop
        public void Connect()
        {
            Log.Debug("Connecting card reader");

            try
            {
                CardContext = new SCardContext();
                CardContext.Establish(SCardScope.System);

                CardMonitor = new SCardMonitor(CardContext);
                CardMonitor.CardInserted += CardInserted;
                CardMonitor.CardRemoved += CardRemoved;

                CardMonitor.Start(GetReader());
            }
            catch (Exception)
            {
                Disconnect();
            }

            if (CardContext == null || !CardContext.IsValid())
            {
                Log.Warn("Card reader connection failed");

                Disconnect();
            }
            else
            {
                Log.Info("Card reader connected");
            }
        }
예제 #10
0
        static void Main(string[] args)
        {
            // Retrieve the names of all installed readers.
            SCardContext ctx = new SCardContext();
            ctx.Establish(SCardScope.System);
            string[] readernames = ctx.GetReaders();

            /* Get the current status of each reader in "readernames".
             */
            SCardReaderState[] states = ctx.GetReaderStatus(readernames);

            foreach (SCardReaderState state in states)
            {
                Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                Console.WriteLine("Reader: " + state.ReaderName);
                Console.WriteLine("CurrentState: " + state.CurrentState
                    + " EventState: " + state.EventState + "\n"
                    + "CurrentStateValue: " + state.CurrentStateValue
                    + " EventStateValue: " + state.EventStateValue);
                Console.WriteLine("UserData: " + state.UserData.ToString()
                    + " CardChangeEventCnt: " + state.CardChangeEventCnt);
                Console.WriteLine("ATR: " + StringAtr(state.ATR));
            }

            ctx.Release();
            return;
        }
예제 #11
0
        static void Main() {
            // Establish Smartcard context
            using (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;
                }

                var readerName = ChooseReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var isoReader = new IsoReader(context, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) {
                    var card = new MifareCard(isoReader);

                    var loadKeySuccessful = card.LoadKey(
                        KeyStructure.NonVolatileMemory, 
                        0x00, // first key slot
                        new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } // key
                    );

                    if (!loadKeySuccessful) {
                        throw new Exception("LOAD KEY failed.");
                    }

                    var authSuccessful = card.Authenticate(MSB, LSB, KeyType.KeyA, 0x00);
                    if (!authSuccessful) {
                        throw new Exception("AUTHENTICATE failed.");
                    }

                    var result = card.ReadBinary(MSB, LSB, 16);
                    Console.WriteLine("Result (before BINARY UPDATE): {0}", 
                        (result != null) 
                        ? BitConverter.ToString(result) 
                        : null);

                    var updateSuccessful = card.UpdateBinary(MSB, LSB, DATA_TO_WRITE);

                    if (!updateSuccessful) {
                        throw new Exception("UPDATE BINARY failed.");
                    }

                    result = card.ReadBinary(MSB, LSB, 16);
                    Console.WriteLine("Result (after BINARY UPDATE): {0}", 
                        (result != null) 
                        ? BitConverter.ToString(result) 
                        : null);
                }
            }
            Console.ReadKey();
        }
        public static string[] EnumerateDevices()
        {
            using (var context = new SCardContext())
            {
                context.Establish(SCardScope.System);
                context.EnsureOK();

                return context.GetReaders();
            }            
        }
예제 #13
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;
        }
예제 #14
0
        public static ElectronicIdentificationData ReadAll()
        {
            // Create PC/SC context
            string[] readerNames;
            using (var context = new SCardContext())
            {
                context.Establish(SCardScope.System);
                readerNames = context.GetReaders();

                if (readerNames.Length > 0)
                {
                    return ReadAll(readerNames[0]);
                }
                //TODO:Handle this better, maybe throw custom Exception
                else return null;
            }
        }
예제 #15
0
        static void Main(string[] args)
        {
            ConsoleKeyInfo keyinfo;

            Console.WriteLine("This program will monitor all SmartCard readers and display all status changes.");
            Console.WriteLine("Press a key to continue.");

            keyinfo = Console.ReadKey();

            // Retrieve the names of all installed readers.
            SCardContext ctx = new SCardContext();
            ctx.Establish(SCardScope.System);
            string[] readernames = ctx.GetReaders();
            ctx.Release();

            if (readernames == null || readernames.Length == 0)
            {
                Console.WriteLine("There are currently no readers installed.");
                return;
            }

            // Create a monitor object with its own PC/SC context.
            SCardMonitor monitor = new SCardMonitor(
                new SCardContext(),
                SCardScope.System);

            // Point the callback function(s) to the static defined methods below.
            monitor.CardInserted += new CardInsertedEvent(CardInserted);
            monitor.CardRemoved += new CardRemovedEvent(CardRemoved);
            monitor.Initialized += new CardInitializedEvent(Initialized);
            monitor.StatusChanged += new StatusChangeEvent(StatusChanged);
            monitor.MonitorException += new MonitorExceptionEvent(MonitorException);

            foreach (string reader in readernames)
                Console.WriteLine("Start monitoring for reader " + reader + ".");

            monitor.Start(readernames);

            // Let the program run until the user presses a key
            keyinfo = Console.ReadKey();
            GC.KeepAlive(keyinfo);

            // Stop monitoring
            monitor.Cancel();
        }
예제 #16
0
        /// <summary>
        /// Tries to populate the list of readers and returns it.
        /// </summary>
        /// <returns>Null if an error occurs. The populated string[] is successful.</returns>
        public string[] PopulateReaders()
        {
            SCardContext context = new SCardContext();
            context.Establish(SCardScope.System);

            try
            {
                _readers = context.GetReaders();
            }
            catch (Exception)
            {
                if (_readers == null)
                    return null;
            }

            context.Dispose();
            return _readers;
        }
예제 #17
0
        public static void Main()
        {
            Console.WriteLine("This program will monitor all SmartCard readers and display all status changes.");
            Console.WriteLine("Press a key to continue.");
            Console.ReadKey(); // Wait for user to press a key

            // Retrieve the names of all installed readers.
            string[] readerNames;
            using (var context = new SCardContext()) {
                context.Establish(SCardScope.System);
                readerNames = context.GetReaders();
                context.Release();
            }

            if (readerNames == null || readerNames.Length == 0) {
                Console.WriteLine("There are currently no readers installed.");
                return;
            }

            // Create a monitor object with its own PC/SC context.
            // The context will be released after monitor.Dispose()
            var monitor = new SCardMonitor(new SCardContext(), SCardScope.System);
            // Point the callback function(s) to the anonymous & static defined methods below.
            monitor.CardInserted += (sender, args) => DisplayEvent("CardInserted", args);
            monitor.CardRemoved += (sender, args) => DisplayEvent("CardRemoved", args);
            monitor.Initialized += (sender, args) => DisplayEvent("Initialized", args);
            monitor.StatusChanged += StatusChanged;
            monitor.MonitorException += MonitorException;

            foreach (var reader in readerNames) {
                Console.WriteLine("Start monitoring for reader " + reader + ".");
            }

            monitor.Start(readerNames);

            // Let the program run until the user presses a key
            Console.ReadKey();

            // Stop monitoring
            monitor.Cancel();

            // Dispose monitor resources (SCardContext)
            monitor.Dispose();
        }
예제 #18
0
        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();
        }
예제 #19
0
파일: CardWriter.cs 프로젝트: edjo23/shop
        public void Connect()
        {
            Log.Debug("Connecting card reader");

            try
            {
                CardContext = new SCardContext();
                CardContext.Establish(SCardScope.System);
            }
            catch (Exception)
            {
                Disconnect();
            }

            if (!CardContext.IsValid())
            {
                // TODO - Log.
                Disconnect();
            }

            Log.Info("Card reader connected");
        }
예제 #20
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;
        }
예제 #21
0
        /// <summary>
        /// Tries to connect to the selected reader.
        /// </summary>
        /// <returns>Null if successful. The error message if not.</returns>
        public string StartMonitoringSelectedReader(string readerName)
        {
            if (string.IsNullOrEmpty(readerName)) return "Reader name is null or empty";
            if (!_readers.Contains(readerName)) return "The reader does not exist. [Logic Error]";
            _connectedReader = readerName;

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

            SCardError result = SCardError.InternalError;

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

            _monitor = new SCardMonitor(new SCardContext(), SCardScope.System, true);
            _monitor.Initialized += (_cardInitalised);
            _monitor.CardInserted += (_cardInserted);
            _monitor.CardRemoved += (_cardRemoved);
            _monitor.Start(readerName);

            return null;
        }
예제 #22
0
        public SCardMonitor(SCardContext hContext)
        {
            if (hContext == null)
                throw new ArgumentNullException("hContext");

            this.context = hContext;
        }
예제 #23
0
 public SCardMonitor(SCardContext hContext, SCardScope scope)
     : this(hContext)
 {
     hContext.Establish(scope);
 }
예제 #24
0
파일: CardWriter.cs 프로젝트: edjo23/shop
 public void Disconnect()
 {
     if (CardContext != null)
     {
         try
         {
             CardContext.Release();
         }
         catch (Exception)
         {
         }
         finally
         {
             CardContext = null;
         }
     }
 }
예제 #25
0
        /// <summary>
        ///   Create UID reader context and wait for events.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        ///   There are currently no readers installed.
        /// </exception>
        protected override void ExecuteContext()
        {
            // Retrieve the names of all installed readers.
              using( Context = new SCardContext() ) {
            Context.Establish( SCardScope.System );

            string[] readernames = null;
            try {
              readernames = Context.GetReaders();
            } catch( PCSCException ) {} finally {
              if( null == readernames || 0 == readernames.Length ) {
            Log.Error( "There are currently no readers installed." );
              }
            }

            // Create a monitor object with its own PC/SC context.
            SCardMonitor monitor = new SCardMonitor( new SCardContext(), SCardScope.System );

            // Point the callback function(s) to the static defined methods below.
            monitor.CardInserted += CardInserted;

            if( null != readernames ) {
              foreach( string reader in readernames ) {
            Log.InfoFormat( "Start monitoring for reader '{0}'.", reader );
              }
              monitor.Start( readernames );
            }

            // Wait for the parent application to signal us to exit.
            ExitApplication = new ManualResetEvent( false );
            ExitApplication.WaitOne();

            // Stop monitoring
            monitor.Cancel();
              }
        }
예제 #26
0
        /// <summary>
        /// Will try to connect to _connectedReader and read the card.
        /// </summary>
        /// <returns>Either the data from the card or the error message. Or if 'uidOnly' is true, just the UID prefixed with 'UID^' and ending with '^'</returns>
        public string ReadCard(bool uidOnly = false)
        {
            SCardContext context = new SCardContext();
            context.Establish(SCardScope.System);
            SCardReader reader = new SCardReader(context);

            SCardError result = reader.Connect(_connectedReader, SCardShareMode.Shared, SCardProtocol.Any);

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("No card is detected (or reader reserved by another application){0}{1}",
                    Environment.NewLine, SCardHelper.StringifyError(result));
            }

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

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Unable to read from card.{0}{1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            string message = string.Format("Card detected:{0}Protocol: {1}{0}State: {2}{0}ATR: {3}{0}",
                Environment.NewLine, protocol, state, BitConverter.ToString(atr ?? new byte[0]));

            CommandApdu apdu = new CommandApdu(IsoCase.Case2Short, reader.ActiveProtocol)
            {
                CLA = 0xFF,
                Instruction = InstructionCode.GetData,
                P1 = 0x00,
                P2 = 0x00,
                Le = 0
            };

            result = reader.BeginTransaction();

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Cannot start transaction.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            SCardPCI recievePci = new SCardPCI();
            IntPtr sendPci = SCardPCI.GetPci(reader.ActiveProtocol);

            byte[] recieveBuffer = new byte[256];

            result = reader.Transmit(sendPci, apdu.ToArray(), recievePci, ref recieveBuffer);

            if (result != SCardError.Success)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("Cannot transmit data.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result));
            }

            var responseApdu = new ResponseApdu(recieveBuffer, IsoCase.Case2Short, reader.ActiveProtocol);

            message += string.Format("SW1: {1}{0}SW2: {2}{0}", Environment.NewLine, responseApdu.SW1, responseApdu.SW2);

            string data = responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "--";

            if (uidOnly)
            {
                context.Dispose();
                reader.Dispose();
                return string.Format("UID^{0}^", data);
            }

            message += string.Format("UID: {0}",data);

            reader.EndTransaction(SCardReaderDisposition.Leave);
            reader.Disconnect(SCardReaderDisposition.Reset);

            context.Dispose();
            reader.Dispose();
            return message;
        }
예제 #27
0
        /// <summary>
        ///     Create UID reader context and wait for events.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        ///     There are currently no readers installed.
        /// </exception>
        protected virtual void ExecuteContext()
        {
            try {
                // Retrieve the names of all installed readers.
                using( Context = new SCardContext() ) {
                    Context.Establish( SCardScope.System );

                    string[] readernames = null;
                    try {
                        Log.Info( "Attempting to retrieve connected readers..." );
                        readernames = Context.GetReaders();
                    } catch( PCSCException ) {}

                    SCardMonitor monitor = null;

                    if( null == readernames || 0 == readernames.Length ) {
                        //throw new InvalidOperationException( "There are currently no readers installed." );
                        Log.Warn( "There are currently no readers installed. Re-attempting in 10 seconds." );

                        if( null == RetryTimer ) {
                            RetryTimer = new Timer( TimeSpan.FromSeconds( 10 ).TotalMilliseconds );
                            RetryTimer.Elapsed += ( e, args ) => { ExecuteContext(); };
                            RetryTimer.Start();
                        }
                    } else {
                        if( null != RetryTimer ) {
                            RetryTimer.Stop();
                            RetryTimer.Dispose();
                        }

                        // Create a monitor object with its own PC/SC context.
                        monitor = new SCardMonitor( new SCardContext(), SCardScope.System );

                        // Point the callback function(s) to the static defined methods below.
                        monitor.CardInserted += CardInserted;

                        foreach( string reader in readernames ) {
                            Log.InfoFormat( "Start monitoring for reader '{0}'.", reader );
                        }

                        monitor.Start( readernames );
                    }

                    // Wait for the parent application to signal us to exit.
                    if( null == ExitApplication ) {
                        ExitApplication = new ManualResetEvent( false );
                    }
                    ExitApplication.WaitOne();

                    // Stop monitoring
                    if( null != monitor ) {
                        monitor.Cancel();
                        monitor.Dispose();
                        monitor = null;
                    }
                }
            } catch( PCSCException pcscException ) {
                Log.Error( "Failed to run application", pcscException );
            }
        }
예제 #28
0
 public SCardReader(SCardContext context)
 {
     this.context = context;
 }
예제 #29
0
 public SmartCardIO()
 {
   ctx = new SCardContext();
   ctx.Establish(this.scope);
   reader = new SCardReader(ctx);
 }
예제 #30
-1
 public PCSCReader()
 {
     context = new SCardContext();
     context.Establish(SCardScope.System);
     readerNames = context.GetReaders();
     reader = new SCardReader(context);
 }