public bool Authenticate(byte msb, byte lsb, KeyType keyType, byte keyNumber) { var authBlock = new GeneralAuthenticate { KeyNumber = keyNumber, KeyType = keyType, Lsb = lsb, Msb = msb }; var authCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = Cla, Instruction = InstructionCode.InternalAuthenticate, P1 = 0x00, P2 = 0x00, Data = authBlock.ToArray() }; Debug.WriteLine($"GENERAL AUTHENTICATE: {BitConverter.ToString(authCmd.ToArray())}"); var response = m_isoReader.Transmit(authCmd); Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}"); return(IsSuccess(response)); }
public bool Authenticate(byte msb, byte lsb, KeyType keyType, byte keyNumber) { var authBlock = new GeneralAuthenticate { MSB = msb, LSB = lsb, KeyNumber = keyNumber, KeyType = keyType }; var authKeyCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.InternalAuthenticate, P1 = 0x00, P2 = 0x00, Data = authBlock.ToArray() }; Debug.WriteLine("General Authenticate: {0}", BitConverter.ToString(authKeyCmd.ToArray())); var response = _isoReader.Transmit(authKeyCmd); Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); return((response.SW1 == 0x90) && (response.SW2 == 0x00)); }
internal bool UpdateBinary(byte msb, byte lsb, byte[] data) { if (data.Length > 16) { throw new Exception("Data length is more than 16 bytes"); } if (msb > 0) { throw new Exception("msb is more than 0"); } var updateBinaryCmd = new CommandApdu(IsoCase.Case4Short, SCardProtocol.T0) { CLA = _customCla, Instruction = InstructionCode.UpdateBinary, P1 = msb, P2 = lsb, Data = data }; Debug.WriteLine("Update Binary: {0}", BitConverter.ToString(updateBinaryCmd.ToArray())); var response = _isoReader.Transmit(updateBinaryCmd); Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); return(IsSuccess(response)); }
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 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(); } } }
private static void Main() { var contextFactory = ContextFactory.Instance; using (var ctx = contextFactory.Establish(SCardScope.System)) { var readerNames = ctx.GetReaders(); if (NoReaderFound(readerNames)) { Console.WriteLine("You need at least one reader in order to run this example."); Console.ReadKey(); return; } var name = ChooseReader(readerNames); if (name == null) { return; } using (var isoReader = new IsoReader( context: ctx, readerName: name, mode: SCardShareMode.Shared, protocol: SCardProtocol.Any, releaseContextOnDispose: 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(); }
public ActionResult WriteToCard(UserCards userCards, string date) { try { SCardContext hContext = new SCardContext(); hContext.Establish(SCardScope.System); //// Retrieve the list of Smartcard readers string[] szReaders = hContext.GetReaders(); SCardReader reader = new SCardReader(hContext); //// Connect to the card SCardError err = reader.Connect(szReaders[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); var code = userCards.ChipCardNo.Substring(Math.Max(0, userCards.ChipCardNo.Length - 4)); byte[] pbRecvBuffer = new byte[256]; byte[] pbRecvBuffer1 = new byte[256]; byte[] pbRecvBuffer2 = new byte[256]; byte[] pbRecvBuffer3 = new byte[256]; byte[] databytes = Encoding.ASCII.GetBytes(code.ToString()); byte[] count = Encoding.ASCII.GetBytes(databytes.Length.ToString()); var apdu = new CommandApdu(IsoCase.Case3Extended, reader.ActiveProtocol) { CLA = 0xFF, INS = 0xD0, P1 = 0x00, P2 = 0x69, Data = databytes }; //// Send SELECT command byte[] selecteCommand = new byte[] { 0xFF, 0xA4, 0x00, 0x00, 0x01, 0x06 }; byte[] password = new byte[] { 0xFF, 0x20, 0x00, 0x00, 0x03, 0xFF, 0xFF, 0xFF }; byte[] writeMemmoryCard = apdu.ToArray(); reader.Transmit(selecteCommand, ref pbRecvBuffer); reader.Transmit(password, ref pbRecvBuffer1); reader.Transmit(writeMemmoryCard, ref pbRecvBuffer2); hContext.Release(); userCards.ExpairDate = Convert.ToDateTime(date); userCardRepository.WriteCardUsers(userCards); return(Ok(new { success = true, successMessage = "Write Sucessfully" })); } catch (Exception ex) { return(Ok(new { success = false, errorMessage = ex.GetBaseException() })); } }
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()); } } } }
public bool LoadKey(KeyStructure keyStructure, byte keyNumber, byte[] key) { var loadKeyCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.ExternalAuthenticate, P1 = (byte)keyStructure, P2 = keyNumber, Data = key }; Debug.WriteLine("Load Authentication Keys: {0}", BitConverter.ToString(loadKeyCmd.ToArray())); var response = _isoReader.Transmit(loadKeyCmd); Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); return(IsSuccess(response)); }
public bool UpdateBinary(byte msb, byte lsb, byte[] data) { var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = Cla, Instruction = InstructionCode.UpdateBinary, P1 = msb, P2 = lsb, Data = data }; Debug.WriteLine($"UPDATE BINARY: {BitConverter.ToString(updateBinaryCmd.ToArray())}"); var response = m_isoReader.Transmit(updateBinaryCmd); Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}"); return(IsSuccess(response)); }
public bool UpdateBinary(byte msb, byte lsb, byte[] data) { var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.UpdateBinary, P1 = msb, P2 = lsb, Data = data }; Debug.WriteLine("Update Binary: {0}", BitConverter.ToString(updateBinaryCmd.ToArray())); var response = _isoReader.Transmit(updateBinaryCmd); Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); return(IsSuccess(response)); }
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); } } } }
public Response SendCommand(byte[] data, String origin) { // We could simply pass the data directly through by // using the lower-level API, but it appears that the // reader/apdu combo provided by the PCSC library does // a bit of additional work on reading to ensure we // interface with the card correctly, so we route through it bool hasData = data.Length > 5; CommandApdu apdu = InitApdu(hasData); apdu.CLA = data[0]; apdu.Instruction = (InstructionCode)data[1]; apdu.P1 = data[2]; apdu.P2 = data[3]; if (hasData) { // TODO!!! The skipped byte is the Lc byte. This field // may actually be longer than 255 though, in which case // we may need multiple bytes byte dataLength = data[4]; apdu.Data = data.Skip(5).Take(dataLength).ToArray(); } // For validation, convert back to byte array, and check equality // We do allow for a differing final byte (if it's 0) because // the library reconstruction does not add this byte (but // everything still seems to work) var newArray = apdu.ToArray(); var dataLen = data.Length; if (data.Last() == 0) { dataLen = newArray.Length; } if (!newArray.SequenceEqual(data.Take(dataLen))) { logger.Error("Reconstructing APDU Failed! \n Orig={0}\n Recon={1}", BitConverter.ToString(data), BitConverter.ToString(newArray)); // TODO: return some sort of error message } return(SendCommand(apdu, origin)); }
public byte[] ReadBinary(byte msb, byte lsb, int size) { var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any) { CLA = Cla, Instruction = InstructionCode.ReadBinary, P1 = msb, P2 = lsb, Le = size }; Debug.WriteLine($"READ BINARY: {BitConverter.ToString(readBinaryCmd.ToArray())}"); var response = m_isoReader.Transmit(readBinaryCmd); Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}\nData = {BitConverter.ToString(response.GetData())}"); return(IsSuccess(response) ? response.GetData() ?? new byte[0] : null); }
/// <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); }
public void GetSingleApplication(byte[] aid) { CommandApdu apdu = new CommandApdu(IsoCase.Case4Short, reader.ActiveProtocol); apdu.CLA = new ClassByte(ClaHighPart.Iso0x, SecureMessagingFormat.None, 0); apdu.Instruction = InstructionCode.SelectFile; apdu.P1 = 0x04; //select by name apdu.P2 = 00; // First or only occurrence apdu.Data = aid; System.Diagnostics.Debug.WriteLine(StringTools.ByteArrayToHexString(apdu.ToArray())); Response res = reader.Transmit( apdu); if (res.SW1 == 0x90) { Applications.Add(new SmartApplication(res.GetData(), reader)); } else { throw new PCSCException(SCardError.FileNotFound, "Select command failed"); } }
/// <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"; }
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(); }
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); } }
public Response SendCommand(CommandApdu apdu, String command) { logger.Trace("Sending Command {0}: {1}", command, BitConverter.ToString(apdu.ToArray())); var response = Reader.Transmit(apdu); logger.Trace("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); if (!response.HasData) { logger.Trace("No data. (Card does not understand \"{0}\")", command); return(null); } else { var resp = response.GetData(); var chars = System.Text.Encoding.UTF8.GetString(resp); string asString = ""; foreach (char ch in chars) { // Skip that annoying beep if (ch != 0x07) { asString += ch; } } logger.Trace("Response: \n {0}\n {1}", BitConverter.ToString(resp), asString); } return(response); }
public byte[] ReadBinary(byte msb, byte lsb, int size) { unchecked { var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.ReadBinary, P1 = msb, P2 = lsb, Le = size }; Debug.WriteLine("Read Binary (before update): {0}", BitConverter.ToString(readBinaryCmd.ToArray())); var response = _isoReader.Transmit(readBinaryCmd); Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2} Data: {2}", response.SW1, response.SW2, BitConverter.ToString(response.GetData())); return(IsSuccess(response) ? response.GetData() ?? new byte[0] : null); } }
private void TestTransaction() { logger.Info("---- Running Test Transaction ----"); try { CloudHostCardService service = new CloudHostCardService(); service.InitComms(); // Explicitly init comms var vibrator = (Vibrator)GetSystemService(VibratorService); service.NotifyTransacting(vibrator); //using (CloudHostCardService service = new CloudHostCardService()) { logger.Trace("Sending SEL_FILE"); byte[] SEL_FILE = { 0x32, 0x50, 0x41, 0x59, 0x2E, 0x53, 0x59, 0x53, 0x2E, 0x44, 0x44, 0x46, 0x30, 0x31 }; var command = new CommandApdu(IsoCase.Case4Short, PCSC.SCardProtocol.T0) { CLA = 0x00, // Class Instruction = InstructionCode.SelectFile, P1 = 0x04, // Parameter 1 P2 = 0x00, // Parameter 2 Data = SEL_FILE // Select PPSE (2PAY.SYS.DDF01) }; var data_sel_file = service.ProcessCommandApdu(command.ToArray(), null); logger.Trace("Sending SEL_INTERAC"); byte[] SEL_INTERAC = { 0xA0, 0x00, 0x00, 0x02, 0x77, 0x10, 0x10 }; // ASCII for Interac var data_sel_interac = service.ProcessCommandApdu(new CommandApdu(IsoCase.Case4Short, PCSC.SCardProtocol.T0) { CLA = 0x00, // Class Instruction = InstructionCode.SelectFile, P1 = 0x04, // Parameter 1 P2 = 0x00, // Parameter 2 Data = SEL_INTERAC // Select Interac file }.ToArray(), null); logger.Trace("Sending GPO"); //byte[] GPO = { 0x83, 0x13, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x24, 0x01, 0x24, 0x82, 0x3D, 0xDE, 0x7A, 0x01 }; byte[] GPO = { 0x83, 0x00 }; var data_gpo = service.ProcessCommandApdu(new CommandApdu(IsoCase.Case4Short, PCSC.SCardProtocol.T0) { CLA = 0x80, // Class Instruction = (InstructionCode)168, P1 = 0x00, // Parameter 1 P2 = 0x00, // Parameter 2 Data = GPO // Get Processing Options }.ToArray(), null); logger.Trace("Sending RR1"); var data_rr1 = service.ProcessCommandApdu(new CommandApdu(IsoCase.Case2Short, PCSC.SCardProtocol.T0) { CLA = 0x00, // Class Instruction = InstructionCode.ReadRecord, P1 = 0x01, // Parameter 1 P2 = 0x0C, // Parameter 2 }.ToArray(), null); logger.Trace("Sending RR2"); var data_rr2 = service.ProcessCommandApdu(new CommandApdu(IsoCase.Case2Short, PCSC.SCardProtocol.T0) { CLA = 0x00, // Class Instruction = InstructionCode.ReadRecord, P1 = 0x01, // Parameter 1 P2 = 0x14, // Parameter 2 }.ToArray(), null); service.OnDeactivated(DeactivationReason.LinkLoss); logger.Trace("Done"); } } catch (Exception e) { logger.Error("Exception thrown: {0}", e.Message); } }
public bool WritePage(byte pageIndex, byte[] data) { var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.UpdateBinary, P1 = 0x00, P2 = pageIndex, Data = data }; Console.WriteLineFormatted("--> Write MIFARE Block = {0}", Color.Blue, Color.White, pageIndex); Console.WriteLineFormatted("--> C-APDU: {0}", Color.Blue, Color.White, BitConverter.ToString(updateBinaryCmd.ToArray())); var responses = _isoReader.Transmit(updateBinaryCmd); DumpResponse(responses); return(IsSuccess(responses)); }
public byte[] ReadPages(byte pageIndex, byte readSize = 0x04) { unchecked { var isFirstBlock = pageIndex == 0; var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.ReadBinary, P1 = 0x00, P2 = pageIndex, Le = isFirstBlock ? 0x10 : readSize }; Console.WriteLineFormatted("--> Read MIFARE Block = {0}", Color.Blue, Color.White, pageIndex); Console.WriteLineFormatted("--> C-APDU: {0}", Color.Blue, Color.White, BitConverter.ToString(readBinaryCmd.ToArray())); var responses = _isoReader.Transmit(readBinaryCmd); DumpResponse(responses); if (IsSuccess(responses)) { return(responses.GetData()); } return(null); } }
private void Button_ReadCardType_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' 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 = 0xF3, P2 = 0x00, Le = 0 // We don't know the ID tag size }; using (rfidReader.Transaction(SCardReaderDisposition.Leave)) { textBox_Log.Text += "Retrieving the UID .... " + "\r\n"; 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); textBox_Log.Text += "SW1: " + responseApdu.SW1.ToString() + ", SW2: " + responseApdu.SW2.ToString() + "\r\n"; if (responseApdu.HasData) { textBox_Log.Text += "CardType: " + BitConverter.ToString(responseApdu.GetData()) + "\r\n"; } else { textBox_Log.Text += "Uid: No uid received" + "\r\n"; } } } } textBox_Log.Text += "-----------------------------------------------\r\n"; }
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 submit_Click(object sender, RoutedEventArgs e) { try { using (var ctx = ContextFactory.Instance.Establish(SCardScope.User)) { var firstReader = ctx .GetReaders() .FirstOrDefault(); if (firstReader == null) { System.Diagnostics.Debug.WriteLine("No reader connected."); return; } using (var isoReader = new IsoReader(context: ctx, readerName: firstReader, mode: SCardShareMode.Shared, protocol: SCardProtocol.Any)) { var selectApdu = new CommandApdu(IsoCase.Case4Short, isoReader.ActiveProtocol) { CLA = 0x00, INS = 0xA4, P1 = 0x04, P2 = 0x00, Data = new byte[] { 0xD1, 0x58, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11 }, Le = 0x00 }; System.Diagnostics.Debug.WriteLine("Send Select APDU command: \r\n{0}", BitConverter.ToString(selectApdu.ToArray())); var selectResponse = isoReader.Transmit(selectApdu); System.Diagnostics.Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", selectResponse.SW1, selectResponse.SW2); var readProfileApdu = new CommandApdu(IsoCase.Case4Short, isoReader.ActiveProtocol) { CLA = 0x00, INS = 0xCA, P1 = 0x11, P2 = 0x00, Data = new byte[] { 0x00, 0x00 }, Le = 0x00 }; System.Diagnostics.Debug.WriteLine("Send Read Profile APDU command: \r\n{0}", BitConverter.ToString(readProfileApdu.ToArray())); var profileResponse = isoReader.Transmit(readProfileApdu); System.Diagnostics.Debug.WriteLine("SW1 SW2 = {0:X2} {1:X2}", profileResponse.SW1, profileResponse.SW2); if (profileResponse.HasData) { var data = profileResponse.GetData(); var cardNumber = GetCardNumber(data[..12]);
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"; }