public void Done() { try { if (sam != null) { if (sam.IsConnected) { sam.Disconnect(SCardReaderDisposition.Unpower); } sam.Dispose(); } if (reader != null) { if (reader.IsConnected) { reader.Disconnect(SCardReaderDisposition.Unpower); } reader.Dispose(); } } catch (Exception E) { // !!! } }
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 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 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); } }
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); }
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 static void Flush() { m_hcontext.Cancel(); if (m_reader != null) { m_reader.Disconnect(SCardReaderDisposition.Unpower); Console.WriteLine("Card Dispose."); } }
public static void Main() { var context = new SCardContext(); context.Establish(SCardScope.System); var readerNames = context.GetReaders(); if (readerNames == null || readerNames.Length < 1) { Console.WriteLine("You need at least one reader in order to run this example."); Console.ReadKey(); return; } // Receive the ATR of each reader by using the GetAttrib function foreach (var readerName in readerNames) { var reader = new SCardReader(context); Console.Write("Trying to connect to reader.. " + readerName); // Connect to the reader, error if no card present. var rc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (rc != SCardError.Success) { Console.WriteLine(" failed. No smart card present? " + SCardHelper.StringifyError(rc) + "\n"); } else { Console.WriteLine(" done."); // receive ATR string attribute byte[] atr; rc = reader.GetAttrib(SCardAttribute.AtrString, out atr); if (rc != SCardError.Success) { // ATR not supported? Console.WriteLine("Error by trying to receive the ATR. {0}\n", SCardHelper.StringifyError(rc)); } else { Console.WriteLine("ATR: {0}\n", BitConverter.ToString(atr ?? new byte[] {})); } reader.Disconnect(SCardReaderDisposition.Leave); } } // We MUST release here since we didn't use the 'using(..)' statement context.Release(); Console.ReadKey(); }
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); }
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(); }
/// <summary> /// Receive the ATR of each reader in <paramref name="readerNames"/> by using the GetAttrib function /// </summary> /// <param name="context">Connection context</param> /// <param name="readerNames">Readers from which the ATR should be requested</param> private static void DisplayAtrs(ISCardContext context, IEnumerable <string> readerNames) { foreach (var readerName in readerNames) { using (var reader = new SCardReader(context)) { if (!ConnectReader(reader, readerName)) { // error while connecting .. continue; } DisplayCardAtr(reader); reader.Disconnect(SCardReaderDisposition.Leave); } } }
public Boolean Close() { try { _reader.Disconnect(SCardReaderDisposition.Leave); _hContext.Release(); return(true); } catch (PCSCException ex) { _error_code = ECODE_SCardError; _error_message = "Close Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; Debug.Print(_error_message); return(false); } }
// Pobranie ATR danej karty private void DisplayAtrs(ISCardContext context, IEnumerable <string> readerNames) { foreach (var readerName in readerNames) { using (var reader = new SCardReader(context)) { if (!ConnectReader(reader, readerName)) { continue; } // Wyświetlanie ATR DisplayCardAtr(reader); // Rozłączenie z czytnikiem reader.Disconnect(SCardReaderDisposition.Leave); } } }
/// <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> /// 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); } } }
void CardInserted(object sender, CardStatusEventArgs args) { SCardMonitor monitor = (SCardMonitor)sender; Log("CardInserted Event for reader: " + args.ReaderName); try { SCardReader reader = new SCardReader(m_card_context); if (reader.Connect(args.ReaderName, SCardShareMode.Shared, SCardProtocol.Any) == SCardError.Success) { DumpStatus(reader); IsoCard card = new IsoCard(reader); if (CardDumper.IsKeyEnabled("DumpCard")) { DumpCard(card); } if (CardDumper.IsKeyEnabled("DumpMoney")) { DumpMoney(card); } if (!string.IsNullOrEmpty(CardDumper.GetConfigurationKey("UpdateMoney"))) { UpdateMoney(card); } } reader.Disconnect(SCardReaderDisposition.Reset); } catch (Exception ex) { Log("Exception: " + ex.ToString()); } }
static void Main() { using (var context = new SCardContext()) { context.Establish(SCardScope.System); // retrieve all reader names var readerNames = context.GetReaders(); if (readerNames == null || readerNames.Length < 1) { Console.WriteLine("No readers found."); Console.ReadKey(); return; } // get the card status of each reader that is currently connected foreach (var readerName in readerNames) { using (var reader = new SCardReader(context)) { Console.WriteLine("Trying to connect to reader {0}.", readerName); var sc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc == SCardError.Success) { DisplayReaderStatus(reader); reader.Disconnect(SCardReaderDisposition.Reset); } else { Console.WriteLine("No card inserted or reader is reserved exclusively by another application."); Console.WriteLine("Error message: {0}\n", SCardHelper.StringifyError(sc)); } } } Console.ReadKey(); } }
public static void GetUID(string readerName) { try { var c = Console.ForegroundColor; //Console.Write("Scan: "); Console.ForegroundColor = ConsoleColor.DarkGreen; using (var ctx = _contextFactory.Establish(SCardScope.System)) { using (var rfidReader = new SCardReader(ctx)) // 'using' statement to make sure the reader will be disposed (disconnected) on exit { var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { Console.ForegroundColor = ConsoleColor.Red; Console.Write($"{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) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Could not begin transaction."); } else { var receiveBuffer = new byte[256]; var adpuSunst = 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) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("\tError: " + SCardHelper.StringifyError(sc)); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); Console.ForegroundColor = ConsoleColor.Green; Console.Write($"{(responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"),-22} "); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write($"{responseApdu.SW1:X2} {responseApdu.SW2:X2} "); DisplayCardAtr(reader: rfidReader); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); } } } } Console.ForegroundColor = c; } catch (Exception ex) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n{ex}\n"); Console.ForegroundColor = c; } }
public byte[] ReadNIS(string reader) { // Connection to reader var sc = _peripheral.Connect(reader, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { throw new Exception(string.Format("Could not connect to reader {0}:\n{1}", reader, SCardHelper.StringifyError(sc))); } try { CommandApdu apdu; ResponseApdu rapdu; byte[] receiveBuffer; /* 00 A4 - 04 0C 0D - A0 00 00 00 30 80 00 00 00 09 81 60 01 Selezione Applet CIE */ receiveBuffer = new byte[2]; apdu = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0XA4, P1 = 0x04, P2 = 0x0C, Le = 0x0D, Data = new byte[] { (byte)0xA0, 0x00, 0x00, 0x00, 0x30, (byte)0x80, 0x00, 0x00, 0x00, 0x09, (byte)0x81, 0x60, 0x01 } }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); /* 00 A4 - 04 0C 06 - A0 00 00 00 00 39 Selezione DF_CIE */ receiveBuffer = new byte[2]; apdu = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0XA4, P1 = 0x04, P2 = 0x0C, Le = 0x00, Data = new byte[] { (byte)0xA0, 0x00, 0x00, 0x00, 0x00, 0x39 } }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); /* 00 B0 - 81 00 00 Lettura NIS */ receiveBuffer = new byte[14]; apdu = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0XB0, P1 = 0x81, P2 = 0x00, Le = 0x00 }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol); var NIS_ID = rapdu.GetData(); /* 00 B0 - 85 00 00 Lettura chiave pubblica - 1*/ receiveBuffer = new byte[233]; apdu = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0XB0, P1 = 0x85, P2 = 0x00, Le = 0x00 }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol); var pubkey1 = rapdu.GetData(); /* 00 B0 - 85 E7 00 - Lettura chiave pubblica - 2 */ receiveBuffer = new byte[233]; apdu = new CommandApdu(IsoCase.Case2Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0XB0, P1 = 0x85, P2 = 0xE7, Le = 0x00 }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, _peripheral.ActiveProtocol); var pubkey2 = rapdu.GetData(); //Combine pubkey1 and pubkey2 to obtain ASN1 structure that contain 2 children, modulus and exponent //that is used to create RSA crypto service provider var pubKeyAsn1 = ASN1Tag.Parse(pubkey1.Combine(pubkey2)); /* 00 22 - 41 A4 06 - 80 01 02 84 01 83 - Selezione chiave int-auth */ receiveBuffer = new byte[2]; apdu = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0x22, P1 = 0x41, P2 = 0xA4, Le = 0x02, Data = new byte[] { 0x80, 0x01, 0x02, 0x84, 0x01, 0x83 } }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); /* Generate random to perform sign and verify */ var challenge = ByteArrayOperations.GenerateRandomByteArray(8); /* 00 88 - 00 00 08 - hashChallenge 00 int-auth*/ receiveBuffer = new byte[258]; apdu = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0x88, P1 = 0x00, P2 = 0x00, Le = 0x00, Data = challenge }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, _peripheral.ActiveProtocol); var signedData = rapdu.GetData(); //Verify challenge with public key using (var rsa = RSA.Create()) { var modulus = pubKeyAsn1.Child(0, 0x02).Data; // modulus. 02 Verify that result is a INTEGER var exp = pubKeyAsn1.Child(1, 0x02).Data; // exp. 02 Verify that result is a INTEGER if (!rsa.PureVerify(challenge, signedData, modulus, exp)) { throw new Exception("Unable to verify challenge"); } } //Read SOD data record var idx = 0; var size = 0xe4; byte[] data; byte[] sodIASData = new byte[0]; bool sodLoaded = false; while (!sodLoaded) { var hexS = idx.ToString("X4"); receiveBuffer = new byte[233]; apdu = new CommandApdu(IsoCase.Case4Short, _peripheral.ActiveProtocol) { CLA = 0x00, INS = 0xB1, P1 = 0x00, P2 = 0x06, Le = 0x00, Data = new byte[] { 0x54, 0x02, byte.Parse(hexS.Substring(0, 2), System.Globalization.NumberStyles.HexNumber), byte.Parse(hexS.Substring(2, 2), System.Globalization.NumberStyles.HexNumber) } }; sc = _peripheral.Transmit( SCardPCI.GetPci(_peripheral.ActiveProtocol), apdu.ToArray(), new SCardPCI(), ref receiveBuffer); rapdu = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, _peripheral.ActiveProtocol); data = rapdu.GetData(); var offset = 2; if (data[1] > 0x80) { offset = 2 + (data[1] - 0x80); } var buf = data.SubArray(offset, data.Length - offset); sodIASData = sodIASData.Combine(buf); idx += size; if (data[2] != 0xe4) { sodLoaded = true; } } //Create IAS ASN1 object var ias = IASSod.Create(sodIASData); var isValid = ias.Verify(NIS_ID); //Verify integrity of data if (isValid) { return(NIS_ID); } return(null); } catch (Exception ex) { throw ex; } finally { _peripheral.Disconnect(SCardReaderDisposition.Reset); } }
// Obsługa przycisku wysłania komend private void ButtonTransmitCommand_Click(object sender, EventArgs e) { // Utworzenie sesji połączenia var contextFactory = ContextFactory.Instance; using (var context = contextFactory.Establish(SCardScope.System)) { // Pobranie nazw czytników var readerNames = context.GetReaders(); if (NoReaderFound(readerNames)) { MessageBox.Show("Brak podłączonych urządzeń"); return; } // Przypisanie nazwy czytnika var readerName = readerNames[0]; if (readerName == null) { return; } using (var rfidReader = new SCardReader(context)) { //przypisanie połaczenia za pośrednictwerm RFID var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) // W przypadku niepowodzenia { MessageBox.Show("Brak połączenia" + readerName + SCardHelper.StringifyError(sc)); return; } // pobranie komendy z pola tekstowego byte[] command = Encoding.ASCII.GetBytes(textBoxCommand.Text); sc = rfidReader.BeginTransaction(); if (sc != SCardError.Success) { MessageBox.Show(""); return; } var receivePci = new SCardPCI(); // IO zwraca protocol control information. var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol); var receiveBuffer = new byte[256]; 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) { MessageBox.Show("BŁĄD: " + SCardHelper.StringifyError(sc)); } // OPOWIEDZ APDU var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); textBoxAnswer.Text = responseApdu.SW1.ToString() + " " + responseApdu.SW2 + (responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : ""); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); } } }
private void Monitor_CardInserted(object sender, CardStatusEventArgs e) { using (var context = _contextFactory.Establish(SCardScope.System)) { // 'using' statement to make sure the reader will be disposed (disconnected) on exit using (var rfidReader = new SCardReader(context)) { var sc = rfidReader.Connect(e.ReaderName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { Debug.WriteLine("Could not connect to reader {0}:\n{1}", e.ReaderName, SCardHelper.StringifyError(sc)); return; } var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 // We don't know the ID tag size }; sc = rfidReader.BeginTransaction(); if (sc != SCardError.Success) { Debug.WriteLine("Could not begin transaction."); return; } 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)); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); Debug.WriteLine("\nRaw UID: " + (responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received")); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); if (responseApdu.HasData) { SendRco(UidToRco(responseApdu.GetData()), BitConverter.ToString(responseApdu.GetData()), e.ReaderName); } } } }
private static string getPanNumber1(SCardContext context, string readerName) { var rfidReader = new SCardReader(context); byte[] readRecord = new byte[0]; byte x = 0x00; var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { return(null); } //----------------Get AID--------------------------- var apdu = new CommandApdu(IsoCase.Case4Short, rfidReader.ActiveProtocol) { CLA = 0x00, INS = 0xA4, P1 = 0x04, P2 = 0x00, Le = 0x00, Data = selectAid }; var receivePci = new SCardPCI(); var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol); var receiveBuffer = new byte[256]; var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case4Short, rfidReader.ActiveProtocol); String aid; byte[] aidByte = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case4Short); if (aidByte == null) { return(null); } String pAid = ByteArrayToHexString(aidByte); int aidInd = pAid.LastIndexOf("4F07"); aid = pAid.Substring(aidInd + 4, 14); //------------------------ end ------------------------------ if (aid.Equals("A0000000041010")) { readRecord = selectMCAID; x = 0x14; } else if (aid.Equals("A0000000031010")) { readRecord = selectVisaAID; x = 0x1C; } //----------------selectMCAID--------------------------- apdu = new CommandApdu(IsoCase.Case4Short, rfidReader.ActiveProtocol) { CLA = 0x00, INS = 0xA4, P1 = 0x04, P2 = 0x00, Le = 0x00, Data = readRecord }; byte[] selectTAypeCard = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case4Short); if (selectTAypeCard == null) { return(null); } //------------------------ end ------------------------------ apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol) { CLA = 0x00, INS = 0xB2, P1 = 0x01, P2 = x, Le = 0x00 }; String pan; byte[] a = sendRequest(rfidReader, sc, receivePci, sendPci, apdu, responseApdu, IsoCase.Case2Short); //(byte[])responseApdu.GetData(); if (a == null) { return(null); } String p = ByteArrayToHexString(a); int panInd = p.LastIndexOf("5A08"); pan = p.Substring(panInd + 4, 16); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); return(pan); }
static void Main(string[] args) { SCardContext ctx = new SCardContext(); ctx.Establish(SCardScope.System); string[] readernames = ctx.GetReaders(); if (readernames == null || readernames.Length < 1) { throw new Exception("You need at least one reader in order to run this example."); } // Show available readers. Console.WriteLine("Available readers: "); for (int i = 0; i < readernames.Length; i++) { Console.WriteLine("[" + i + "] " + readernames[i]); } int num = 0; if (readernames.Length > 1) { // Ask the user which one to choose. Console.Write("Which reader is an RFID reader? "); string relin = Console.ReadLine(); if (!(int.TryParse(relin, out num)) || num < 0 || num > readernames.Length) { Console.WriteLine("An invalid number has been entered. Exiting."); return; } } string readername = readernames[num]; SCardReader RFIDReader = new SCardReader(ctx); SCardError rc = RFIDReader.Connect( readername, SCardShareMode.Shared, SCardProtocol.Any); if (rc != SCardError.Success) { Console.WriteLine("Unable to connect to RFID card / chip. Error: " + SCardHelper.StringifyError(rc)); return; } // prepare APDU byte[] ucByteSend = new byte[] { 0xFF, // the instruction class 0xCA, // the instruction code 0x00, // parameter to the instruction 0x00, // parameter to the instruction 0x00 // size of I/O transfer }; byte[] ucByteReceive = new byte[10]; Console.Out.WriteLine("Retrieving the UID .... "); rc = RFIDReader.BeginTransaction(); if (rc != SCardError.Success) { throw new Exception("Could not begin transaction."); } SCardPCI ioreq = new SCardPCI(); /* creates an empty object (null). * IO returned protocol control information. */ IntPtr sendPci = SCardPCI.GetPci(RFIDReader.ActiveProtocol); rc = RFIDReader.Transmit( sendPci, /* Protocol control information, T0, T1 and Raw * are global defined protocol header structures. */ ucByteSend, /* the actual data to be written to the card */ ioreq, /* The returned protocol control information */ ref ucByteReceive); if (rc == SCardError.Success) { Console.Write("Uid: "); for (int i = 0; i < (ucByteReceive.Length); i++) { Console.Write("{0:X2} ", ucByteReceive[i]); } Console.WriteLine(""); } else { Console.WriteLine("Error: " + SCardHelper.StringifyError(rc)); } RFIDReader.EndTransaction(SCardReaderDisposition.Leave); RFIDReader.Disconnect(SCardReaderDisposition.Reset); return; }
public 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 = new SCardReader(context)) { var sc = rfidReader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any); if (sc != SCardError.Success) { Console.WriteLine("Could not connect to reader {0}:\n{1}", readerName, SCardHelper.StringifyError(sc)); Console.ReadKey(); return; } var apdu = new CommandApdu(IsoCase.Case2Short, rfidReader.ActiveProtocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 // We don't know the ID tag size }; sc = rfidReader.BeginTransaction(); if (sc != SCardError.Success) { Console.WriteLine("Could not begin transaction."); Console.ReadKey(); return; } Console.WriteLine("Retrieving the UID .... "); var receivePci = new SCardPCI(); // IO returned protocol control information. var sendPci = SCardPCI.GetPci(rfidReader.ActiveProtocol); var receiveBuffer = new byte[256]; var command = apdu.ToArray(); sc = rfidReader.Transmit( sendPci, // Protocol Control Information (T0, T1 or Raw) command, // command APDU receivePci, // returning Protocol Control Information ref receiveBuffer); // data buffer if (sc != SCardError.Success) { Console.WriteLine("Error: " + SCardHelper.StringifyError(sc)); } var responseApdu = new ResponseApdu(receiveBuffer, IsoCase.Case2Short, rfidReader.ActiveProtocol); Console.Write("SW1: {0:X2}, SW2: {1:X2}\nUid: {2}", responseApdu.SW1, responseApdu.SW2, responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "No uid received"); rfidReader.EndTransaction(SCardReaderDisposition.Leave); rfidReader.Disconnect(SCardReaderDisposition.Reset); Console.ReadKey(); } } }
public string 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) { SCardContext ctx = new SCardContext(); ctx.Establish(SCardScope.System); // retrieve all reader names string[] readernames = ctx.GetReaders(); if (readernames != null) { // get the card status of each reader that is currently connected foreach (string readername in readernames) { SCardReader reader = new SCardReader(ctx); Console.Write("Trying to connect to reader " + readername + ".."); SCardError serr = reader.Connect(readername, SCardShareMode.Shared, SCardProtocol.Any); if (serr == SCardError.Success) { // SmartCard inserted, reader is now connected. Console.WriteLine(" done."); string[] tmpreadernames; SCardProtocol proto; SCardState state; byte[] atr; serr = reader.Status( out tmpreadernames, // contains the reader name(s) out state, // contains the current state (flags) out proto, // contains the currently used communication protocol out atr); // contains the card ATR if (serr == SCardError.Success) { Console.WriteLine("Connected with protocol " + proto + " in state " + state); if (atr != null && atr.Length > 0) { Console.Write("Card ATR: "); foreach (byte b in atr) { Console.Write("{0:X2}", b); } Console.WriteLine(); } Console.WriteLine(); } else { Console.WriteLine("Unable to retrieve card status.\nError message: " + SCardHelper.StringifyError(serr) + ".\n"); } reader.Disconnect(SCardReaderDisposition.Reset); } else { /* SmardCard not inserted or reader is reserved exclusively by * another application. */ Console.WriteLine(" failed.\nError message: " + SCardHelper.StringifyError(serr) + ".\n"); } } } return; }
public 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); } }
/// <summary> /// Will try to connect to _connectedReader and read the card. /// </summary> /// <returns>Either the data from the card or the error message. Or if 'uidOnly' is true, just the UID prefixed with 'UID^' and ending with '^'</returns> public string ReadCard(bool uidOnly = false) { SCardContext context = new SCardContext(); context.Establish(SCardScope.System); SCardReader reader = new SCardReader(context); SCardError result = reader.Connect(_connectedReader, SCardShareMode.Shared, SCardProtocol.Any); if (result != SCardError.Success) { context.Dispose(); reader.Dispose(); return(string.Format("No card is detected (or reader reserved by another application){0}{1}", Environment.NewLine, SCardHelper.StringifyError(result))); } string[] readerNames; SCardProtocol protocol; SCardState state; byte[] atr; result = reader.Status(out readerNames, out state, out protocol, out atr); if (result != SCardError.Success) { context.Dispose(); reader.Dispose(); return(string.Format("Unable to read from card.{0}{1}", Environment.NewLine, SCardHelper.StringifyError(result))); } string message = string.Format("Card detected:{0}Protocol: {1}{0}State: {2}{0}ATR: {3}{0}", Environment.NewLine, protocol, state, BitConverter.ToString(atr ?? new byte[0])); CommandApdu apdu = new CommandApdu(IsoCase.Case2Short, reader.ActiveProtocol) { CLA = 0xFF, Instruction = InstructionCode.GetData, P1 = 0x00, P2 = 0x00, Le = 0 }; result = reader.BeginTransaction(); if (result != SCardError.Success) { context.Dispose(); reader.Dispose(); return(string.Format("Cannot start transaction.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result))); } SCardPCI recievePci = new SCardPCI(); IntPtr sendPci = SCardPCI.GetPci(reader.ActiveProtocol); byte[] recieveBuffer = new byte[256]; result = reader.Transmit(sendPci, apdu.ToArray(), recievePci, ref recieveBuffer); if (result != SCardError.Success) { context.Dispose(); reader.Dispose(); return(string.Format("Cannot transmit data.{0} {1}", Environment.NewLine, SCardHelper.StringifyError(result))); } var responseApdu = new ResponseApdu(recieveBuffer, IsoCase.Case2Short, reader.ActiveProtocol); message += string.Format("SW1: {1}{0}SW2: {2}{0}", Environment.NewLine, responseApdu.SW1, responseApdu.SW2); string data = responseApdu.HasData ? BitConverter.ToString(responseApdu.GetData()) : "--"; if (uidOnly) { context.Dispose(); reader.Dispose(); return(string.Format("UID^{0}^", data)); } message += string.Format("UID: {0}", data); reader.EndTransaction(SCardReaderDisposition.Leave); reader.Disconnect(SCardReaderDisposition.Reset); context.Dispose(); reader.Dispose(); return(message); }