protected virtual void Dispose(bool disposing) { try { if (!_disposed) { if (disposing) { //Cleanup managed objects if (!_stopped) { this.StopListeners(); } cardMonitor.Dispose(); cardMonitor = null; cardFactory.Release(); cardFactory.Dispose(); cardFactory = null; } // Cleanup unmanaged objects } _disposed = true; } catch { throw new Exception("Unable to dispose smartcard manager"); } }
/// <summary>Creates a new smart card reader object.</summary> /// <param name="context">Connection context to the PC/SC Resource Manager.</param> /// <remarks> /// <example> /// <code lang="C#"> /// // Create PC/SC context /// var ctx = new SCardContext(); /// ctx.Establish(SCardScope.System); /// /// // Create reader object and connect to the Smart Card /// var myReader = new SCardReader(ctx); /// var rc = myReader.Connect( /// "OMNIKEY CardMan 5321", /// SCardShareMode.Shared, /// SCardProtocol.T1); /// </code> /// </example> /// </remarks> /// <exception cref="ArgumentNullException">If <paramref name="context"/> is <see langword="null" /></exception> public SCardReader(ISCardContext context) { if (context == null) { throw new ArgumentNullException("context"); } _context = context; }
private void HandleSmartCard(String readerName) { using (ISCardContext ctx = contextFactory.Establish(SCardScope.System)) using (ICardReader reader = ctx.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { StatusMessage?.Invoke("Connected to tag"); IccDetection cardIdent = new IccDetection(reader); cardIdent.DetectCardType(); StatusMessage?.Invoke("Device class: " + cardIdent.PcscDeviceClass.ToString()); StatusMessage?.Invoke("Card name: " + cardIdent.PcscCardName.ToString()); StatusMessage?.Invoke("ATR: " + BitConverter.ToString(cardIdent.Atr)); if (cardIdent.PcscDeviceClass == DeviceClass.StorageClass && (cardIdent.PcscCardName == CardName.MifareUltralight || cardIdent.PcscCardName == CardName.MifareUltralightC || cardIdent.PcscCardName == CardName.MifareUltralightEV1)) { HandleMifareUL(reader); } else if (cardIdent.PcscDeviceClass == DeviceClass.StorageClass && (cardIdent.PcscCardName == CardName.MifareStandard1K || cardIdent.PcscCardName == CardName.MifareStandard4K)) { HandleMifareStandard(reader); } else { HandleHCEClient(reader); } } }
/// <summary>Initializes a new instance of the <see cref="IsoReader" /> class that will create its own instance of a <see cref="SCardReader" />.</summary> /// <param name="context">A context to the PC/SC Resource Manager.</param> /// <param name="releaseContextOnDispose">if set to <c>true</c> the <paramref name="context" /> will be released on <see cref="Dispose()" />.</param> /// <exception cref="System.ArgumentNullException">If <paramref name="context" /> is <see langword="null" /></exception> public IsoReader(ISCardContext context, bool releaseContextOnDispose = false) { _context = context ?? throw new ArgumentNullException(nameof(context)); Reader = new SCardReader(context); _releaseContextOnDispose = releaseContextOnDispose; _disconnectReaderOnDispose = true; }
public Iso7816.ApduResponse SignalACR(string readerName, ACRReaderControl ctrl) { byte ledStateCtrl = 0; if (ctrl.finalRed) { ledStateCtrl |= 1 << 0; } if (ctrl.finalGreen) { ledStateCtrl |= 1 << 1; } if (ctrl.redMask) { ledStateCtrl |= 1 << 2; } if (ctrl.greenMask) { ledStateCtrl |= 1 << 3; } if (ctrl.initRedBlink) { ledStateCtrl |= 1 << 4; } if (ctrl.initGreenBlink) { ledStateCtrl |= 1 << 5; } if (ctrl.redBlinkMask) { ledStateCtrl |= 1 << 6; } if (ctrl.greenBlinkMask) { ledStateCtrl |= 1 << 7; } byte[] ctrlData = new byte[] { ctrl.t1Duration, ctrl.t2Duration, ctrl.reps, ctrl.buzzer }; blockCardEvents += 1; try { using (ISCardContext ctx = contextFactory.Establish(SCardScope.System)) using (ICardReader reader = ctx.ConnectReader(readerName, SCardShareMode.Direct, SCardProtocol.Unset)) { var apdu = new Iso7816.ApduCommand(0xFF, 0x00, 0x40, ledStateCtrl, ctrlData, null); return(reader.Control(apdu)); } } finally { new Thread(() => { Thread.Sleep(((ctrl.t1Duration * 100) + (ctrl.t2Duration * 100)) * ctrl.reps); blockCardEvents -= 1; }).Start(); } // For all I'm aware, this always returns a failure APDU, but the reader does perform the specified action. }
public ThaiNationalIDCardReader() { context = ContextFactory.Instance.Establish(SCardScope.System); reader = new SCardReader(context); apdu = new ThaiNationalIDCardAPDUCommandType02(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); }
/// <summary> /// Provides an easy to use CCID wrapper over <see cref="PCSC"/>. /// </summary> /// <remarks><paramref name="ctx"/> and <paramref name="reader"/> are both disposed of upon class destruction or disposal.</remarks> /// <param name="ctx">PCSC carc context</param> /// <param name="reader">PCSC card reader</param> public CCIDDriver(ISCardContext ctx, ISCardReader reader) { Context = ctx ?? throw new ArgumentNullException(); Reader = reader ?? throw new ArgumentNullException(); ReadVersion(); ReadSerial(); byte[] caps = ReadCapabilities(); }
/// <summary>Creates a new SCardMonitor object that is able to listen for certain smart card / reader changes.</summary> /// <param name="context">A new Application Context to the PC/SC Resource Manager.</param> /// <param name="releaseContextOnDispose">If <see langword="true" /> the supplied <paramref name="context" /> will be released (using <see cref="ISCardContext.Release()" />) on <see cref="Dispose()" /></param> /// <remarks>The monitor object should use its own application context to the PC/SC Resource Manager. It will create a (new) backgroud thread that will listen for status changes. /// <para>Warning: You MUST dispose the monitor instance otherwise the background thread will run forever!</para> /// </remarks> public SCardMonitor(ISCardContext context, bool releaseContextOnDispose = false) { if (context == null) { throw new ArgumentNullException("context"); } _context = context; _releaseContextOnDispose = releaseContextOnDispose; }
public SCardMonitor(ISCardContext context, bool releaseContextOnDispose = false) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; _releaseContextOnDispose = releaseContextOnDispose; }
/// <summary>Creates a new SCardMonitor object that is able to listen for certain smart card / reader changes.</summary> /// <param name="contextFactory">A smartcard context factory</param> /// <param name="scope">Scope of the establishment. This can either be a local or remote connection.</param> public SCardMonitor(IContextFactory contextFactory, SCardScope scope) { if (contextFactory == null) { throw new ArgumentNullException(nameof(contextFactory)); } _context = contextFactory.Establish(scope); _releaseContextOnDispose = true; }
/// <summary>Initializes a new instance of the <see cref="IsoReader" /> class that will create its own instance of a <see cref="SCardReader" />.</summary> /// <param name="context">A context to the PC/SC Resource Manager.</param> /// <param name="releaseContextOnDispose">if set to <c>true</c> the <paramref name="context" /> will be released on <see cref="Dispose()" />.</param> /// <exception cref="System.ArgumentNullException">If <paramref name="context" /> is <see langword="null" /></exception> public IsoReader(ISCardContext context, bool releaseContextOnDispose = false) { if (context == null) { throw new ArgumentNullException("context"); } _context = context; _reader = new SCardReader(context); _releaseContextOnDispose = releaseContextOnDispose; _disconnectReaderOnDispose = true; }
public SCardMonitor(ISCardContext context, SCardScope scope, bool releaseContextOnDispose = true) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; _context.Establish(scope); _releaseContextOnDispose = releaseContextOnDispose; }
private static void PrintReadersPerGroup(string[] groupNames, ISCardContext context) { foreach (var groupName in groupNames) { Console.WriteLine("\nGroup " + groupName + " contains "); foreach (var readerName in context.GetReaders(new[] { groupName })) { Console.WriteLine("\t" + readerName); } } }
/// <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 SmartCard(string readerName) { var contextFactory = ContextFactory.Instance; _context = contextFactory.Establish(SCardScope.System); if (string.IsNullOrEmpty(readerName)) { throw new ApplicationException("No smartCard readers found"); } reader = new IsoReader(_context, readerName, SCardShareMode.Exclusive, SCardProtocol.Any, true); }
public SmartcardFactory(SCardScope scope) { try { _scope = scope; //Estabilish context cardFactory = contextFactory.Establish(_scope); } catch { throw; } }
/// <summary> /// PC/SCを利用してFeliCaカードを操作する /// </summary> /// <exception cref="Exception" /> public Felica() { context = ContextFactory.Instance.Establish(SCardScope.System); try { CurrentReaderName = ReaderNames[0]; } catch (ArgumentOutOfRangeException ex) { throw new Exception("有効なカードリーダがありません。", ex); } }
// ---------------------------------------------------------------------- private string Open(ISCardContext context, string pattern) { try { // get all reader names var readerList = new List <string>(); var list = context.GetReaders(); if (list.Length <= 0) { logger.Trace("no card readers!"); return(null); } logger.Trace("connected card readers:"); foreach (var item in list) { readerList.Add(item); logger.Trace("- {0}", item); } // pattern to test logger.Trace("pattern to test: {0}", pattern); // test pattern to find matched reader var reader = -1; var regex = new Regex(pattern); for (var i = 0; i < readerList.Count; i++) { var match = regex.Match(readerList[i]); if (match.Success) { reader = i; break; } } // reader name if (reader >= 0 && reader < readerList.Count) { logger.Trace("selected card reader name: {0}", readerList[reader]); return(readerList[reader]); } else { logger.Trace("no card readers selected!"); return(null); } } catch (Exception ex) { logger.Error(ex); return(null); } }
/// <summary> /// Receive the ATR of each reader in <paramref name="readerNames"/> /// by using the <see cref="ICardReader.GetAttrib(SCardAttribute)"/> function /// </summary> /// <param name="context">Connection context</param> /// <param name="readerNames">Readers from which the ATR should be requested</param> private static void DisplayAtrForEachReader(ISCardContext context, IEnumerable <string> readerNames) { foreach (var readerName in readerNames) { try { using (var reader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { DisplayAtr(reader); } } catch (Exception exception) { Console.WriteLine("Could not connect to reader {0}. No smart card present? ({1})", readerName, exception.GetType()); } } }
/// <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); } } }
/// <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) { try { using (var reader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { PrintReaderStatus(reader); Console.WriteLine(); } } catch (Exception exception) { Console.WriteLine( "No card inserted or reader '{0}' is reserved exclusively by another application.", readerName); Console.WriteLine("Error message: {0} ({1})\n", exception.Message, exception.GetType()); } } }
// 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); } } }
private void StartMonitor(ISCardContext ctx) { try { var readers = GetReaders(ctx); OnInitialized(new DeviceChangeEventArgs( readers, Enumerable.Empty <string>(), Enumerable.Empty <string>())); while (true) { var scannerStates = new[] { new SCardReaderState { ReaderName = "\\\\?PnP?\\Notification", CurrentStateValue = (IntPtr)(readers.Count << 16), EventStateValue = (IntPtr)SCRState.Unknown, } }; var rc = ctx.GetStatusChange(ctx.Infinite, scannerStates); if (rc == SCardError.Cancelled) { return; } if (rc != SCardError.Success) { throw new PCSCException(rc); } var newReaderList = GetReaders(ctx); var attached = GetAttachedReaders(readers, newReaderList); var detached = GetDetachedReaders(readers, newReaderList); OnStatusChanged(new DeviceChangeEventArgs( newReaderList.ToList(), attached.ToList(), detached.ToList())); readers = newReaderList; } } catch (Exception exception) { OnMonitorException(new DeviceMonitorExceptionEventArgs(exception)); } }
private string DisplayAtrForEachReader(ISCardContext context, IEnumerable <string> readerNames) { foreach (var readerName in readerNames) { try { using (var reader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) { return(DisplayAtr(reader)); } } catch (Exception exception) { outputError.Text = exception.Message; return(null); } } return(null); }
/// <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); } } }
public string[] GetReaders() { /*try * {*/ _hContext = _contextFactory.Establish(SCardScope.System); string[] szReaders = _hContext.GetReaders(); _hContext.Release(); /* if (szReaders.Length <= 0) * throw new PCSCException(SCardError.NoReadersAvailable, * "Could not find any Smartcard reader.");*/ return(szReaders); /*} * catch (PCSCException ex) * { * /* _error_code = ECODE_SCardError; * _error_message = "GetReaders Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; * Debug.Print(_error_message); * throw ex; * }*/ }
public string[] GetReaders() { try { _hContext = _contextFactory.Establish(SCardScope.System); string[] szReaders = _hContext.GetReaders(); _hContext.Release(); if (szReaders.Length <= 0) { throw new PCSCException(SCardError.NoReadersAvailable, "Could not find any Smartcard reader."); } return(szReaders); } catch (PCSCException ex) { _error_code = ECODE_SCardError; _error_message = "GetReaders Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; Debug.Print(_error_message); throw ex; } }
private void InitializeDevice() { var contextFactory = ContextFactory.Instance; using (context = contextFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); var monitorFactory = MonitorFactory.Instance; monitor = monitorFactory.Create(SCardScope.System); if (readerNames.Length == 0) { cp.Invoke((MethodInvoker)(() => this.cp.DeviceInitialized(true))); return; } readerName = readerNames[0]; AttachToAllEvents(monitor); Console.WriteLine($"Initializing Reader: {readerNames[0]}"); monitor.Start(readerNames[0]); Console.WriteLine($"Reader Initialized: {readerNames[0]}"); } }
private void TryTurnOffBeep(string readerName) { if (!readerName.Contains("ACR")) { return; } try { using (ISCardContext ctx = contextFactory.Establish(SCardScope.System)) using (ICardReader reader = ctx.ConnectReader(readerName, SCardShareMode.Direct, SCardProtocol.Unset)) { var apdu = new Iso7816.ApduCommand(0xFF, 0x00, 0x52, 0x00, null, 0x00); var res = reader.Control(apdu); if (res.Succeeded) { StatusMessage?.Invoke("Turned off buzzer on " + reader.Name); } } } catch (Exception) { } }
/// <summary> /// Asks the user to select a smartcard reader containing the Mifare chip /// </summary> /// <param name="readerNames">Collection of available smartcard readers</param> /// <returns>The selected reader name or <c>null</c> if none</returns> private static string ChooseReader(ISCardContext context) { var readerNames = context.GetReaders(); if (NoReaderAvailable(readerNames)) { Console.WriteLine("You need at least one reader.", Color.Red); return(null); } if (readerNames.Length == 1) { return(readerNames.Single()); } // Show available readers. Console.WriteLine("Available readers: ", Color.White); for (var i = 0; i < readerNames.Length; i++) { Console.WriteLine("[{0}] {1}", Color.White, i, readerNames[i]); } // Ask the user which one to choose. Console.Write("Which reader has an inserted NTAG215 card? ", Color.White); var line = Console.ReadLine(); if (int.TryParse(line, out int choice) && (choice >= 0) && (choice <= readerNames.Length)) { return(readerNames[choice]); } Console.WriteLine("An invalid number has been entered.", Color.Red); return(null); }
public ConnectedReaders(ISCardContext cardContext) { _cardContext = cardContext; }
/// <summary>Creates a new smart card reader object.</summary> /// <param name="context">Connection context to the PC/SC Resource Manager.</param> /// <remarks> /// <example> /// <code lang="C#"> /// // Create PC/SC context /// var ctx = new SCardContext(); /// ctx.Establish(SCardScope.System); /// /// // Create reader object and connect to the Smart Card /// var myReader = new SCardReader(ctx); /// var rc = myReader.Connect( /// "OMNIKEY CardMan 5321", /// SCardShareMode.Shared, /// SCardProtocol.T1); /// </code> /// </example> /// </remarks> /// <exception cref="ArgumentNullException">If <paramref name="context"/> is <see langword="null" /></exception> public SCardReader(ISCardContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } CurrentContext = context; }
public Boolean Open(string readerName = null) { try { // delay 1.5 second for ATR reading. Thread.Sleep(1500); _hContext = _contextFactory.Establish(SCardScope.System); _reader = new SCardReader(_hContext); // Connect to the card if (String.IsNullOrEmpty(readerName)) { // Open first avaliable reader. // Retrieve the list of Smartcard _readers string[] szReaders = _hContext.GetReaders(); if (szReaders.Length <= 0) { throw new PCSCException(SCardError.NoReadersAvailable, "Could not find any Smartcard _reader."); } _err = _reader.Connect(szReaders[0], SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(_err); } else { _err = _reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); CheckErr(_err); } _pioSendPci = new IntPtr(); switch (_reader.ActiveProtocol) { case SCardProtocol.T0: _pioSendPci = SCardPCI.T0; break; case SCardProtocol.T1: _pioSendPci = SCardPCI.T1; break; case SCardProtocol.Raw: _pioSendPci = SCardPCI.Raw; break; default: throw new PCSCException(SCardError.ProtocolMismatch, "Protocol not supported: " + _reader.ActiveProtocol.ToString()); } string[] readerNames; SCardProtocol proto; SCardState state; byte[] atr; var sc = _reader.Status( out readerNames, // contains the reader name(s) out state, // contains the current state (flags) out proto, // contains the currently used communication protocol out atr); // contains the ATR if (atr == null || atr.Length < 2) { return(false); } if (atr[0] == 0x3B && atr[1] == 0x67) { /* corruption card */ _apdu = new APDU_THAILAND_IDCARD_TYPE_01(); } else { _apdu = new APDU_THAILAND_IDCARD_TYPE_02(); } // select MOI Applet if (SelectApplet()) { return(true); } else { _error_code = ECODE_UNSUPPORT_CARD; _error_message = "SmartCard not support(Cannot select Ministry of Interior Applet.)"; return(false); } } catch (PCSCException ex) { _error_code = ECODE_SCardError; _error_message = "Open Err: " + ex.Message + " (" + ex.SCardError.ToString() + ")"; Debug.Print(_error_message); return(false); } }
/// <summary>Creates a new SCardMonitor object that is able to listen for certain smart card / reader changes.</summary> /// <param name="context">A new Application Context to the PC/SC Resource Manager.</param> /// <param name="scope">Scope of the establishment. This can either be a local or remote connection.</param> /// <param name="releaseContextOnDispose">If <see langword="true" /> the supplied <paramref name="context" /> will be released (using <see cref="ISCardContext.Release()" />) on <see cref="Dispose()" /></param> /// <remarks>The monitor object should use its own application context to the PC/SC Resource Manager. It will create a (new) backgroud thread that will listen for status changes. /// <para>Warning: You MUST dispose the monitor instance otherwise the background thread will run forever!</para> /// </remarks> public SCardMonitor(ISCardContext context, SCardScope scope, bool releaseContextOnDispose = true) : this(context, releaseContextOnDispose) { _context.Establish(scope); }
/// <summary>Initializes a new instance of the <see cref="IsoReader" /> class that will create its own instance of a <see cref="SCardReader" /> and immediately connect.</summary> /// <param name="context">A context to the PC/SC Resource Manager.</param> /// <param name="readerName">Name of the reader to connect with.</param> /// <param name="mode">The share mode.</param> /// <param name="protocol">The communication protocol. <seealso cref="ISCardReader.Connect(string,SCardShareMode,SCardProtocol)" /></param> /// <param name="releaseContextOnDispose">if set to <c>true</c> the <paramref name="context" /> will be released on <see cref="Dispose()" />.</param> public IsoReader(ISCardContext context, string readerName, SCardShareMode mode, SCardProtocol protocol, bool releaseContextOnDispose = true) : this(context, releaseContextOnDispose) { Connect(readerName, mode, protocol); }