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: {BitConverter.ToString(updateBinaryCmd.ToArray())}"); var response = _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)); }
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: {BitConverter.ToString(loadKeyCmd.ToArray())}"); var response = _isoreader.Transmit(loadKeyCmd); //Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}"); 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 bool UpdateBinary(int msb, int lsb, byte[] data) { unchecked { var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = 0xFF, Instruction = InstructionCode.UpdateBinary, P1 = (byte)msb, P2 = (byte)lsb, Data = data }; Debug.WriteLine(string.Format("Update Binary: {0}", BitConverter.ToString(updateBinaryCmd.ToArray()))); var response = _isoReader.Transmit(updateBinaryCmd); Debug.WriteLine(string.Format("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2)); return(Success(response)); } }
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 bool LoadKey(KeyStructure keyStructure, int keyNumber, byte[] key) { unchecked { var loadKeyCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = 0xFF, Instruction = InstructionCode.ExternalAuthenticate, P1 = (byte)keyStructure, P2 = (byte)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(Success(response)); } }
public override IEnumerable <CommandApdu> AsApdus() { var chunks = this.data.Split(this.blockSize).ToList(); return(chunks.Select((block, index, isLast) => { if (isLast) { this.P1 ^= 0x80; } return CommandApdu.Case3S( ApduClass.GlobalPlatform, ApduInstruction.StoreData, this.P1, (byte)index, block.ToArray()); })); }
private byte[] SendCommand(CommandApdu command) { var response = reader.Transmit(command); if (!response.HasData) { return new byte[] { response.SW1, response.SW2 } } ; var data = response.GetData(); var result = new byte[data.Length + 2]; Buffer.BlockCopy(data, 0, result, 0, data.Length); result[result.Length - 2] = response.SW1; result[result.Length - 1] = response.SW2; return(result); }
bool WriteBlock(IsoCard card, int block, byte[] data) { CommandApdu apdu = card.ConstructCommandApdu(IsoCase.Case3Short); apdu.CLA = 0xFF; apdu.Instruction = InstructionCode.UpdateBinary; apdu.P1 = 0x00; apdu.P2 = (byte)block; apdu.Data = data; Response response = card.Transmit(apdu); if (response.SW1 == (byte)SW1Code.Normal) { return(true); } return(false); }
bool LoadKey(IsoCard card, byte[] key) { CommandApdu apdu = card.ConstructCommandApdu(IsoCase.Case3Short); apdu.CLA = 0xFF; apdu.Instruction = InstructionCode.ExternalAuthenticate; apdu.P1 = 0x20; apdu.P2 = 0x00; apdu.Data = key; Response response = card.Transmit(apdu); if (response.SW1 == (byte)SW1Code.Normal) { return(true); } return(false); }
public static void ReadCard(SCardContext context, string reader, ref string tes) { IsoReader isoReader = new IsoReader(context, reader, SCardShareMode.Shared, SCardProtocol.Any); var apdu = new CommandApdu(IsoCase.Case2Short, isoReader.ActiveProtocol) { CLA = 0xff, // Class. INS = 0xCA, // what instrution you are using. P1 = 0x00, // Parameter 1. P2 = 0x00, // Parameter 2. Le = 0x4 // Length of the return value. }; Response test = isoReader.Transmit(apdu); uID = BitConverter.ToString(test.GetData()); string[] a = uID.Split('-'); Array.Reverse(a); parrent.CardInserted(string.Join("", a)); }
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[] ReadBinary(byte Msb, byte Lsb, int size) { var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any) { CLA = CUSTOM_CLA, Instruction = InstructionCode.ReadBinary, P1 = Msb, P2 = Lsb, Le = size }; //Debug.WriteLine($"Read Binary: {BitConverter.ToString(readBinaryCmd.ToArray())}"); var response = _isoreader.Transmit(readBinaryCmd); //Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}\nData: {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 byte[] Bytes() { var hexLen = new BinaryHex( _offsetLength .Value() .ToString("X4") ).Bytes(); var offsetMSB = hexLen.Skip(0).Take(1).First(); // new HexInt(_offsetLength).Bytes().First(); var offsetLSB = hexLen.Skip(1).Take(1).First(); //new HexInt(_offsetLength + _expectedDataLength).Bytes().First(); var comm = new CommandApdu(_isoCase, _activeProtocol) { CLA = 0x00, Instruction = InstructionCode.ReadBinary, P1 = offsetMSB, P2 = offsetLSB, //new BinaryHex(_offsetLength.ToString("X2")).Bytes().First(), Le = _expectedDataLength.Value() }.ToArray(); return(comm); }
public void ReadData() { var contextFactory = ContextFactory.Instance; using (var ctx = contextFactory.Establish(SCardScope.System)) { using (var isoReader = new IsoReader(ctx, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) { var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any) { CLA = 0xFF, INS = 0xCA, P1 = 0x00, P2 = 0x00 }; var response = isoReader.Transmit(updateBinaryCmd); Console.WriteLine(response.GetData()); Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2); } } }
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"); } }
private static void SetBuzzerState(string readerName, bool enabled) { Console.Write("Setting buzzer state... "); using var ctx = ContextFactory.Instance.Establish(SCardScope.System); using var isoReader = new IsoReader(ctx, readerName, SCardShareMode.Shared, SCardProtocol.Any, false); var p2 = enabled ? (byte)0xFF : (byte)0x00; // Set buzzer output during card detection var apdu = new CommandApdu(IsoCase.Case2Short, isoReader.ActiveProtocol) { CLA = 0xFF, // Class Instruction = 0x00, // Insruction P1 = 0x52, // Parameter 1 P2 = p2, // Parameter 2 - 00h: Buzzer will NOT turn on when a card is detected // FFh: Buzzer will turn on when a card is detected Le = 0x00 // Expected length of the returned data }; var response = isoReader.Transmit(apdu); Console.WriteLine(response.SW1 == 0x90 && response.SW2 == 0x00 ? "Success!" : "ERROR"); }
byte[] ReadBinary(byte msb, byte lsb, int size) { var readerContext = Readers[_activeReaderName]; //// unchecked { var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any) { CLA = CustomCla, Instruction = InstructionCode.ReadBinary, P1 = msb, P2 = lsb, Le = size }; //Debug.WriteLine($"Read Binary: {BitConverter.ToString(readBinaryCmd.ToArray())}"); var response = readerContext.IsoReader.Transmit(readBinaryCmd); var data = response.GetData(); Debug.WriteLine($"SW1 SW2 = {response.SW1:X2} {response.SW2:X2}"); if (data != null) { Debug.WriteLine($"Data: {BitConverter.ToString(data)}"); } if ((response.SW1 == (byte)SW1Code.Normal) && (response.SW2 == 0x00)) { return(response.GetData()); } else { //// throw new Exception("Read binary failed"); return new byte[] { } }; } } #endif }
public override CommandApdu AsApdu() { var apdu = CommandApdu.Case2S(ApduClass.GlobalPlatform, ApduInstruction.Delete, this.P1, this.P2, 0x00); var data = new List <byte>(); switch (this.scope) { case DeleteCommandScope.CardContent: data.AddTLV(TLV.Build((byte)Tag.ExecutableLoadFileOrApplicationAID, this.application)); if (this.token.Any()) { data.AddTLV(TLV.Build((byte)Tag.DeleteToken, this.token)); } break; case DeleteCommandScope.Key: if (this.keyIdentifier == 0 && this.keyVersionNumber == 0) { throw new InvalidOperationException("A key identifier or key version number must be specified."); } if (this.keyIdentifier > 0) { data.AddTLV(TLV.Build((byte)Tag.KeyIdentifier, this.keyIdentifier)); } if (this.keyVersionNumber > 0) { data.AddTLV(TLV.Build((byte)Tag.KeyVersionNumber, this.keyVersionNumber)); } break; } apdu.CommandData = data.ToArray(); return(apdu); }
/// <summary> /// Issues a GPO command. /// </summary> /// <remarks>Pdol data , reponce parsing and storing are handled internaly</remarks> public void GetProcessingOptions() { List <byte> pdoldata = new List <byte> { 0x83 }; var pdol = TLV_SELECT.TagList.SingleOrDefault(t => t.TagStringName == "9F38"); if (pdol != null) { var tempdata = TlvTools.parseTagLengthData(pdol.TagValue.ToArray()); pdoldata.Add((byte)tempdata.Length); pdoldata.AddRange(tempdata); } else { pdoldata.Add(0x00); } CommandApdu apdu = new CommandApdu(IsoCase.Case4Short, _reader.ActiveProtocol) { CLA = new ClassByte(ClaHighPart.Iso8x, SecureMessagingFormat.None, 0), INS = 0xA8, P1 = 0x00, P2 = 00, Data = pdoldata.ToArray() }; var res = _reader.TransmitWithLog(apdu); // data buffer RES_GPO = res.GetData(); GpoTemplateFormat = (RES_GPO[0] == (byte)EmvConstants.GpoTemplateFormat.Format1) ? EmvConstants.GpoTemplateFormat.Format1 : EmvConstants.GpoTemplateFormat.Format2; TLV_GPO = new SmartTlv(RES_GPO); }
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); } }
string ReadUID(IsoCard card) { string ouput = ""; CommandApdu apdu = card.ConstructCommandApdu(IsoCase.Case2Short); apdu.CLA = 0xFF; apdu.Instruction = InstructionCode.GetData; apdu.P1 = 0x00; apdu.P2 = 0x00; apdu.Le = 0x00; Response response = card.Transmit(apdu); if (response.SW1 == (byte)SW1Code.Normal) { byte[] data = response.GetData(); if (data != null) { ouput = ToHex(data); } } return(ouput); }
private new CommandApdu Build(IEnumerable <byte> commandData, byte p2 = 0x00) { return(CommandApdu.Case4S(ApduClass.GlobalPlatform, ApduInstruction.Install, this.P1, p2, commandData.ToArray(), 0x00)); }
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); } }
public static Data GetData() { try { 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(null); } //var name = ChooseReader(readerNames); var name = readerNames.Last(); while (name == null) { return(null); } 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 = 0xFF, // Class Instruction = InstructionCode.GetData, P1 = 0x00, // Parameter 1 P2 = 0x00, // Parameter 2 Le = 0x00 // Expected length of the returned data }; Console.WriteLine("Send APDU with 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)"); return(null); } else { var data = response.GetData(); Console.WriteLine("Challenge: {0}", BitConverter.ToString(data)); var uid = BitConverter.ToString(data); return(Data.GetData().FirstOrDefault(o => o.Uid == BitConverter.ToString(data))); } } } } catch (Exception) { return(null); } }
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(); }
static void Main(string[] args) { // Establish PC/SC context SCardContext ctx = new SCardContext(); ctx.Establish(SCardScope.System); // Create a reader object SCardReader reader = new SCardReader(ctx); // Use the first reader that is found string firstreader = ctx.GetReaders()[0]; // Connect to the card IsoCard card = new IsoCard(reader); card.Connect(firstreader, SCardShareMode.Shared, SCardProtocol.Any); // Build a ATR fetch case CommandApdu apdu = card.ConstructCommandApdu( IsoCase.Case2Short); apdu.CLA = 0x00; // Class apdu.INS = 0x84; // Instruction: GET CHALLENGE apdu.P1 = 0x00; // Parameter 1 apdu.P2 = 0x00; // Parameter 2 apdu.Le = 0x08; // Expected length of the returned data // Transmit the Command APDU to the card and receive the response Response resp = card.Transmit(apdu); // Show SW1SW2 from the last response packet (if more than one has been received). Console.WriteLine("SW1: {0:X2} SW2: {1:X2}", resp.SW1, resp.SW2); byte[] data; // First test - get the data from all response APDUs data = resp.GetData(); if (data != null) { Console.Write("CHALLENGE:"); foreach (byte b in data) { Console.Write(" {0:X2}", b); } Console.WriteLine(); } // Second test - get the data from each response APDU. int i = 0; foreach (ResponseApdu respApdu in resp.ResponseApduList) { data = respApdu.GetData(); if (data != null) { Console.Write("APDU ({0}), DATA:", i); foreach (byte b in data) { Console.Write(" {0:X2}", b); } Console.WriteLine(); i++; } } return; }
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); } }