public static async Task <bool> Initialize() { if (reader == null) { try { reader = await CardReader.FindAsync(); if (reader == null) { throw new Exception(); } reader.CardAdded += Reader_CardAdded; reader.CardRemoved += Reader_CardRemoved; return(true); } catch { return(false); } } else { return(true); } }
public OMNIKEY5021CL(SmartCardReader chipScanner, ICSDeviceListener csManager) { this.chipScanner = chipScanner; this.csManager = csManager; this.timePerTimeout = TimeSpan.FromHours(2); //change this if you want another value, to be the standard this.nextTimeout = DateTime.Now + this.timePerTimeout; }
public OMNIKEY5021CL(SmartCardReader chipScanner, ICSDeviceListener csManager, TimeSpan timeoutTimer) { this.chipScanner = chipScanner; this.csManager = csManager; this.timePerTimeout = timeoutTimer; this.nextTimeout = DateTime.Now + this.timePerTimeout; }
public void Run(string readerName) { var reader = new SmartCardReader(readerName); try { ConsoleWriter.Instance.PrintSplitter(); ConsoleWriter.Instance.PrintTask($"Connecting to {reader.PcscReaderName}"); ReaderHelper.ConnectToReaderWithCard(reader); ConsoleWriter.Instance.PrintMessage($"Connected\nConnection Mode: {reader.ConnectionMode}"); ReaderHelper.GetDataCommand(reader, "Get Historical Bytes", GetDataCommand.Type.Specific); ConsoleWriter.Instance.PrintSplitter(); } catch (Exception e) { ConsoleWriter.Instance.PrintError(e.Message); } finally { if (reader.IsConnected) { reader.Disconnect(CardDisposition.Unpower); ConsoleWriter.Instance.PrintMessage("Reader connection closed"); } ConsoleWriter.Instance.PrintSplitter(); } }
public void Run() { try { ConsoleWriter.Instance.PrintSplitter(); ConsoleWriter.Instance.PrintTask("Establishing SAM Secure Session"); var reader = new SmartCardReader(_readerName); using (var secureSession = new SamSecureSession(reader)) { secureSession.Establish(SamSecureSessionMasterKey, SamSecureSessionKeyNumber); if (secureSession.IsSessionActive) { ConsoleWriter.Instance.PrintMessage("Session established"); ExecuteExample(secureSession); ConsoleWriter.Instance.PrintSplitter(); } else { ConsoleWriter.Instance.PrintError("Failed to establish session"); } } } catch (Exception e) { ConsoleWriter.Instance.PrintError("Exception's been thrown: message = " + e.Message); } }
private async Task InitSmartCardAsync() { // Check if the SmartCardConnection API exists on this currently running SKU of Windows if (!ApiInformation.IsTypePresent("Windows.Devices.SmartCards.SmartCardConnection")) { // This SKU of Windows does not support Smart Card Connections SetStatusOutput("This SKU of Windows does not support Smart Card connections"); return; } // Initialize smart card reader var devSelector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc); var devices = await DeviceInformation.FindAllAsync(devSelector); if (devices != null && devices.Count == 0) { SetStatusOutput("No NFC Smart Card Reader found in this device."); return; } // Subscribe to Smart Cards _smartCardReader = await SmartCardReader.FromIdAsync(devices.FirstOrDefault().Id); _smartCardReader.CardAdded += SmartCardReaderOnCardAdded; SetStatusOutput("Subscribed for NFC Smart Cards"); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { var deviceInfo = await SmartCardReaderUtils.GetDefaultSmartCardReaderInfo(); if (deviceInfo == null) { LogMessage("NFC card reader mode not supported on this device", NotifyType.ErrorMessage); return; } if (!deviceInfo.IsEnabled) { var msgbox = new Windows.UI.Popups.MessageDialog("Your NFC proximity setting is turned off, you will be taken to the NFC proximity control panel to turn it on"); msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK")); await msgbox.ShowAsync(); // This URI will navigate the user to the NFC proximity control panel NfcUtils.LaunchNfcProximitySettingsPage(); return; } if (m_cardReader == null) { m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id); m_cardReader.CardAdded += cardReader_CardAdded; m_cardReader.CardRemoved += cardReader_CardRemoved; } }
public void Run(string readerName) { var reader = new SmartCardReader(readerName); try { ConsoleWriter.Instance.PrintSplitter(); ConsoleWriter.Instance.PrintTask($"Connecting to {reader.PcscReaderName}"); ReaderHelper.ConnectToReaderWithCard(reader); ConsoleWriter.Instance.PrintMessage($"Connected\nConnection Mode: {reader.ConnectionMode}"); ReaderHelper.ConnectToReaderWithCard(reader); SendUpdateBinaryCommand(reader, UpdateBinaryCommand.Type.Plain, 0x00, "ABCDEF01"); ConsoleWriter.Instance.PrintSplitter(); } catch (Exception e) { ConsoleWriter.Instance.PrintError(e.Message); } finally { if (reader.IsConnected) { reader.Disconnect(CardDisposition.Unpower); ConsoleWriter.Instance.PrintMessage("Reader connection closed"); } ConsoleWriter.Instance.PrintSplitter(); } }
private void CardReader_CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { //Card Removed //LogMessage("Card removed"); //ShowToastNotification("Card Removed"); ShowToastNotification("Card Removed"); }
public static async Task <SmartCardReader> GetSmartCardReader() { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync (SmartCardReader.GetDeviceSelector()); return(await SmartCardReader.FromIdAsync(devices[0].Id)); }
private async void CardAdded(SmartCardReader sender, CardAddedEventArgs args) { try { await MifareCard.ConnectAsync(args.SmartCard); var cardname = MifareCard.GetCardName(); var cardid = await MifareCard.GetCardIDAsync(); byte[] KeyA = { 0xEE, 0x14, 0xB8, 0x5E, 0xAC, 0x78 }; byte[] KeyB = { 0x2B, 0x44, 0xD1, 0x6B, 0x6C, 0x7D }; byte[] madkey = { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 }; byte[] madkeyb = { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }; await MifareCard.LoadKeyAsync(Mifare.DefaultKeys.FactoryDefault, KeyTypeEnum.KeyA); await MifareCard.LoadKeyAsync(Mifare.DefaultKeys.FactoryDefault, KeyTypeEnum.KeyB); await MifareCard.LoadKeyAsync(Mifare.DefaultKeys.FactoryDefault, KeyTypeEnum.KeyDefaultF); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { (CardStatus.Fill as SolidColorBrush).Color = Colors.Green; ControlPanel.IsEnabled = true; CardId.Text = cardid; CardType.Text = cardname; }); } catch (Exception ex) { PopupMessage(ex.Message); } }
private async void EnterCardPage_Loaded(object sender, RoutedEventArgs e) { Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; // Configure SmartCard var sc = (string)localSettings.Values["SmartCard"]; if (sc != "None") { SmartCardReader reader = await SmartCardReader.FromIdAsync((string)localSettings.Values["SmartCard"]); reader.CardRemoved += Reader_CardRemoved; reader.CardAdded += Reader_CardAdded; } else { Button cardButton = new Button { Content = "Process Card..." }; cardButton.Click += CardButton_Click; cardButton.HorizontalAlignment = HorizontalAlignment.Center; cardButton.VerticalAlignment = VerticalAlignment.Top; cardButton.Margin = new Thickness(0, 350, 0, 0); cardButton.FontSize = 30; pgGrid.Children.Add(cardButton); } }
private static void OnCardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { lock (cardConnectionLock) { if (currentConnection != null) { currentConnection.Dispose(); currentConnection = null; currentCardId = null; } } // Let users know the card is gone // Raise on UI thread context.Post(_ => { var evt = cardRemoved; if (evt != null) { evt(sender, EventArgs.Empty); } }, null); }
public void Run(string readerName) { using (var reader = new SmartCardReader(readerName)) { try { ConsoleWriter.Instance.PrintSplitter(); ConsoleWriter.Instance.PrintTask($"Connecting to {reader.PcscReaderName}"); ReaderHelper.ConnectToReader(reader); ConsoleWriter.Instance.PrintMessage($"Connected\nConnection Mode: {reader.ConnectionMode}"); ExecuteExample(reader); ConsoleWriter.Instance.PrintSplitter(); } catch (Exception e) { ConsoleWriter.Instance.PrintError(e.Message); } finally { if (reader.IsConnected) { reader.Disconnect(CardDisposition.Unpower); ConsoleWriter.Instance.PrintMessage("Reader connection closed"); } ConsoleWriter.Instance.PrintSplitter(); } } }
public async void OnCardAdded(SmartCardReader sender, CardAddedEventArgs args) { // カード検索 var card = args.SmartCard; if (card == null) { return; } Log("Card OK"); // カードタイプ判別 using (var con = await card.ConnectAsync()) { IccDetection detection = new IccDetection(card, con); await detection.DetectCardTypeAync(); Log(" CardName : " + detection.PcscCardName.ToString()); Log(" DeviceClass : " + detection.PcscDeviceClass.ToString()); if (detection.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass && detection.PcscCardName == Pcsc.CardName.FeliCa) { new Controller.FelicaController(con); } } }
async private void GetDevices() { try { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc)); // There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is // enumerated despite that the device does not support it. As a workaround, we can do an additonal check // to ensure the device truly does support it. var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True"); if (workaroundDetect.Count == 0 || devices.Count == 0) { PopupMessage("No Reader Found!"); } CardReader = await SmartCardReader.FromIdAsync(devices.First().Id); MifareCard = new MifareCard(new MifareClassic()); CardReader.CardAdded += CardAdded; CardReader.CardRemoved += CardRemoved; } catch (Exception e) { PopupMessage("Exception: " + e.Message); } }
//public static bool Status //{ // get // { // var scStatus = await Reader.GetStatusAsync(); // if(scStatus == SmartCardReaderStatus.Ready) return false; // } //} public static async void DeviceSetAsync() { // Reader検索 var selector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Any); var devices = await DeviceInformation.FindAllAsync(selector); var device = devices.FirstOrDefault(); if (device == null) { return; } Debug.WriteLine("Device Set"); Reader = await SmartCardReader.FromIdAsync(device.Id); if (Reader == null) { return; } Debug.WriteLine("Reader Set"); Reader.CardAdded += OnCardAdded; return; }
public async Task <bool> AttachReader(OnCardData onCardData) { isDetached = false; // check if we are already attached if (reader != null) { return(true); } // check to see if we can get the reader var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc); if (deviceInfo == null || isDetached) { return(false); } // instantiate reader reader = await SmartCardReader.FromIdAsync(deviceInfo.Id); if (!isDetached) { reader.CardAdded += OnCardAdded; reader.CardRemoved += OnCardRemoved; customEvent = onCardData; CardDataEvent += customEvent; } return(!isDetached); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { // First try to find a reader that advertises as being NFC var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc); if (deviceInfo == null) { // If we didn't find an NFC reader, let's see if there's a "generic" reader meaning we're not sure what type it is deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Any); } if (deviceInfo == null) { LogMessage("NFC card reader mode not supported on this device"); return; } if (m_cardReader == null) { m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id); m_cardReader.CardAdded += cardReader_CardAdded; m_cardReader.CardRemoved += cardReader_CardRemoved; } }
public static string GetSerialNumber(string readerName) { string readerSerialNumber; using (var reader = new SmartCardReader(readerName)) { var getSerialNumberCommand = new Readers.AViatoR.Components.SerialNumber(); ConnectToReader(reader); try { var response = SendCommand(reader, getSerialNumberCommand.GetApdu); readerSerialNumber = getSerialNumberCommand.TranslateResponse(response); } catch (Exception) { // TODO Currently errors are suppressed, maybe should add some way to indicate the reason why serial number is not read return(string.Empty); } finally { if (reader.IsConnected) { reader.Disconnect(CardDisposition.Unpower); } } } return(readerSerialNumber); }
public static void GetCardUID(SmartCardReader sender, CardAddedEventArgs args) { byte[] byteCardUID = Get7ByteCardUID(args).Result; string cardUID = Convert7ByteCardUIDToDecimal(byteCardUID); ChipScannerManager.RecieveUIDFromChipScanner(cardUID); }
private static void GetCardID(SmartCardReader sender, CardAddedEventArgs args) { byte[] byteCardID = Get7ByteCardID(args).Result; string decimalCardID = Convert7ByteCardIDToDecimal(byteCardID); CopyPaste(decimalCardID); }
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (cardReader != null) { cardReader.CardAdded -= cardReader_CardAdded; cardReader.CardRemoved -= cardReader_CardRemoved; cardReader = null; } }
private void CheckCardReader() { _cardReader = CardManager.CardReaders.FirstOrDefault(); if (_cardReader != null) { _cardReader.StartPolling(400); } }
private async void CardReader_CardAdded(SmartCardReader sender, CardAddedEventArgs args) { // Handle Card //await HandleCard(args.SmartCard); //ShowToastNotification("Card Added"); System.Diagnostics.Debug.WriteLine("Card Added"); ShowToastNotification("Card Added"); await HandleCard(args.SmartCard); }
protected virtual void CardReader_CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { if (connection != null) { connection.Dispose(); } OnCardRemovedFromField(new EventArgs()); }
private void Reader_CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // A card has been inserted into the sender SmartCardReader. this.Frame.Navigate(typeof(InteriorPage)); }); }
/// <summary> /// Click handler for the 'Delete' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Delete_Click(object sender, RoutedEventArgs e) { if (!rootPage.ValidateTPMSmartCard()) { rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage); return; } Button b = sender as Button; b.IsEnabled = false; rootPage.NotifyUser("Deleting the TPM virtual smart card...", NotifyType.ErrorMessage); try { SmartCard card = await rootPage.GetSmartCard(); // The following two lines are not directly related to TPM virtual // smart card creation, but are used to demonstrate how to handle // CardRemoved events by registering an event handler with a // SmartCardReader object. Since we are using a TPM virtual smart // card in this case, the card cannot actually be added to or // removed from the reader, but a CardRemoved event will fire // when the reader and card are deleted. // // We must retain a reference to the SmartCardReader object to // which we are adding the event handler. We use += to add the // HandleCardRemoved method as an event handler. The function // will be automatically boxed in a TypedEventHandler, but // the function signature match the template arguments for // the specific event - in this case, // <SmartCardReader, CardRemovedEventArgs> reader = card.Reader; reader.CardRemoved += HandleCardRemoved; bool result = await SmartCardProvisioning.RequestVirtualSmartCardDeletionAsync(card); if (result) { rootPage.NotifyUser("TPM virtual smart card deletion completed.", NotifyType.StatusMessage); rootPage.SmartCardReaderDeviceId = null; } else { rootPage.NotifyUser("TPM virtual smart card deletion was canceled by the user.", NotifyType.StatusMessage); } } catch (Exception ex) { rootPage.NotifyUser("TPM virtual smartcard deletion failed with exception: " + ex.ToString(), NotifyType.ErrorMessage); } finally { b.IsEnabled = true; } }
public void Run(string readerName) { var reader = new SmartCardReader(readerName); var secureChannel = new Readers.SecureSession.SecureChannel(reader); try { ConsoleWriter.Instance.PrintSplitter(); ConsoleWriter.Instance.PrintTask("Establishing Secure Session"); if (!IsValidSessionKeyFormat(EncKey) || !IsValidSessionKeyFormat(MacKey)) { throw new ArgumentException("Secure session key format is incorrect, correct format of session key string is 32 character long hexadecimal string without hex specifier. Example: \"00000000000000000000000000000000\""); } secureChannel.Establish(EncKey + MacKey, KeyRelatedAccesRight); if (secureChannel.IsSessionActive) { ConsoleWriter.Instance.PrintMessage("Session established"); ConsoleWriter.Instance.PrintSplitter(); ReaderHelper.GeneralAuthenticateiClass(secureChannel, "Authenticate without implicit selection. Key from slot: ", BookNumber.Book0, PageNumber.Page0, GeneralAuthenticateCommand.ImplicitSelection.Off, GeneralAuthenticateCommand.iClassKeyType.PicoPassCreditKeyKC, 0x21); ReaderHelper.UpdateBinaryCommand(secureChannel, "Update binary, target block nr: ", UpdateBinaryCommand.Type.Plain, 0x14, "BACDEF0122345678"); ConsoleWriter.Instance.PrintSplitter(); } else { ConsoleWriter.Instance.PrintError("Failed to establish session"); } } catch (Exception e) { ConsoleWriter.Instance.PrintError(e.Message); } finally { if (secureChannel.IsSessionActive) { secureChannel.Terminate(); ConsoleWriter.Instance.PrintMessage("Secure Session terminated."); } if (reader.IsConnected) { reader.Disconnect(CardDisposition.Unpower); ConsoleWriter.Instance.PrintMessage("Reader connection closed"); } ConsoleWriter.Instance.PrintSplitter(); } }
public async Task GetAllSmartCardsAsync() { string selector = SmartCardReader.GetDeviceSelector(); var readers = await DeviceInformation.FindAllAsync(selector); foreach (var reader in readers) { this.AllReadersInfo.Add(new Tuple <string, string>(reader.Name, reader.Id)); } }
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (m_cardReader != null) { m_cardReader.CardAdded -= cardReader_CardAdded; m_cardReader.CardRemoved -= cardReader_CardRemoved; m_cardReader = null; } base.OnNavigatingFrom(e); }
/// <summary> /// Card added event handler gets triggered when card enters nfc field /// </summary> /// <returns>None</returns> public async void CardAdded(SmartCardReader sender, CardAddedEventArgs args) { try { ChangeTextBlockFontColor(TextBlock_Header, Windows.UI.Colors.Green); await HandleCard(args); } catch (Exception e) { PopupMessage("CardAdded Exception: " + e.Message); } }
/// <summary> /// Enumerates NFC reader and registers event handlers for card added/removed /// </summary> /// <returns>None</returns> async private void GetDevices() { try { Reader = await CardReader.FindAsync(); if (Reader == null) { PopupMessage("No Readers Found"); return; } Reader.CardAdded += CardAdded; Reader.CardRemoved += CardRemoved; } catch (Exception e) { PopupMessage("Exception: " + e.Message); } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { // Clear the messages MainPage.Current.NotifyUser(String.Empty, NotifyType.StatusMessage, true); // First try to find a reader that advertises as being NFC var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc); if (deviceInfo == null) { // If we didn't find an NFC reader, let's see if there's a "generic" reader meaning we're not sure what type it is deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Any); } if (deviceInfo == null) { LogMessage("NFC card reader mode not supported on this device", NotifyType.ErrorMessage); return; } if (!deviceInfo.IsEnabled) { var msgbox = new Windows.UI.Popups.MessageDialog("Your NFC proximity setting is turned off, you will be taken to the NFC proximity control panel to turn it on"); msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK")); await msgbox.ShowAsync(); // This URI will navigate the user to the NFC proximity control panel NfcUtils.LaunchNfcProximitySettingsPage(); return; } if (m_cardReader == null) { m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id); m_cardReader.CardAdded += cardReader_CardAdded; m_cardReader.CardRemoved += cardReader_CardRemoved; } }
public SmartCardReaderEvents(SmartCardReader This) { this.This = This; }
private async void cardReader_CardAdded(SmartCardReader sender, CardAddedEventArgs args) { await HandleCard(args.SmartCard); }
private void cardReader_CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { LogMessage("Card removed"); }
/// <summary> /// Card removed event handler gets triggered when card leaves nfc field /// </summary> /// <returns>None</returns> void CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) { card?.Dispose(); ChangeTextBlockFontColor(TextBlock_Header, Windows.UI.Colors.Red); }
private async void button1_Click(object sender, RoutedEventArgs e) { var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc); if (deviceInfo == null) { deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Any); } if (deviceInfo == null) { MessageDialog msg = new MessageDialog("NFC card reader mode not supported on this device"); await msg.ShowAsync(); return; } if (m_cardReader == null) { button1.IsEnabled = false; button1.Content = "Tap your amiibo to continue !"; m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id); m_cardReader.CardAdded += cardReader_CardAdded; m_cardReader.CardRemoved += cardReader_CardRemoved; } }
/// <summary> /// Click handler for the 'create' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Create_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; b.IsEnabled = false; rootPage.NotifyUser("Creating TPM virtual smart card...", NotifyType.StatusMessage); try { SmartCardPinPolicy pinPolicy = ParsePinPolicy(); IBuffer adminkey = CryptographicBuffer.GenerateRandom( MainPage.ADMIN_KEY_LENGTH_IN_BYTES); SmartCardProvisioning provisioning = await SmartCardProvisioning.RequestVirtualSmartCardCreationAsync( FriendlyNameText.Text, adminkey, pinPolicy); // If card creation is cancelled by the user, // RequestVirtualSmartCard will return null instead of a // SmartCardProvisioning object. if (null == provisioning) { rootPage.NotifyUser( "TPM virtual smart card creation was canceled by " + "the user.", NotifyType.StatusMessage); b.IsEnabled = true; return; } // The following two lines are not directly related to TPM virtual // smart card creation, but are used to demonstrate how to handle // CardAdded events by registering an event handler with a // SmartCardReader object. Since we are using a TPM virtual smart // card in this case, the card cannot actually be added to or // removed from the reader, but a CardAdded event will fire as // soon as the event handler is added, since the card is already // inserted. // // We must retain a reference to the SmartCardReader object to // which we are adding the event handler. Hence we assign the // reader object associated with the SmartCardProvisioning we // received from RequestVirtualSmartCardCreationAsync to the // class's "reader" member. Then, we use += to add the // HandleCardAdded method as an event handler. The function // will be automatically boxed in a TypedEventHandler, but // the function signature match the template arguments for // the specific event - in this case, // <SmartCardReader, CardAddedEventArgs> reader = provisioning.SmartCard.Reader; reader.CardAdded += HandleCardAdded; // Store the reader's device ID and admin key to enable the // following scenarios in the sample. rootPage.SmartCardReaderDeviceId = provisioning.SmartCard.Reader.DeviceId; rootPage.AdminKey = adminkey; // Once RequestVirtualSmartCardCreationAsync has returned, the card // is already provisioned and ready to use. Therefore, the steps // in this using block are not actually necessary at this point. // However, should you want to re-provision the card in the future, // you would follow this sequence: acquire a challenge context, // calculate a response, and then call ProvisionAsync on the // challenge context with the calculated response. using (var context = await provisioning.GetChallengeContextAsync()) { IBuffer response = ChallengeResponseAlgorithm.CalculateResponse( context.Challenge, adminkey); await context.ProvisionAsync(response, true); } rootPage.NotifyUser( "TPM virtual smart card is provisioned and ready for use.", NotifyType.StatusMessage); } catch (Exception ex) { // Two potentially common error scenarios when creating a TPM // virtual smart card are that the user's machine may not have // a TPM, or the TPM may not be ready for use. It is important // to explicitly check for these scenarios by checking the // HResult of any exceptions thrown by // RequestVirtualSmartCardCreationAsync and gracefully // providing a suitable message to the user. if(NTE_DEVICE_NOT_FOUND == ex.HResult) { rootPage.NotifyUser( "We were unable to find a Trusted Platform Module on " + "your machine. A TPM is required to use a TPM Virtual " + "Smart Card.", NotifyType.ErrorMessage); } else if (NTE_DEVICE_NOT_READY == ex.HResult) { rootPage.NotifyUser( "Your Trusted Platform Module is not ready for use. " + "Please contact your administrator for assistance with " + "initializing your TPM.", NotifyType.ErrorMessage); } else { rootPage.NotifyUser( "TPM virtual smart card creation failed with exception: " + ex.ToString(), NotifyType.ErrorMessage); } } finally { b.IsEnabled = true; } }
void HandleCardRemoved(SmartCardReader evtReader, CardRemovedEventArgs args) { // This event handler will not be invoked on the UI thread. Hence, // to perform UI operations we need to post a lambda to be executed // back on the UI thread; otherwise we may access objects which // are not marshalled for the current thread, which will result in an // exception due to RPC_E_WRONG_THREAD. uiContext.Post((object ignore) => { rootPage.NotifyUser( "Card removed from reader " + evtReader.Name + ".", NotifyType.StatusMessage); }, null); }
private async void SmartCardReaderOnCardAdded(SmartCardReader sender, CardAddedEventArgs args) { SetStatusOutput("Found smart card"); // Get Answer to Reset (ATR) according to ISO 7816 // ATR = info about smart card's characteristics, behaviors, and state // https://en.wikipedia.org/wiki/Answer_to_reset var info = await args.SmartCard.GetAnswerToResetAsync(); var infoArray = info.ToArray(); SetStatusOutput("Answer to Reset: " + BitConverter.ToString(infoArray)); // Connect to the card // var connection = await args.SmartCard.ConnectAsync(); // ... }