public string RetrieveCardUID() { var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { MessageBox.Show("The reader did not have enough time to read, \nplease reswipe the card", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return("Failed to retrieve card 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, command, receivePci, ref receiveBuffer); if (sc != SCardError.Success) { MessageBox.Show("Error: " + SCardHelper.StringifyError(sc)); return("Failed to retrieve card UID"); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); return(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received, please reswipe the card"); }
private static void DisplayReaderStatus(ISCardReader reader) { 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 (sc == SCardError.Success) { Console.WriteLine("Connected with protocol {0} in state {1}", proto, state); DisplayCardAtr(atr); Console.WriteLine(); } else { Console.WriteLine("Unable to retrieve card status.\nError message: {0}", SCardHelper.StringifyError(sc)); } }
private byte[] ReadFileNextBlock(int offSet, int lenght) { TS.TraceV("Start ReadFileNextBlock, offset = \"{0}\", length = \"{1}\".", offSet, lenght); byte[] pbRecvBuffer = new byte[lenght + 2]; //// Last 2 bytes are sw1 + sw2 byte[] offSetArr = MTVReader.Converter.IntToByteArray(offSet, 2); byte[] lenghtArr = MTVReader.Converter.IntToByteArray(lenght, 1); byte[] readFile = new byte[] { 0x00, 0xB0, offSetArr[0], offSetArr[1], lenghtArr[0] }; SCardError err = this.crdReader.Transmit(readFile, ref pbRecvBuffer); if (err != SCardError.Success) { TS.TraceV("CardReaderException: \"{0}\".", SCardHelper.StringifyError(err)); throw new CardReaderException(err, "Unfortunately, this smart card can not be read"); } ResponseApdu resp = new ResponseApdu(pbRecvBuffer, IsoCase.Case4Extended, this.crdReader.ActiveProtocol); if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00)) { throw new CardReaderException(string.Format("Error reading next block for file at offset {0}, length {1}", offSet, lenght)); } TS.TraceV("End ReadFileNextBlock."); return(resp.GetData()); }
static void checkError(SCardError error) //sprawdzenie czy włożona została karta { if (error != SCardError.Success) { throw new PCSCException(error, SCardHelper.StringifyError(error)); } }
private SCardReader GetReader() { TS.TraceI("Start GetReader."); //// Establish SCard context SCardContext hContext = OpenSystemWideCardContext(); //// Create a reader object using the existing context SCardReader reader = new SCardReader(hContext); //// Connect to the card SCardError err = reader.Connect(this.ReaderName, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); if (err != SCardError.Success) { TS.TraceV("CardReaderException: \"{0}\".", SCardHelper.StringifyError(err)); throw new CardReaderException(err, "Unfortunately, this smart card can not be read"); } if (reader.ActiveProtocol != SCardProtocol.T0 && reader.ActiveProtocol != SCardProtocol.T1) { throw new CardReaderException(SCardError.ProtocolMismatch, "Protocol not supported: " + reader.ActiveProtocol.ToString()); } TS.TraceV("AciveProtocol: \"{0}\".", reader.ActiveProtocol); TS.TraceI("End GetReader."); return(reader); }
static void checkError(SCardError err) { if (err != SCardError.Success) { throw new PCSCException(err, SCardHelper.StringifyError(err)); } }
private void CheckErr(SCardError _err) { if (_err != SCardError.Success) { throw new PCSCException(_err, SCardHelper.StringifyError(_err)); } }
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; }
private void TransmitBytes() { // Create a new PC/SC context. var ctx = new SCardContext(); ctx.Establish(SCardScope.System); // Connect to the reader var rfidReader = new SCardReader(ctx); SCardError rc = rfidReader.Connect( READER_NAME, SCardShareMode.Shared, SCardProtocol.T1); if (rc != SCardError.Success) { return; } // prepare APDU byte[] ucByteSend = new byte[] { 0xFF, // the instruction class 0xCA, // the instruction code 0x00, // parameter to the instruction 0x00, // parameter to the instruction 0x00 // size of I/O transfer }; rc = rfidReader.BeginTransaction(); if (rc != SCardError.Success) { MessageBox.Show("Klaida: nutruko ryšys su skaitytuvu..."); } SCardPCI ioreq = new SCardPCI(); // IO returned protocol control information. byte[] ucByteReceive = new byte[10]; rc = rfidReader.Transmit( SCardPCI.T1, // Protocol control information, T0, T1 and Raw // are global defined protocol header structures. ucByteSend, // the actual data to be written to the card ioreq, // The returned protocol control information ref ucByteReceive); if (rc == SCardError.Success) { var byteList = new List <byte>(ucByteReceive); byteList.RemoveRange(byteList.Count - 2, 2); ucByteReceive = byteList.ToArray(); backgroundNFCListener.ReportProgress(0, String.Format(BitConverter.ToString(ucByteReceive).Replace("-", ""))); } else { backgroundNFCListener.ReportProgress(0, String.Format("Klaida: " + SCardHelper.StringifyError(rc))); } rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); ctx.Release(); }
private void HandleError() { if (error == SCardError.Success) { return; } throw new PCSCException(error, SCardHelper.StringifyError(error)); }
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(); }
public string ReadRfid() { string result = null; if (_InitRfid()) { byte[] sendBuffer = { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; byte[] receiveBuffer = new byte[10]; SCardError errorCode = _reader.BeginTransaction(); if (errorCode != SCardError.Success) { throw new ApplicationException("НЕ УДАЛОСЬ НАЧАТЬ ТРАНЗАКЦИЮ"); } SCardPCI ioreq = new SCardPCI(); // создаём пустой объект IntPtr sendPci = SCardPCI.GetPci(_reader.ActiveProtocol); errorCode = _reader.Transmit ( sendPci, sendBuffer, ioreq, ref receiveBuffer ); if (errorCode == SCardError.Success) { StringBuilder builder = new StringBuilder(8); for (int i = receiveBuffer.Length - 3; i >= 0; i--) { builder.AppendFormat("{0:X2}", receiveBuffer[i]); } result = builder.ToString(); } else { throw new ApplicationException (string.Format( "ОШИБКА: {0}", SCardHelper.StringifyError(errorCode) )); } _reader.EndTransaction(SCardReaderDisposition.Leave); } _CloseRfid(); return(result); }
static bool CheckErr(SCardError err) { if (err != SCardError.Success) { throw new PCSCException(err, SCardHelper.StringifyError(err)); } else { return(true); } }
private string GetUid(string readerName) { using (var context = new SCardContext()) { context.Establish(SCardScope.System); using (var rfidReader = new SCardReader(context)) { var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { Debug.WriteLine($"PcscWrapper: Could not connect to reader {readerName}:\n{SCardHelper.StringifyError(sc)}"); return(null); } var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 // We don't know the ID tag size }; sc = rfidReader.BeginTransaction(); if (sc != SCardError.Success) { Debug.WriteLine("PcscWrapper: Could not begin transaction."); return(null); } var receivePci = new SCardPCI(); // IO returned protocol control information. var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol); var receiveBuffer = new byte[256]; var command = apdu.ToArray(); sc = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU receivePci, // returning Protocol Control Information ref receiveBuffer); // data buffer if (sc != SCardError.Success) { Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc)); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); if (responseApdu.HasData) { string uid = BitConverter.ToString(responseApdu.GetData()).Replace("-", "").ToUpper(); return(uid); } } } return(null); }
///// <summary> ///// Select a special applet based on its AID (Application IDentifier) with a length of 5 bytes. ///// </summary> ///// <param name="AID">Application Identifier. A 5 byte array that represents the applet to select</param> public void SelectSpecialApplet(byte[] AID) { TS.TraceI("Start SelectApplet with ID \"{0}\".", Helper.ByteArrayToString(AID)); this.crdReader = GetReader(); byte[] pbRecvBuffer = new byte[256]; if (AID.Length != 0x05) { throw new ArgumentException("Invalid length AID", "AID"); } //// Send SELECT Applet command byte[] selectApplet = new byte[] { 0x00, 0xA4, 0x04, 0x00, 0x05, AID[0], AID[1], AID[2], AID[3], AID[4], 0x00 }; TS.TraceV("Select applet command: \"{0}\".", Helper.ByteArrayToString(selectApplet)); /////* //// 00 = Class //// A4 = Instructie //// 04 = P1 = Select Dedicated File (DF) //// 00 = P2 = File Control Information (FCI) //// 0B = lc = Lengte van de AID //// AID //// 00 = End ////*/ SCardError err = crdReader.Transmit(selectApplet, ref pbRecvBuffer); if (err != SCardError.Success) { throw new CardReaderException(err, SCardHelper.StringifyError(err)); } ResponseApdu resp = new ResponseApdu(pbRecvBuffer, IsoCase.Case4Extended, this.crdReader.ActiveProtocol); if ((resp.SW1 == 0x6A) && (resp.SW2 == 0x82)) { throw new CardReaderException("Applet not found"); } if ((resp.SW1 != 0x62) && (resp.SW2 != 0x83)) { throw new CardReaderException("Invalid response"); } /*if ((resp.SW1 != 0x90) && (resp.SW2 != 0x00)) * { * throw new CardReaderException("Invalid response"); * } */ TS.TraceI("End SelectApplet."); }
private bool _InitRfid() { _context = new SCardContext(); _context.Establish(SCardScope.System); string[] readerNames = _context.GetReaders(); if ((readerNames == null) || (readerNames.Length == 0)) { throw new ApplicationException("Нет считывателей!"); } int selected = 0; if (!string.IsNullOrEmpty(ReaderName)) { selected = Array.IndexOf(readerNames, ReaderName); if (selected < 0) { throw new ApplicationException ( "Нет считывателя с именем " + ReaderName ); } } _reader = new SCardReader(_context); SCardError errorCode = _reader.Connect ( readerNames[selected], SCardShareMode.Shared, SCardProtocol.Any ); if (errorCode == ((SCardError)(-2146434967))) { _reader = null; return(false); } if (errorCode != 0) { _reader.Disconnect(SCardReaderDisposition.Reset); _reader = null; throw new ApplicationException (string.Format( "НЕ УДАЛОСЬ ПОДКЛЮЧИТЬСЯ: {0}", SCardHelper.StringifyError(errorCode) )); } return(true); }
/// <summary> /// Connect to reader using <paramref name="name"/> /// </summary> /// <param name="reader">Smartcard reader instance</param> /// <param name="name">Requested reader name</param> /// <returns><c>true</c> if connection attempt was successful</returns> private static bool ConnectReader(ISCardReader reader, string name) { Console.Write($"Trying to connect to reader.. {name}"); var rc = reader.Connect(name, SCardShareMode.Shared, SCardProtocol.Any); if (rc == SCardError.Success) { Console.WriteLine(" done."); return(true); } Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n"); return(false); }
/// <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); }
/// <summary> /// Receive and print ATR string attribute /// </summary> /// <param name="reader">Connected smartcard reader instance</param> private static void DisplayCardAtr(ISCardReader reader) { byte[] atr; var rc = reader.GetAttrib(SCardAttribute.AtrString, out atr); if (rc != SCardError.Success) { // ATR not supported? Console.WriteLine("Error by trying to receive the ATR. {0}\n", SCardHelper.StringifyError(rc)); } else { Console.WriteLine("ATR: {0}\n", BitConverter.ToString(atr ?? new byte[] {})); } }
static void Main(string[] args) { var context = new SCardContext(); context.Establish(SCardScope.System); var readerNames = context.GetReaders(); if (readerNames == null || readerNames.Length < 1) { Console.WriteLine("You need at least one reader in order to run this example."); Console.ReadKey(); return; } foreach (var readerName in readerNames) { var reader = new SCardReader(context); Console.Write("Trying to connect to reader.. " + readerName); var rc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (rc != SCardError.Success) { Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n"); } else { Console.WriteLine(" done."); byte[] attribute = null; rc = reader.GetAttrib(SCardAttribute.VendorInterfaceDeviceTypeVersion, out attribute); if (rc != SCardError.Success) { Console.WriteLine("Error by trying to receive attribute. {0}\n", SCardHelper.StringifyError(rc)); } else { Console.WriteLine("Attribute value: {0}\n", BitConverter.ToString(attribute ?? new byte[] { })); } reader.Disconnect(SCardReaderDisposition.Leave); } } context.Release(); Console.ReadKey(); }
// Funkcja wyświetlająca ATR karty znajdującej się w czytniku private void DisplayCardAtr(ISCardReader reader) { byte[] atr; // Pobranie ATR var rc = reader.GetAttrib(SCardAttribute.AtrString, out atr); // W przypadku niepowodzenia if (rc != SCardError.Success) { textBoxATREquals.Text = "Nie udało się połączyć. " + SCardHelper.StringifyError(rc); } else { textBoxATREquals.Text = BitConverter.ToString(atr ?? new byte[] { }); } }
// Łączy z kartą, wymagane by wysyłać komendy // wsunięcie kolejnej karty wymaga ponownego połączenia public bool Connect() { try { if (state <= 0) { throw new Exception("Urządzenie nie zainicjowane."); } // Połącz się z czytnikiem SCardError err = reader.Connect(readerName, SCardShareMode.Exclusive, SCardProtocol.T0 | SCardProtocol.T1); if (err != SCardError.Success) { throw new PCSCException(err, SCardHelper.StringifyError(err)); } // Określ strukturę protokołu switch (reader.ActiveProtocol) { case SCardProtocol.T0: protocol = SCardPCI.T0; break; case SCardProtocol.T1: protocol = SCardPCI.T1; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "Protokół " + reader.ActiveProtocol.ToString() + "jest nieobsługiwany."); } return(true); } catch (PCSCException ex) { return(false); } catch (Exception ex) { return(false); } }
public override IOption <IReader> Content() { Debug.WriteLine("GetEnumerator Reader TreadID " + Thread.CurrentThread.ManagedThreadId); var cardError = _reader.Connect(_readerName, SCardShareMode.Shared, SCardProtocol.Any); if (cardError != SCardError.Success) { Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(cardError)); return(new Option <IReader>()); } SCardProtocol proto; SCardState state; byte[] atr; var readerNames = new[] { _readerName }; var sc = _reader.Status( out readerNames, out state, out proto, out atr ); if (sc != SCardError.Success) { Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(sc)); return(new Option <IReader>()); } sc = _reader.BeginTransaction(); if (sc != SCardError.Success) { Console.WriteLine("Could not begin transaction. {0}", SCardHelper.StringifyError(sc)); return(new Option <IReader>()); } Console.WriteLine("Connected with protocol {0} in state {1}", proto, state); Console.WriteLine("Card ATR: {0}", BitConverter.ToString(atr)); return(new Option <IReader>( new WrappedReader( //new LogedReader( _reader //) ) )); }
static void Main(string[] args) { using (var context = new SCardContext()) { context.Establish(SCardScope.System); string[] readerNames = null; try { // retrieve all reader names readerNames = context.GetReaders(); // 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)); } } } } catch (Exception) { if (readerNames == null) { Console.WriteLine("No readers found."); return; } } Console.ReadKey(); } }
static void DisplayCardAtr(ISCardReader reader) { try { var rc = reader.GetAttrib(SCardAttribute.AtrString, out var atr); if (rc != SCardError.Success) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Error by trying to receive the ATR. {0}", SCardHelper.StringifyError(rc)); } else { Console.ForegroundColor = ConsoleColor.Gray; Console.Write("{0}", BitConverter.ToString(atr ?? new byte[] { })); } } catch (Exception ex) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n{ex}\n"); Console.ForegroundColor = c; } }
/// <summary> /// Retrieves the UID of a card that is currently connected to the given /// reader. /// </summary> /// <param name="readername"></param> /// <exception cref="Exception">Could not begin transaction.</exception> private byte[] UidFromConnectedCard(string readername) { SCardReader rfidReader = new SCardReader(Context); SCardError resultCode = rfidReader.Connect(readername, SCardShareMode.Shared, SCardProtocol.Any); if (resultCode != SCardError.Success) { throw new Exception("Unable to connect to RFID card / chip. Error: " + SCardHelper.StringifyError(resultCode)); } // prepare APDU byte[] payload = 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[] receiveBuffer = new byte[10]; resultCode = rfidReader.BeginTransaction(); if (resultCode != SCardError.Success) { throw new Exception("Could not begin transaction."); } SCardPCI ioreq = new SCardPCI(); IntPtr protocolControlInformation = SCardPCI.GetPci(rfidReader.ActiveProtocol); resultCode = rfidReader.Transmit(protocolControlInformation, payload, ioreq, ref receiveBuffer); if (resultCode != SCardError.Success) { Log.Error(SCardHelper.StringifyError(resultCode)); receiveBuffer = null; } rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); return(receiveBuffer); }
/// <summary> /// Read all the data on the tag and format it as a phone number - will be used to make the payment /// </summary> /// <param name="reader"></param> /// <returns></returns> private static string ReadTag(SCardReader reader) { try { if (reader != null) { if (reader.IsConnected) { // Byte arrays to hold the responses byte[] dataBlock1 = new byte[256]; byte[] dataBlock2 = new byte[256]; // Transmit the commands SCardError err1 = reader.Transmit(Command.READ_FIRST_12_BLOCKS_FROM_BLOCK_5, ref dataBlock1); SCardError err2 = reader.Transmit(Command.READNEXT_12BLOCKS_FROM_BLOCK_9, ref dataBlock2); //Check for any errors and thro any exceptions CheckErr(err1); CheckErr(err2); // Idf no errors then read out the data byte[] readData = Command.formatResponses(dataBlock1, dataBlock2); return(NdefHelper.getNdefFromByteArray(readData)); } } else { Console.WriteLine("Tag couldn't be read, no reader is available"); } } catch (PCSCException ex) { Console.WriteLine(SCardHelper.StringifyError(ex.SCardError)); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(null); }
public IBinary Transmit(IBinary rawCommandApdu) { Debug.WriteLine("Read TreadID " + Thread.CurrentThread.ManagedThreadId); var receiveBuffer = new byte[1024 + _responseApduTrailerLength]; var receivePci = new SCardPCI(); var sendPci = SCardPCI.GetPci(SCardProtocol.T1); var sc = _reader.Transmit( sendPci, rawCommandApdu.Bytes(), receivePci, ref receiveBuffer ); if (sc != SCardError.Success) { throw new Exception("Error: " + SCardHelper.StringifyError(sc)); } return(new Binary(receiveBuffer)); }
/// <summary> /// Displays the card status of each reader in <paramref name="readerNames"/> /// </summary> /// <param name="context">Smartcard context to connect</param> /// <param name="readerNames">Smartcard readers</param> private static void DisplayReaderStatus(ISCardContext context, IEnumerable <string> readerNames) { 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) { Console.WriteLine("No card inserted or reader is reserved exclusively by another application."); Console.WriteLine("Error message: {0}\n", SCardHelper.StringifyError(sc)); continue; } PrintReaderStatus(reader); Console.WriteLine(); reader.Disconnect(SCardReaderDisposition.Reset); } } }
/// <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); }