Example #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();
        }
Example #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();
        }
Example #3
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());
            }
        }
Example #4
0
        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");
            }
        }
Example #5
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;
        }
Example #6
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();
            }
        }
Example #7
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;
        }
Example #8
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));
        }
Example #9
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();
            }
        }
Example #10
0
        /// <summary>
        /// Create and establish a new smart card context.
        /// </summary>
        /// <param name="scope">Scope of the establishment. This can either be a local or remote connection.</param>
        /// <returns>A new established smart card context</returns>
        public ISCardContext Establish(SCardScope scope)
        {
            var context = new SCardContext();

            context.Establish(scope);
            return(context);
        }
Example #11
0
        static void Main(string[] args)
        {
            var context = new SCardContext();

            context.Establish(SCardScope.System);

            // Get readers
            Console.WriteLine("Currently connected readers: ");
            var readerNames = context.GetReaders();

            foreach (var readerName in readerNames)
            {
                Console.WriteLine("\t" + readerName);
            }

            if (readerNames.Length == 0)
            {
                Console.WriteLine("No readers");
            }
            else
            {
                var reader = new SCardReader(context);
                reader.Connect(readerNames[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1);
                IntPtr protocol;
                switch (reader.ActiveProtocol)
                {
                case SCardProtocol.T0:
                    protocol = SCardPCI.T0;
                    break;

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

                default:
                    throw new PCSCException(SCardError.ProtocolMismatch, "No protocol: " + reader.ActiveProtocol.ToString());
                }

                // SELECT TELECOM
                SendCommand(reader, protocol, new byte[] { 0xA0, 0xA4, 0x00, 0x00, 0x02, 0x7F, 0x10, }, "SELECT TELECOM", ReadType.Bytes);

                // GET RESPONSE
                SendCommand(reader, protocol, new byte[] { 0xA0, 0xC0, 0x00, 0x00, 0x16 }, "GET RESPONSE", ReadType.Bytes);

                // SELECT ADN
                SendCommand(reader, protocol, new byte[] { 0xA0, 0xA4, 0x00, 0x00, 0x02, 0x6F, 0x3A }, "SELECT ADN", ReadType.Bytes);

                // GET RESPONSE
                SendCommand(reader, protocol, new byte[] { 0xA0, 0xC0, 0x00, 0x00, 0x0F }, "GET RESPONSE", ReadType.Bytes);

                // READ RECORD
                for (byte i = 0; i < 45; ++i)
                {
                    SendCommand(reader, protocol, new byte[] { 0xA0, 0xB2, i, 0x04, 0x2E }, "READ RECORD", ReadType.ASCII);
                }
                context.Release();
            }
            Console.Read();
        }
Example #12
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();
            }            
        }
Example #14
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;
        }
Example #15
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;
            }
        }
Example #16
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();
        }
Example #17
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;
        }
Example #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();
        }
Example #19
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();
        }
Example #20
0
        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");
        }
Example #21
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;
        }
Example #22
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;
        }
Example #23
0
        static void Main(string[] args)
        {
            try
            {
            SCardContext hContext = new SCardContext();
            hContext.Establish(SCardScope.System);

            var szReaders = hContext.GetReaders();

            if (szReaders.Length <= 0)
                throw new PCSCException(SCardError.NoReadersAvailable,
                    "Could not find any Smartcard reader.");

                Console.WriteLine("reader name: " + szReaders[1]);

                // Create a reader object using the existing context
                SCardReader reader = new SCardReader(hContext);

                // Connect to the card
                SCardError err = reader.Connect(szReaders[1],
                    SCardShareMode.Shared,
                    SCardProtocol.T0 | SCardProtocol.T1);
                CheckErr(err);

                IntPtr pioSendPci;
                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());
                }

                byte[] pbRecvBuffer = new byte[256];

                // Send SELECT command
                // Select command 0x00, 0xA4, 0x04, 0x00,
                //Length  0x08
                //AID A0A1A2A3A4000301
                byte[] cmd1 = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x08, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0x00, 0x03, 0x01 };
                err = reader.Transmit(pioSendPci, cmd1, ref pbRecvBuffer);
                CheckErr(err);

                //(6A82: The application to be selected could not be found.)

                Console.Write("Select response: ");
                for (int i = 0; i < pbRecvBuffer.Length; i++)
                    Console.Write("{0:X2} ", pbRecvBuffer[i]);
                Console.WriteLine();

                pbRecvBuffer = new byte[256];

                // Send test command
                byte[] cmd2 = new byte[] { 0x00, 0x00, 0x00, 0x00 };
                err = reader.Transmit(pioSendPci, cmd2, ref pbRecvBuffer);
                CheckErr(err);

                Console.Write("Test commad response: ");
                for (int i = 0; i < pbRecvBuffer.Length; i++)
                    Console.Write("{0:X2} ", pbRecvBuffer[i]);
                Console.WriteLine();

                hContext.Release();
                
            }
            catch (PCSCException ex)
            {
                Console.WriteLine("Ouch: "
                    + ex.Message
                    + " (" + ex.SCardError.ToString() + ")");
            }
             Console.ReadLine();
        }
 public SmartCardIO()
 {
   ctx = new SCardContext();
   ctx.Establish(this.scope);
   reader = new SCardReader(ctx);
 }
Example #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();
              }
        }
Example #26
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 );
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            // Establish PC/SC context
            SCardContext ctx = new SCardContext();
            ctx.Establish(SCardScope.System);

            // Create a reader object
            SCardReader reader = new SCardReader(ctx);

            // Use the first reader that is found
            string firstreader = ctx.GetReaders()[0];

            // Connect to the card
            IsoCard card = new IsoCard(reader);
            card.Connect(firstreader, SCardShareMode.Shared, SCardProtocol.Any);

            // Build a ATR fetch case
            CommandApdu apdu = card.ConstructCommandApdu(
                IsoCase.Case2Short);

            apdu.CLA = 0x00; // Class
            apdu.INS = 0x84; // Instruction: GET CHALLENGE 
            apdu.P1 = 0x00;  // Parameter 1
            apdu.P2 = 0x00;  // Parameter 2
            apdu.Le = 0x08;  // Expected length of the returned data

            // Transmit the Command APDU to the card and receive the response
            Response resp = card.Transmit(apdu);

            // Show SW1SW2 from the last response packet (if more than one has been received).
            Console.WriteLine("SW1: {0:X2} SW2: {1:X2}", resp.SW1, resp.SW2);

            byte[] data;

            // First test - get the data from all response APDUs
            data = resp.GetData();
            if (data != null)
            {
                Console.Write("CHALLENGE:");

                foreach (byte b in data)
                    Console.Write(" {0:X2}", b);
                Console.WriteLine();
            }

            // Second test - get the data from each response APDU.
            int i = 0;
            foreach (ResponseApdu respApdu in resp.ResponseApduList)
            {
                data = respApdu.GetData();

                if (data != null)
                {
                    Console.Write("APDU ({0}), DATA:", i);
                    foreach (byte b in data)
                        Console.Write(" {0:X2}", b);
                    Console.WriteLine();
                    i++;
                }
            }
            return;
        }
Example #28
0
 public SCardMonitor(SCardContext hContext, SCardScope scope)
     : this(hContext)
 {
     hContext.Establish(scope);
 }
Example #29
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;
        }
Example #30
0
 public SCardMonitor(SCardContext hContext, SCardScope scope)
     : this(hContext)
 {
     hContext.Establish(scope);
 }
Example #31
0
        public static void Main() {
            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 = ChooseRfidReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var rfidReader = new SCardReader(context)) {

                    var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
                    if (sc != SCardError.Success) {
                        Console.WriteLine("Could not connect to reader {0}:\n{1}",
                            readerName,
                            SCardHelper.StringifyError(sc));
                        Console.ReadKey();
                        return;
                    }
                    
                    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) {
                        Console.WriteLine("Could not begin transaction.");
                        Console.ReadKey();
                        return;
                    }

                    Console.WriteLine("Retrieving the UID .... ");

                    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) {
                        Console.WriteLine("Error: " + SCardHelper.StringifyError(sc));
                    }

                    var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol);
                    Console.Write("SW1: {0:X2}, SW2: {1:X2}\nUid: {2}", 
                        responseApdu.SW1, 
                        responseApdu.SW2, 
                        responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received");

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

                    Console.ReadKey();
                }
            }
        }
Example #32
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.");

            // Show available readers.
            Console.WriteLine("Available readers: ");
            for (int i = 0; i < readernames.Length; i++)
                Console.WriteLine("[" + i + "] " + readernames[i]);

            int num = 0;

            if (readernames.Length > 1)
            {
                // Ask the user which one to choose.
                Console.Write("Which reader is an RFID reader? ");
                string relin = Console.ReadLine();
                if (!(int.TryParse(relin, out num))
                    || num < 0
                    || num > readernames.Length)
                {
                    Console.WriteLine("An invalid number has been entered. Exiting.");
                    return;
                }
            }

            string readername = readernames[num];

            SCardReader RFIDReader = new SCardReader(ctx);
            SCardError rc = RFIDReader.Connect(
                readername,
                SCardShareMode.Shared,
                SCardProtocol.Any);

            if (rc != SCardError.Success)
            {
                Console.WriteLine("Unable to connect to RFID card / chip. Error: " +
                    SCardHelper.StringifyError(rc));
                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
            };
            byte[] ucByteReceive = new byte[10];

            Console.Out.WriteLine("Retrieving the UID .... ");

            rc = RFIDReader.BeginTransaction();
            if (rc != SCardError.Success)
                throw new Exception("Could not begin transaction.");

            SCardPCI ioreq = new SCardPCI();    /* creates an empty object (null).
                                                 * IO returned protocol control information.
                                                 */
            IntPtr sendPci = SCardPCI.GetPci(RFIDReader.ActiveProtocol);
            rc = RFIDReader.Transmit(
                sendPci,    /* 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)
            {
                Console.Write("Uid: ");
                for (int i = 0; i < (ucByteReceive.Length); i++)
                    Console.Write("{0:X2} ", ucByteReceive[i]);
                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("Error: " + SCardHelper.StringifyError(rc));
            }

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

            return;
        }
Example #33
-1
 public PCSCReader()
 {
     context = new SCardContext();
     context.Establish(SCardScope.System);
     readerNames = context.GetReaders();
     reader = new SCardReader(context);
 }