void cardMonitor_CardInserted(object sender, CardStatusEventArgs e) { var cardReader = new SCardReader(cardContext); cardReader.Connect(e.ReaderName, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); int rxBuffLen = 32; byte[] recieveBuff = new byte[rxBuffLen]; cardReader.Transmit(new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x04 }, recieveBuff, ref rxBuffLen); string tag = BitConverter.ToString(recieveBuff, 0, rxBuffLen); if (IsMonitoring == true) { base.RaiseTagRead(tag); foreach (var listener in TagListeners) { listener.TagRead(new RFIDTag { RFIDTagType = RFIDTag.TagType.Short, Tag = tag }); } } cardReader.Disconnect(SCardReaderDisposition.Leave); }
public void Connect(int position) { if (hContext.CheckValidity() != PCSC.SCardError.Success) { init(); } // Create a reader object using the existing context reader = new SCardReader(hContext); // Connect to the card SCardError err = reader.Connect(szReaders[position], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(err); switch (reader.ActiveProtocol) { case SCardProtocol.T0: pioSendPci = SCardPCI.T0; break; case SCardProtocol.T1: pioSendPci = SCardPCI.T1; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "Protocol not supported: " + reader.ActiveProtocol.ToString()); } }
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); }
private void _dcmd(byte[] _name) { try { // initialize the reader. SCardReader _reader = new SCardReader(_context); _context.Establish(SCardScope.System); // connect to the reader, protocol not limited. SCardError _error = _reader.Connect(_port, SCardShareMode.Direct, SCardProtocol.Unset); if (CheckError(_error)) { throw new PCSCException(_error); } byte[] _pbRecvBuffer = new byte[256]; // use the hexadecimal code to control the LED. _error = _reader.Control(IOCTL_SCL2000_CTL, _name, ref _pbRecvBuffer); if (CheckError(_error)) { throw new PCSCException(_error); } string _result = ToHexString(_pbRecvBuffer); // disconnect the reader. _reader.Disconnect(SCardReaderDisposition.Leave); } catch (PCSCException ex) { Console.WriteLine(ex.Message + " (" + ex.SCardError.ToString() + ") "); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// NFC 리더기로 Message를 보내는 함수입니다. 보낼 명령어를 string 형태로 입력하면 Byte 배열로 자동 변환됩니다. /// </summary> /// <param name="message">보낼 메세지를 string 형태로 입력합니다.</param> /// <returns>APDU 통신 결과를 리턴합니다.</returns> public string SendMessageToReader(string message) { SCardReader reader = new SCardReader(SContext); // 카드에 연결합니다. SCardError err = reader.Connect(readers[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); long SendPCILength = 0; switch (reader.ActiveProtocol) { case SCardProtocol.T0: SendPCILength = (long)SCardPCI.T0; break; case SCardProtocol.T1: SendPCILength = (long)SCardPCI.T1; break; default: throw new Exception("Protocol not support,"); } byte[] receiveBuffer = new byte[256]; err = reader.Transmit(StringToByte(message), ref receiveBuffer); CheckError(err); return(ByteToString(receiveBuffer)); }
//} while (flag ); public static void connection() { context = new SCardContext(); context.Establish(SCardScope.System); string[] readerList = context.GetReaders(); Boolean noReaders = readerList.Length <= 0; if (noReaders) { throw new PCSCException(SCardError.NoReadersAvailable, "Czytnik nie zostal odnaleziony"); // Console.WriteLine("Czytnik nie zostal odnaleziony"); } int counter = 1; Console.WriteLine("Wybierz czytnik: "); foreach (string element in readerList) { Console.WriteLine("F" + counter + " -> " + element); counter++; } var input = Console.ReadKey(); string tmp = readerList[0]; switch (input.Key) { case ConsoleKey.F1: tmp = readerList[0]; break; case ConsoleKey.F2: tmp = readerList[1]; break; } Console.WriteLine("Wcisnij dowolny klawisz by kontynowac..."); Console.ReadKey(); reader = new SCardReader(context); error = reader.Connect(tmp, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); checkError(error); if (reader.ActiveProtocol == SCardProtocol.T0) { intptr = SCardPCI.T0; } else if (reader.ActiveProtocol == SCardProtocol.T1) { intptr = SCardPCI.T1; } else { Console.WriteLine("Protokol nie jest obslugiwany"); Console.WriteLine("Wcisnij dowolny klawisz by kontynowac..."); Console.ReadKey(); } }
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"); }
static void Main(string[] args) { var context = new SCardContext(); context.Establish(SCardScope.System); // Get readers Console.WriteLine("Currently connected readers: "); var readerNames = context.GetReaders(); foreach (var readerName in readerNames) { Console.WriteLine("\t" + readerName); } if (readerNames.Length == 0) { Console.WriteLine("No readers"); } else { var reader = new SCardReader(context); reader.Connect(readerNames[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); IntPtr protocol; switch (reader.ActiveProtocol) { case SCardProtocol.T0: protocol = SCardPCI.T0; break; case SCardProtocol.T1: protocol = SCardPCI.T1; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "No protocol: " + reader.ActiveProtocol.ToString()); } // SELECT TELECOM SendCommand(reader, protocol, new byte[] { 0xA0, 0xA4, 0x00, 0x00, 0x02, 0x7F, 0x10, }, "SELECT TELECOM", ReadType.Bytes); // GET RESPONSE SendCommand(reader, protocol, new byte[] { 0xA0, 0xC0, 0x00, 0x00, 0x16 }, "GET RESPONSE", ReadType.Bytes); // SELECT ADN SendCommand(reader, protocol, new byte[] { 0xA0, 0xA4, 0x00, 0x00, 0x02, 0x6F, 0x3A }, "SELECT ADN", ReadType.Bytes); // GET RESPONSE SendCommand(reader, protocol, new byte[] { 0xA0, 0xC0, 0x00, 0x00, 0x0F }, "GET RESPONSE", ReadType.Bytes); // READ RECORD for (byte i = 0; i < 45; ++i) { SendCommand(reader, protocol, new byte[] { 0xA0, 0xB2, i, 0x04, 0x2E }, "READ RECORD", ReadType.ASCII); } context.Release(); } Console.Read(); }
static void Main(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(); }
// public byte[] ReadBlockRange(byte msb, byte blockFrom, byte blockTo) // { // byte i; // int nBlock = 0; // int count = 0; // // for (i = blockFrom; i <= blockTo;) // { // if ((i + 1) % 4 == 0) continue; // nBlock++; // } // // var dataOut = new byte[nBlock * 16]; // for (i = blockFrom; i <= blockTo; i++) // { // if ((i + 1) % 4 == 0) continue; // Array.Copy(ReadBlock(msb, i), 0, dataOut, count * 16, 16); // count++; // } // // return dataOut; // } public void connect() { var ctx = new SCardContext(); ctx.Establish(SCardScope.System); var reader = new SCardReader(ctx); reader.Connect(nfcReader, SCardShareMode.Shared, SCardProtocol.Any); }
public static void connection() { context = new SCardContext(); //nawiązanie połączenia z czytnikiem string[] readerList = context.GetReaders(); // wczytanie dostępnych czytników do listy Boolean noReaders = readerList.Length <= 0; if (noReaders) { throw new PCSCException(SCardError.NoReadersAvailable, "Czytnik nie zostal odnaleziony"); } int counter = 1; Console.WriteLine("Wybierz czytnik: "); foreach (string element in readerList) { Console.WriteLine("F" + counter + " -> " + element); counter++; } var input = Console.ReadKey(); string tmp = readerList[0]; switch (input.Key) { case ConsoleKey.F1: tmp = readerList[0]; break; case ConsoleKey.F2: tmp = readerList[1]; break; } Console.WriteLine("Wcisnij dowolny klawisz by kontynowac..."); Console.ReadKey(); //w zależności od wybranego czytniku wybrany zostanie odpowiedni protokół T0 lub T1. W przypadku pozostałych zostanie wyrzucony wyjątek reader = new SCardReader(context); error = reader.Connect(tmp, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); checkError(error); if (reader.ActiveProtocol == SCardProtocol.T0) { intptr = SCardPCI.T0; } else if (reader.ActiveProtocol == SCardProtocol.T1) { intptr = SCardPCI.T1; } else { Console.WriteLine("Protokol nie jest obslugiwany"); Console.WriteLine("Wcisnij dowolny klawisz by kontynowac..."); Console.ReadKey(); } }
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(); }
/// <summary> /// Creates a new <see cref="CCIDDriver"/> by connecting to the device specified by <paramref name="name"/>. /// </summary> /// <param name="name">Device name</param> /// <param name="mode">Connection mode</param> /// <param name="protocol">Connection protocol</param> /// <returns>Returns a new <see cref="CCIDDriver"/> if the device was found.</returns> /// <exception cref="ConnectionException">Thrown if the device is not found or may not be connected to at this time.</exception> public static CCIDDriver OpenDevice(string name, SCardShareMode mode = SCardShareMode.Exclusive, SCardProtocol protocol = SCardProtocol.Any) { ISCardContext ctx = ContextFactory.Instance.Establish(SCardScope.System); ISCardReader reader = new SCardReader(ctx); if (reader.Connect(name, mode, protocol) != SCardError.Success) { throw new ConnectionException("Failed to connect to device."); } return(new CCIDDriver(ctx, reader)); }
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); }
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); }
public bool ReadVersionInformation() { bool Result = false; Version = ""; byte[] capdu = new byte[] { 0xE0, 0x00, 0x00, 0x18, 0x00 }; byte[] rapdu = new byte[128]; try { SCardError ret = reader.Connect(readers[indexReader], SCardShareMode.Direct, SCardProtocol.Unset); Result = (ret == SCardError.Success); if (Result) { ret = reader.Control(SCARD_CTL_CODE(3500), capdu, ref rapdu); Result = (ret == SCardError.Success) && (rapdu.Length >= 6) && (rapdu[0] == 0xE1) && (rapdu[1] == 0x00) && (rapdu[2] == 0x00) && (rapdu[3] == 0x00); if (Result) { Version = System.Text.ASCIIEncoding.ASCII.GetString(rapdu, 5, rapdu[4]); } reader.Disconnect(SCardReaderDisposition.Leave); } } catch (Exception E) { Result = false; } return(Result); }
/// <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); }
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(); }
// Łą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); } }
/// <summary> /// NFC Tag에 값을 쓰는 함수입니다. 현재는 ASCII 코드를 지원하고 4글자만 사용할 수 있습니다. /// </summary> /// <param name="message">4글자의 작성 메세지를 입력합니다.</param> /// <returns>쓰기의 성공 여부를 확인합니다.</returns> public bool WriteToTag(string message) { if (message.Length > 4) { throw new Exception("Only 4 letters of the message. Sorry."); } SCardReader reader = new SCardReader(SContext); // 카드에 연결합니다. SCardError err = reader.Connect(readers[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); long SendPCILength = 0; switch (reader.ActiveProtocol) { case SCardProtocol.T0: SendPCILength = (long)SCardPCI.T0; break; case SCardProtocol.T1: SendPCILength = (long)SCardPCI.T1; break; default: throw new Exception("Protocol not support,"); } byte[] receiveBuffer = new byte[256]; byte[] header = new byte[] { 0xFF, 0xD6, 0x00, 0x04, 0x04 }; byte[] Message = StringToByte(message); byte[] sendMessage; sendMessage = new byte[header.Length + Message.Length]; Array.Copy(header, 0, sendMessage, 0, header.Length); Array.Copy(Message, 0, sendMessage, 5, Message.Length); err = reader.Transmit(sendMessage, ref receiveBuffer); CheckError(err); return(true); }
public string GetReaderPort(string reader) { using (var context = new SCardContext()) { context.Establish(SCardScope.System); var scReader = new SCardReader(context); SCardError error = scReader.Connect(reader, SCardShareMode.Shared, SCardProtocol.Any); byte[] port; error = scReader.GetAttrib(SCardAttribute.ChannelId, out port); context.Release(); StringBuilder builder = new StringBuilder(); foreach (var b in port) { builder.Append(Convert.ToString(b, 16)); } return(builder.ToString()); } }
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(); } }
/// <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> /// NFC 리더기로 Message를 보내는 함수입니다. MessageList 열거형으로 보낼 메세지를 선택하시고 실행하시면 APDU 통신을 통해 바로 결과를 string으로 리턴합니다. /// </summary> /// <param name="message">NFC 리더기로 보낼 MessageList를 선택하여 입력합니다.</param> /// <returns>APDU 통신 결과를 리턴합니다.</returns> public string SendMessageToReader(MessageList message) { SCardReader reader = new SCardReader(SContext); // 카드에 연결합니다. SCardError err = reader.Connect(readers[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); long SendPCILength = 0; switch (reader.ActiveProtocol) { case SCardProtocol.T0: SendPCILength = (long)SCardPCI.T0; break; case SCardProtocol.T1: SendPCILength = (long)SCardPCI.T1; break; default: throw new Exception("Protocol not support,"); } byte[] receiveBuffer = new byte[256]; byte[] sendMessage = null; switch (message) { case MessageList.GetBlockData: sendMessage = new byte[] { 0xFF, 0xB0, 0x00, 0x04, 0x04 }; break; case MessageList.GetCardUID: sendMessage = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; break; } err = reader.Transmit(sendMessage, ref receiveBuffer); CheckError(err); return(ByteToString(receiveBuffer)); }
public byte[] SendApdu(byte[] apdu) { byte[] receiveBuffer = new byte[263]; using (SCardReader scardReader = new SCardReader((ISCardContext)this.Context)) { SCardError code1 = scardReader.Connect(this.selectedReader, SCardShareMode.Shared, SCardProtocol.Any); if (code1 == SCardError.Success) { SCardError code2 = scardReader.Transmit(apdu, ref receiveBuffer); if (code2 == SCardError.Success) { return(receiveBuffer); } PcscService.logger.Warn("Error while sending APDU to smartcard. Error message: " + SCardHelper.StringifyError(code2)); return((byte[])null); } PcscService.logger.Warn("No card inserted or reader is reserved exclusively by another application. Error message: " + SCardHelper.StringifyError(code1)); return((byte[])null); } }
public static void Init() { // Establish Scard Context m_hcontext = new SCardContext(); m_hcontext.Establish(SCardScope.System); // Retrieve the list of Smartcard readers string[] szReaders = m_hcontext.GetReaders(); if (szReaders.Length <= 0) { throw new PCSCException(SCardError.NoReadersAvailable, "Could not found any Smartcard readers."); } Console.WriteLine("reader name: " + szReaders[0]); // Create a reader object using the existing context m_reader = new SCardReader(m_hcontext); // Connect to the card m_err = m_reader.Connect(szReaders[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(m_err); switch (m_reader.ActiveProtocol) { case SCardProtocol.T0: m_pioSendPci = SCardPCI.T0; break; case SCardProtocol.T1: m_pioSendPci = SCardPCI.T1; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "Protocol not supported: " + m_reader.ActiveProtocol.ToString()); } }
public string ReadCardUID() { // initialize the reader. SCardReader _reader = new SCardReader(_context); // connect to the reader, protocol not limited. SCardError _error = _reader.Connect(_port, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); if (CheckError(_error)) { return(string.Empty); } IntPtr _pioSendPci; // according to the active protocol to set the request structure. switch (_reader.ActiveProtocol) { case SCardProtocol.T0: _pioSendPci = SCardPCI.T0; break; case SCardProtocol.T1: _pioSendPci = SCardPCI.T1; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "Protocol Not Supported: " + _reader.ActiveProtocol.ToString()); } byte[] _pbRecvBuffer = new byte[256]; // transmit the data fron reader. _error = _reader.Transmit(_pioSendPci, Get_ID, ref _pbRecvBuffer); string _result = ToHexString(_pbRecvBuffer); if (CheckError(_error)) { return(string.Empty); } return(_result); }
/// <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); } } }