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(); }
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(); }
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; }
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(); } }
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()); } }
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(); } }
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)); }
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; }
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(); }
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(); } }
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; }
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; } }
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(); }
/// <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; }
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(); }
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(); }
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; }
public Boolean Open(string readerName = null) { try { // Establish SCard context _hContext = new SCardContext(); _hContext.Establish(SCardScope.System); // Create a _reader object using the existing context _reader = new SCardReader(_hContext); // Connect to the card if (readerName == null || readerName == String.Empty) { // Retrieve the list of Smartcard _readers string[] szReaders = _hContext.GetReaders(); if (szReaders.Length <= 0) throw new PCSCException(SCardError.NoReadersAvailable, "Could not find any Smartcard _reader."); _err = _reader.Connect(szReaders[0], SCardShareMode.Exclusive, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(_err); } else { _err = _reader.Connect(readerName, SCardShareMode.Exclusive, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(_err); } _pioSendPci = new IntPtr(); 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()); } string[] readerNames; SCardProtocol proto; SCardState state; byte[] atr; var sc = _reader.Status( out readerNames, // contains the reader name(s) out state, // contains the current state (flags) out proto, // contains the currently used communication protocol out atr); // contains the ATR if (atr == null || atr.Length < 2) { return false; } if (atr[0] == 0x3B && atr[1] == 0x68) //Smart card tested with old type (Figure A.) { _apdu = new APDU_THAILAND_IDCARD_3B68(); } else if (atr[0] == 0x3B && atr[1] == 0x78) //Smart card tested with new type (figure B.) { _apdu = new APDU_THAILAND_IDCARD_3B68(); } else if (atr[0] == 0x3B && atr[1] == 0x67) { _apdu = new APDU_THAILAND_IDCARD_3B67(); } else { _error_code = ECODE_UNSUPPORT_CARD; _error_message = "Card not support"; Console.WriteLine(_error_message); return false; } return true; } catch (PCSCException ex) { _error_code = ECODE_SCardError; _error_message = "Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; Console.WriteLine(_error_message); return false; } }
static void Main(string[] args) { SCardContext ctx = new SCardContext(); ctx.Establish(SCardScope.System); // retrieve all reader names string[] readernames = ctx.GetReaders(); if (readernames != null) { // get the card status of each reader that is currently connected foreach (string readername in readernames) { SCardReader reader = new SCardReader(ctx); Console.Write("Trying to connect to reader " + readername + ".."); SCardError serr = reader.Connect(readername, SCardShareMode.Shared, SCardProtocol.Any); if (serr == SCardError.Success) { // SmartCard inserted, reader is now connected. Console.WriteLine(" done."); string[] tmpreadernames; SCardProtocol proto; SCardState state; byte[] atr; serr = reader.Status( out tmpreadernames, // contains the reader name(s) out state, // contains the current state (flags) out proto, // contains the currently used communication protocol out atr); // contains the card ATR if (serr == SCardError.Success) { Console.WriteLine("Connected with protocol " + proto + " in state " + state); if (atr != null && atr.Length > 0) { Console.Write("Card ATR: "); foreach (byte b in atr) Console.Write("{0:X2}", b); Console.WriteLine(); } Console.WriteLine(); } else { Console.WriteLine("Unable to retrieve card status.\nError message: " + SCardHelper.StringifyError(serr) + ".\n"); } reader.Disconnect(SCardReaderDisposition.Reset); } else { /* SmardCard not inserted or reader is reserved exclusively by another application. */ Console.WriteLine(" failed.\nError message: " + SCardHelper.StringifyError(serr) + ".\n"); } } } return; }
public string ReadSmartCard() { using (var context = new SCardContext()) { context.Establish(SCardScope.System); string readerName = null; try { string[] readerNames = context.GetReaders(); readerName = readerNames[0]; } catch(Exception ex) { return "error"; } if (readerName == null) { return "error"; } using (var rfidReader = new SCardReader(context)) { var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { return "error";//"Could not connect to reader {0}:\n{1}"; } 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) { return "none";// "Could not begin transaction."; } 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) { return "none";//SCardHelper.StringifyError(sc); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); int id = responseApdu.HasData ? BitConverter.ToInt32(responseApdu.GetData(),0) : -1; //int id = responseApdu.HasData ? System.Text.Encoding.UTF8.GetString(responseApdu.GetData()) : "none"; if (id < 0) id = id * (-1); return id.ToString(); } } return "none"; }
static void Main(string[] args) { // Establish Smartcard context 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."); // we will use the first reader for the transmit test. string readername = readernames[0]; SCardReader reader = new SCardReader(ctx); SCardError rc = reader.Connect( readername, SCardShareMode.Shared, SCardProtocol.Any); if (rc != SCardError.Success) { Console.WriteLine("Could not connect to card in reader " + readername + "\n" + "Error: " + SCardHelper.StringifyError(rc)); return; } // Build a GET CHALLENGE command CommandApdu apdu = new CommandApdu( IsoCase.Case2Short, reader.ActiveProtocol); 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 // convert the APDU object into an array of bytes byte[] cmd = apdu.ToArray(); // prepare a buffer for response APDU -> LE + 2 bytes (SW1 SW2) byte[] outbuf = new byte[apdu.ExpectedResponseLength]; rc = reader.Transmit( cmd, ref outbuf); if (rc == SCardError.Success) { Console.WriteLine("Ok."); if (outbuf != null) { ResponseApdu response = new ResponseApdu(outbuf, apdu.Case, apdu.Protocol); if (response.IsValid) { Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); if (response.HasData) { Console.Write("Data: "); for (int i = 0; i < (response.DataSize); i++) Console.Write("{0:X2} ", response.FullApdu[i]); Console.WriteLine(""); } } } } else { // Error Console.WriteLine(SCardHelper.StringifyError(rc)); } return; }
/// <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 ); } }
/// <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(); } }
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(); } } }
public string[] GetReaders() { try { // Establish SCard context _hContext = new SCardContext(); _hContext.Establish(SCardScope.System); string[] szReaders = _hContext.GetReaders(); _hContext.Release(); if (szReaders.Length <= 0) throw new PCSCException(SCardError.NoReadersAvailable, "Could not find any Smartcard reader."); return szReaders; } catch (PCSCException ex) { _error_code = ECODE_SCardError; _error_message = "Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; Console.WriteLine(_error_message); return null; } }
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(); }
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; }
public PCSCReader() { context = new SCardContext(); context.Establish(SCardScope.System); readerNames = context.GetReaders(); reader = new SCardReader(context); }