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"); }
/// <inheritdoc /> public int Transmit(byte[] sendBuffer, byte[] receiveBuffer) { return(Transmit( sendPci: SCardPCI.GetPci(Protocol), sendBuffer: sendBuffer, receiveBuffer: receiveBuffer)); }
private static byte[] sendRequest(SCardReader rfidReader, SCardError sc, SCardPCI receivePci, IntPtr sendPci, CommandApdu apdu, ResponseApdu responseApdu, IsoCase isoCase) { sc = rfidReader.BeginTransaction(); if (sc != SCardError.Success) { return(null); } receivePci = new SCardPCI(); 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) { return(null); } responseApdu = new ResponseApdu(receiveBuffer, isoCase, rfidReader.ActiveProtocol); if (!responseApdu.HasData) { return(null); } return((byte[])responseApdu.GetData()); }
public static void Main() { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); if (NoReaderFound(readerNames)) { 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' statement to make sure the reader will be disposed (disconnected) on exit using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 // We don't know the ID tag size }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { Console.WriteLine("Retrieving the UID .... "); var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); // IO returned protocol control information. var receiveBuffer = new byte[256]; var command = apdu.ToArray(); var bytesReceived = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU command.Length, receivePci, // returning Protocol Control Information receiveBuffer, receiveBuffer.Length); // data buffer var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); Console.Write("SW1: {0:X2}, SW2: {1:X2}\nUid: {2}", responseApdu.SW1, responseApdu.SW2, responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"); } Console.ReadKey(); } } }
/// <inheritdoc /> public int Transmit(IntPtr sendPci, byte[] sendBuffer, int sendBufferLength, SCardPCI receivePci, byte[] receiveBuffer, int receiveBufferLength) { var receivePciPointer = receivePci?.MemoryPtr ?? IntPtr.Zero; return(Transmit(sendPci, sendBuffer, sendBufferLength, receivePciPointer, receiveBuffer, receiveBufferLength)); }
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(); }
/// <inheritdoc /> public int Transmit(SCardPCI sendPci, byte[] sendBuffer, int sendBufferLength, byte[] receiveBuffer, int receiveBufferLength) { ThrowOnInvalidSendPci(sendPci); var sendPciMemoryPtr = sendPci.MemoryPtr; return(Transmit(sendPciMemoryPtr, sendBuffer, sendBufferLength, IntPtr.Zero, receiveBuffer, receiveBufferLength)); }
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); }
private static void ThrowOnInvalidSendPci(SCardPCI sendPci) { if (sendPci == null) { throw new ArgumentNullException(nameof(sendPci)); } if (sendPci.MemoryPtr == IntPtr.Zero) { throw new ArgumentException("Valid sendPci required", nameof(sendPci)); } }
/// <inheritdoc /> public int Transmit(SCardPCI sendPci, byte[] sendBuffer, int sendBufferLength, SCardPCI receivePci, byte[] receiveBuffer, int receiveBufferLength) { ThrowOnInvalidSendPci(sendPci); var sendPciPointer = sendPci.MemoryPtr; var receivePciPointer = receivePci?.MemoryPtr ?? IntPtr.Zero; return(Transmit(sendPciPointer, sendBuffer, sendBufferLength, receivePciPointer, receiveBuffer, receiveBufferLength)); }
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> /// Get data writing on the card /// </summary> /// <returns></returns> public static byte[] GetDataFromTheCard() { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); if (readerNames == null) { return(null); } var readerName = readerNames[0]; if (readerName == null) { return(null); } // 'using' statement to make sure the reader will be disposed (disconnected) on exit using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.ReadBinary, P1 = 0x00, P2 = 0x09, Le = 0x07 // We don't know the ID tag size }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); // IO returned protocol control information. var receiveBuffer = new byte[256]; var command = apdu.ToArray(); var bytesReceived = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU command.Length, receivePci, // returning Protocol Control Information receiveBuffer, receiveBuffer.Length); // data buffer var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); return(responseApdu.GetData()); } } } }
/// <inheritdoc /> public int Transmit(SCardPCI sendPci, byte[] sendBuffer, byte[] receiveBuffer) { var sendBufferLength = sendBuffer?.Length ?? 0; var receiveBufferLength = receiveBuffer?.Length ?? 0; return(Transmit( sendPci: sendPci, sendBuffer: sendBuffer, sendBufferLength: sendBufferLength, receivePci: default(SCardPCI), receiveBuffer: receiveBuffer, receiveBufferLength: receiveBufferLength)); }
private ResponseApdu RetransmitOnInsufficientBuffer(CommandApdu commandApdu, ResponseApdu responseApdu, out SCardPCI receivePci) { int receiveBufferLength; var resendCmdApdu = (CommandApdu)commandApdu.Clone(); if (responseApdu.SW2 == 0) { resendCmdApdu.Le = 0; // 256 receiveBufferLength = 256 + 2; // 2 bytes for status word } else { resendCmdApdu.Le = responseApdu.SW2; receiveBufferLength = responseApdu.SW2 + 2; // 2 bytes for status word } var receiveBuffer = new byte[receiveBufferLength]; receivePci = new SCardPCI(); try { var sendBuffer = resendCmdApdu.ToArray(); // Shall we wait until we re-send we APDU/TPDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } // send Command APDU again with new Le value return(SimpleTransmit( sendBuffer, sendBuffer.Length, resendCmdApdu.Case, resendCmdApdu.Protocol, receivePci, receiveBuffer, receiveBufferLength)); } catch (WinErrorInsufficientBufferException ex) { throw new InvalidApduException( $"Retransmission failed because of unsufficient buffer. Le={resendCmdApdu.Le}", ex); } catch (InvalidOperationException ex) { throw new InvalidApduException( $"Got SW1={responseApdu.SW1:X}. Retransmission failed because of an invalid APDU.", resendCmdApdu, ex); } }
public byte[] SendCommand2(byte[] command) { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { using (var rfidReader = context.ConnectReader(CardReaderName, SCardShareMode.Shared, SCardProtocol.Any)) { using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { Console.WriteLine("Retrieving the UID .... "); var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); // IO returned protocol control information. var receiveBuffer = new byte[256]; command = new byte[] { 0, 132, 0, 0, 4 }; var bytesReceived = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU command.Length, receivePci, // returning Protocol Control Information receiveBuffer, receiveBuffer.Length); // data buffer //var responseApdu = // new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); //Console.Write("SW1: {0:X2}, SW2: {1:X2}\nUid: {2}", // responseApdu.SW1, // responseApdu.SW2, // responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"); byte[] receiveData = new byte[bytesReceived]; //byte[] result = responseApdu.GetData(); Array.Copy(receiveBuffer, receiveData, bytesReceived); // log?.AddLog("接收:" + BitConverter.ToString(receiveData)); return(receiveData); } } } }
private ResponseApdu SimpleTransmit(byte[] commandApdu, int commandApduLength, IsoCase isoCase, SCardProtocol protocol, SCardPCI receivePci, ref byte[] receiveBuffer, ref int receiveBufferLength) { SCardError sc; var cmdSent = false; do { // send Command APDU to the card sc = _reader.Transmit( SCardPCI.GetPci(_reader.ActiveProtocol), commandApdu, commandApduLength, receivePci, receiveBuffer, ref receiveBufferLength); // Do we need to resend the command APDU? if (sc == SCardError.InsufficientBuffer && receiveBuffer.Length < receiveBufferLength) { // The response buffer was too small. receiveBuffer = new byte[receiveBufferLength]; // Shall we wait until we re-send we APDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } } else { cmdSent = true; } } while (cmdSent == false); if (sc == SCardError.Success) { return(new ResponseApdu(receiveBuffer, receiveBufferLength, isoCase, protocol)); } // An error occurred, throw exception.. ThrowExceptionOnSCardError(sc); return(null); }
private static string GetCardUID(string readerName) { using (var context = _contextFactory.Establish(SCardScope.System)) { using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 // We don't know the ID tag size }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { //Console.WriteLine("Retrieving the UID .... "); var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); // IO returned protocol control information. var receiveBuffer = new byte[256]; var command = apdu.ToArray(); var bytesReceived = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU command.Length, receivePci, // returning Protocol Control Information receiveBuffer, receiveBuffer.Length); // data buffer var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); Log.Debug("Uid: {2} SW1: {0:X2}, SW2: {1:X2}\n", responseApdu.SW1, responseApdu.SW2, responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"); return(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()).Replace("-", "").ToUpper() : null); } } } }
/// <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); }
public byte[] SendCommand(byte[] command) { // return SendCommand2(command); using (RfidReader.Transaction(SCardReaderDisposition.Leave)) { CPUCardLogHelper.AddLog(LogTypeEnum.Send, "", command); var sendPci = SCardPCI.GetPci(RfidReader.Protocol); var receivePci = new SCardPCI(); // IO returned protocol control information. var receiveBuffer = new byte[256]; try { var bytesReceived = RfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU command.Length, receivePci, // returning Protocol Control Information receiveBuffer, receiveBuffer.Length); // data buffer //var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); byte[] receiveData = new byte[bytesReceived]; //byte[] result = responseApdu.GetData(); Array.Copy(receiveBuffer, receiveData, bytesReceived); CPUCardLogHelper.AddLog(LogTypeEnum.Recivie, "", receiveData); return(receiveData); } catch (Exception ex) { CPUCardLogHelper.AddLog(LogTypeEnum.error, "设备发送异常" + ex.Message, command); return(new byte[0]); } } }
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)); }
private ResponseApdu SimpleTransmit(byte[] commandApdu, int commandApduLength, IsoCase isoCase, SCardProtocol protocol, SCardPCI receivePci, byte[] receiveBuffer, int receiveBufferLength) { SCardError sc; do { // send Command APDU to the card sc = Reader.Transmit( SCardPCI.GetPci(Reader.ActiveProtocol), commandApdu, commandApduLength, receivePci, receiveBuffer, ref receiveBufferLength); // Do we need to resend the command APDU? if (sc.HasInsufficientBuffer() && receiveBuffer.Length < receiveBufferLength) { // The response buffer was too small. receiveBuffer = new byte[receiveBufferLength]; // Shall we wait until we re-send we APDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } } else { break; } } while (true); if (sc != SCardError.Success) { sc.Throw(); } return(new ResponseApdu(receiveBuffer, receiveBufferLength, isoCase, protocol)); }
/// <summary> /// The implementation of transmit with log /// </summary> /// <param name="reader">Reader Name</param> /// <param name="command">APDU command</param> /// <returns></returns> public static Response TransmitWithLog(this IsoReader reader, CommandApdu command) { SCardPCI receivePci = new SCardPCI(); // IO returned protocol control information. IntPtr sendPci = SCardPCI.GetPci(reader.ActiveProtocol); #if DEBUG System.Diagnostics.Debug.WriteLine(StringTools.ByteArrayToHexString(command.ToArray())); #endif var res = reader.Transmit(command); // data buffer #if DEBUG System.Diagnostics.Debug.WriteLine(StringTools.ByteArrayToHexString(res.GetData())); #endif if (res.SW1 != 0x61) { return(res); } CommandApdu apdu2 = new CommandApdu(IsoCase.Case2Short, reader.ActiveProtocol) { CLA = new ClassByte(ClaHighPart.Iso0x, SecureMessagingFormat.None, 0), Instruction = InstructionCode.GetResponse, P1 = 0x00, P2 = 00, Le = res.SW2 }; #if DEBUG System.Diagnostics.Debug.WriteLine(StringTools.ByteArrayToHexString(apdu2.ToArray())); #endif res = reader.Transmit(apdu2); #if DEBUG System.Diagnostics.Debug.WriteLine(StringTools.ByteArrayToHexString(res.GetData())); #endif return(res); }
/// <summary> /// 不要なものも含まれているので実装時は選別 /// 現在は履歴を一件ずつ解析、表示しているが処理金額比較などを行う為 /// データクラスを作成して、一度すべて読み込んでから解析を行う事 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_SuicaRead_Click(object sender, RoutedEventArgs e) { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); if (NoReaderFound(readerNames)) { textBox_Log.Text += "You need at least one reader in order to run this example.\r\n"; return; } var readerName = ChooseRfidReader(readerNames); if (readerName == null) { return; } using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { byte[] dataIn = { 0x0f, 0x09 }; var apduSelectFile = new CommandApdu(IsoCase.Case4Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.SelectFile, P1 = 0x00, P2 = 0x01, Data = dataIn, Le = 0 }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { textBox_Log.Text += "SelectFile .... \r\n"; var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); var receiveBuffer = new byte[256]; var command = apduSelectFile.ToArray(); var bytesReceivedSelectedFile = rfidReader.Transmit(sendPci, command, command.Length, receivePci, receiveBuffer, receiveBuffer.Length); var responseApdu = new ResponseApdu(receiveBuffer, bytesReceivedSelectedFile, IsoCase.Case2Short, rfidReader.Protocol); textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString() + ", SW2: " + responseApdu.SW2.ToString() + "\r\n" + "Length: " + responseApdu.Length.ToString() + "\r\n"; for (int i = 0; i < 20; ++i) { var apduReadBinary = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.ReadBinary, P1 = 0x00, P2 = (byte)i, Le = 0 }; textBox_Log.Text += "Read Binary .... \r\n"; var commandReadBinary = apduReadBinary.ToArray(); var bytesReceivedReadBinary2 = rfidReader.Transmit(sendPci, commandReadBinary, commandReadBinary.Length, receivePci, receiveBuffer, receiveBuffer.Length); var responseApdu2 = new ResponseApdu(receiveBuffer, bytesReceivedReadBinary2, IsoCase.Case2Extended, rfidReader.Protocol); textBox_Log.Text += "SW1: " + responseApdu2.SW1.ToString() + ", SW2: " + responseApdu2.SW2.ToString() + "\r\n" + "Length: " + responseApdu2.Length.ToString() + "\r\n"; //parse_tag(receiveBuffer); DataManager.GetInstance().AddHistryList(receiveBuffer); textBox_Log.Text += "\r\n"; } //履歴DB、CSVに書き込み DataManager.GetInstance().WriteUserHistoryDB(); foreach (var s in DataManager.GetInstance().GetHistoryList()) { ShowResultData(s); } } } } textBox_Log.Text += "-----------------------------------------------\r\n"; }
public string GetCardUID(string cardReaderName) { try { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { using (var rfidReader = new SCardReader(context)) { var sc = rfidReader.Connect(cardReaderName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { Debug.WriteLine(string.Format("GetCardUID: Could not connect to reader {0}:\n{1}", cardReaderName, SCardHelper.StringifyError(sc))); return(string.Empty); } 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("GetCardUID: Could not begin transaction."); return(string.Empty); } Debug.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) { Debug.WriteLine("Error: " + SCardHelper.StringifyError(sc)); return(string.Empty); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); string cardUID = responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"; rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); return(cardUID); } } } catch (Exception ex) { Debug.WriteLine("GetCardUID exception: CardReaderName: " + cardReaderName + ". Error: " + ex.ToString()); return(string.Empty); } }
static void Main(string[] args) { if (Process.GetProcesses().Count( p => p.ProcessName.ToLower() == Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.SetupInformation.ApplicationName.ToLower()) ) > 1) { Console.WriteLine("Only a single instance can run in a time"); return; } var monitorFactory = MonitorFactory.Instance; var monitor = monitorFactory.Create(SCardScope.System); var readerName = "ACS ACR122 0"; string cardUID = null; monitor.StatusChanged += (sender, states) => { if (states.NewState == SCRState.Empty) { cardUID = null; Console.Clear(); Console.WriteLine("[Status] Card Remove"); } else if (states.NewState == SCRState.Present) { if (states.NewState == SCRState.InUse) { Console.WriteLine($"[Status] {states.NewState}"); return; } Console.WriteLine($"[Status] {states.NewState}"); using (var context = ContextFactory.Instance.Establish(SCardScope.System)) { try { if (!string.IsNullOrEmpty(cardUID)) { return; } using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { //Console.WriteLine("Retrieving the UID .... "); var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); var receiveBuffer = new byte[256]; var command = apdu.ToArray(); var bytesReceived = rfidReader.Transmit( sendPci, command, command.Length, receivePci, receiveBuffer, receiveBuffer.Length); var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); if (responseApdu.HasData) { cardUID = BitConverter.ToString(responseApdu.GetData()).Replace("-", string.Empty); string cardNo = CCardUtil.CardCode(cardUID); if (string.IsNullOrEmpty(cardNo)) { Console.WriteLine("[Card] Unsupported Card"); return; } Console.WriteLine("[Card] ID:" + cardNo); InputSimulator s = new InputSimulator(); s.Keyboard.TextEntry(cardNo); Thread.Sleep(10); s.Keyboard.KeyDown(VirtualKeyCode.RETURN); Thread.Sleep(10); s.Keyboard.KeyUp(VirtualKeyCode.RETURN); Thread.Sleep(10); } else { cardUID = null; Console.WriteLine("[Card] No uid received"); } } } } catch (PCSC.Exceptions.ReaderUnavailableException) { cardUID = null; Console.WriteLine("[Card] Reader Unavailable"); } } } }; monitor.Start(readerName); Console.ReadKey(); monitor.Cancel(); monitor.Dispose(); }
/// <summary>Adds the specified PCI.</summary> /// <param name="receivePci">The PCI.</param> protected internal void Add(SCardPCI receivePci) { _lstReceivePci.Add(receivePci); }
private byte[] send(byte[] apdu) { byte[] resp = new byte[290]; SCardError rt; string temp = ""; Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Input, new Action(() => { temp = xTool.ConvertTool.Bytes2String(apdu); if (temp.Length > 9) { print("-> " + temp.Substring(0, 4) + " " + temp.Substring(4, 4) + " " + temp.Substring(8, 2) + " " + temp.Substring(10)); } else if (temp.Length > 7) { print("-> " + temp.Substring(0, 4) + " " + temp.Substring(4, 4)); } else { print("-> " + temp); } })); if (temp.Length < 8) { throw new PCSCException(SCardError.ApduFormatWrong, "PCSC: 0x" + ((int)SCardError.ApduFormatWrong).ToString("X8") + ", " + getEnumDescription(SCardError.ApduFormatWrong)); } var t1 = System.DateTime.Now; var t2 = t1; if (isDebug()) { t1 = System.DateTime.Now; resp = this.debug.send(apdu); t2 = System.DateTime.Now; } else { t1 = System.DateTime.Now; rt = this.Reader.Transmit(SCardPCI.GetPci(this.Reader.ActiveProtocol), apdu, ref resp); t2 = System.DateTime.Now; if (rt != SCardError.Success) { throw new PCSCException(rt, "PCSC: 0x" + ((int)rt).ToString("X8") + ", " + getEnumDescription(rt)); } //throw new ArgumentException("Description: " + getEnumDescription(rt) + "\n" + "PCSC Error: " + "0x" + ((int)rt).ToString("X8") + "\n"); } Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Input, new Action(() => { print("<- " + xTool.ConvertTool.Bytes2String(resp)); if (this.isTime) { var tm = (t2.Hour * 60 * 60 + t2.Minute * 60 + t2.Second) * 1000 + t2.Millisecond - (t1.Hour * 60 * 60 + t1.Minute * 60 + t1.Second) * 1000 - t1.Millisecond; print("Time: " + tm + "ms"); } })); return(resp); }
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; }
/// <summary>Transmits the specified command APDU.</summary> /// <param name="commandApdu">The command APDU.</param> /// <returns>A response containing one ore more <see cref="ResponseApdu" />.</returns> public virtual Response Transmit(CommandApdu commandApdu) { if (commandApdu == null) { throw new ArgumentNullException("commandApdu"); } // prepare send buffer (Check Command APDU and convert it to an byte array) byte[] sendBuffer; try { sendBuffer = commandApdu.ToArray(); } catch (InvalidOperationException exception) { throw new InvalidApduException("Invalid APDU.", commandApdu, exception); } // create Response object var response = new Response(); // prepare receive buffer (Response APDU) var receiveBufferLength = commandApdu.ExpectedResponseLength; // expected size that shall be returned var receiveBuffer = new byte[receiveBufferLength]; var receivePci = new SCardPCI(); var responseApdu = SimpleTransmit( sendBuffer, sendBuffer.Length, commandApdu.Case, // ISO case used by the Command APDU commandApdu.Protocol, // Protocol used by the Command APDU receivePci, ref receiveBuffer, ref receiveBufferLength); /* Check status word SW1SW2: * * 1. 0x6cxx -> Set response buffer size Le <- SW2 * 2. AND/OR 0x61xx -> More data can be read with GET RESPONSE */ if (responseApdu.SW1 == (byte) SW1Code.ErrorP3Incorrect) { // Case 1: SW1=0x6c, Previous Le/P3 not accepted -> Set le = SW2 var resendCmdApdu = (CommandApdu) commandApdu.Clone(); if (responseApdu.SW2 == 0) { resendCmdApdu.Le = 0; // 256 receiveBufferLength = 256 + 2; // 2 bytes for status word } else { resendCmdApdu.Le = responseApdu.SW2; receiveBufferLength = responseApdu.SW2 + 2; // 2 bytes for status word } receiveBuffer = new byte[receiveBufferLength]; receivePci = new SCardPCI(); try { sendBuffer = resendCmdApdu.ToArray(); // Shall we wait until we re-send we APDU/TPDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } // send Command APDU again with new Le value responseApdu = SimpleTransmit( sendBuffer, sendBuffer.Length, resendCmdApdu.Case, resendCmdApdu.Protocol, receivePci, ref receiveBuffer, ref receiveBufferLength); } catch (InvalidOperationException ex) { throw new InvalidApduException("Got SW1=0x6c. Retransmission failed because of an invalid APDU.", resendCmdApdu, ex); } } if (responseApdu.SW1 == (byte) SW1Code.NormalDataResponse) { // Case 2: SW1=0x61, More data available -> GET RESPONSE /* The transmission system shall issue a GET RESPONSE command APDU (or TPDU) * to the card by assigning the minimum of SW2 and Le to parameter Le (or P3)). * Le = min(Le,SW2) */ var le = (commandApdu.Le < responseApdu.SW2) ? commandApdu.Le : responseApdu.SW2; do { // add the last ResponseAPDU to the Response object response.Add(responseApdu); response.Add(receivePci); var getResponseApdu = ConstructGetResponseApdu(ref le); if (le == 0) { receiveBufferLength = 256 + 2; // 2 bytes for status word } else { receiveBufferLength = le + 2; // 2 bytes for status word } receiveBuffer = new byte[receiveBufferLength]; try { sendBuffer = getResponseApdu.ToArray(); // Shall we wait until we re-send we APDU/TPDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } // send Command APDU again with new Le value responseApdu = SimpleTransmit( sendBuffer, sendBuffer.Length, getResponseApdu.Case, getResponseApdu.Protocol, receivePci, ref receiveBuffer, ref receiveBufferLength); } catch (InvalidOperationException ex) { throw new InvalidApduException( "Got SW1=0x61. Retransmission failed because of an invalid GET RESPONSE APDU.", getResponseApdu, ex); } // In case there is more data available. le = responseApdu.SW2; } while ( // More data available. responseApdu.SW1 == (byte) SW1Code.NormalDataResponse || // Warning condition: data may be corrupted. Iso7816-4 7.1.5 (responseApdu.SW1 == (byte) SW1Code.WarningNVDataNotChanged && responseApdu.SW2 == 0x81)); } response.Add(responseApdu); response.Add(receivePci); return response; }
private ResponseApdu SimpleTransmit(byte[] commandApdu, int commandApduLength, IsoCase isoCase, SCardProtocol protocol, SCardPCI receivePci, ref byte[] receiveBuffer, ref int receiveBufferLength) { SCardError sc; var cmdSent = false; do { // send Command APDU to the card sc = _reader.Transmit( SCardPCI.GetPci(_reader.ActiveProtocol), commandApdu, commandApduLength, receivePci, receiveBuffer, ref receiveBufferLength); // Do we need to resend the command APDU? if (sc == SCardError.InsufficientBuffer && receiveBuffer.Length < receiveBufferLength) { // The response buffer was too small. receiveBuffer = new byte[receiveBufferLength]; // Shall we wait until we re-send we APDU? if (RetransmitWaitTime > 0) { Thread.Sleep(RetransmitWaitTime); } } else { cmdSent = true; } } while (cmdSent == false); if (sc == SCardError.Success) { return new ResponseApdu(receiveBuffer, receiveBufferLength, isoCase, protocol); } // An error occurred, throw exception.. sc.Throw(); return null; }
public static (bool Success, string Report) GetUid(IContextFactory contextFactory, string readerName) { try { using (var ctx = contextFactory.Establish(SCardScope.System)) { using (var rfidReader = new SCardReader(ctx)) { try { var rc = rfidReader.SetAttrib(SCardAttribute.AsyncProtocolTypes, new[] { (byte)1 }); // var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { return(false, SCardHelper.StringifyError(sc)); } else { 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(false, "Could not begin transaction."); } else { var receiveBuffer = new byte[256]; sc = rfidReader.Transmit( SCardPCI.GetPci(rfidReader.ActiveProtocol), // Protocol Control Information (T0, T1 or Raw) apdu.ToArray(), // command APDU new SCardPCI(), // returning Protocol Control Information ref receiveBuffer); // data buffer if (sc != SCardError.Success) { return(false, SCardHelper.StringifyError(sc)); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); if (responseApdu.HasData) { if (!(responseApdu.SW1 == 0x90 && responseApdu.SW2 == 0)) { return(false, "Not 90-00"); } var uid = responseApdu.GetData(); return(true, BitConverter.ToString(uid).Replace("-", "")); } else { return(false, "ResponseApdu has no data"); } } } } catch (Exception ex) { return(false, ex.Message); } finally { rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); } } } } catch (Exception ex) { return(false, ex.Message); } }
private void Button_ReadID_Click(object sender, RoutedEventArgs e) { var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); if (NoReaderFound(readerNames)) { textBox_Log.Text += "You need at least one reader in order to run this example." + "\r\n"; return; } var readerName = ChooseRfidReader(readerNames); if (readerName == null) { return; } using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.Protocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { textBox_Log.Text += "Retrieving the UID .... " + "\r\n"; var sendPci = SCardPCI.GetPci(rfidReader.Protocol); var receivePci = new SCardPCI(); var receiveBuffer = new byte[256]; var command = apdu.ToArray(); var bytesReceived = rfidReader.Transmit( sendPci, command, command.Length, receivePci, receiveBuffer, receiveBuffer.Length); var responseApdu = new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case2Short, rfidReader.Protocol); textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString() + " ,SW2: " + responseApdu.SW2.ToString() + "\r\n"; if (responseApdu.HasData) { textBox_Log.Text += "Uid: " + BitConverter.ToString(responseApdu.GetData()) + "\r\n"; } else { textBox_Log.Text += "Uid: No uid received" + "\r\n"; } } } } textBox_Log.Text += "-----------------------------------------------\r\n"; }