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);
            }
        }
コード例 #2
0
        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;
            }
        }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: MainPage.xaml.cs プロジェクト: nunanas21/CIS-109
        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;
            }
        }
コード例 #5
0
        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);
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: uker70/OO-Design-Pattern
        public static async Task <SmartCardReader> GetSmartCardReader()
        {
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync
                                                      (SmartCardReader.GetDeviceSelector());

            return(await SmartCardReader.FromIdAsync(devices[0].Id));
        }
コード例 #7
0
ファイル: ReaderService.cs プロジェクト: siamcats/Marutamachi
        //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;
        }
コード例 #8
0
ファイル: MainPage.xaml.cs プロジェクト: nomada2/nfc-bt-demo
        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");
        }
コード例 #9
0
        // カード読込メソッド
        private async Task <string> Getmid()
        {
            // Reader検索
            var selector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Any);
            var devices  = await DeviceInformation.FindAllAsync(selector);

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                return("");
            }

            var reader = await SmartCardReader.FromIdAsync(device.Id);

            if (reader == null)
            {
                return("");
            }

            // カード検索
            var cards = await reader.FindAllCardsAsync();

            var card = cards.FirstOrDefault();

            if (card == null)
            {
                return("");
            }

            // 接続してポーリングコマンド送信
            using (var con = await card.ConnectAsync())
            {
                var handler = new AccessHandler(con);
                try
                {
                    var result = await handler.TransparentExchangeAsync(new byte[] { 6, 0, 0xff, 0xff, 0, 3 });

                    byte[] idm = new byte[8];
                    Array.Copy(result, 2, idm, 0, idm.Length);
                    string s = "";
                    foreach (byte b in idm)
                    {
                        // 0x00がでたらループを抜けるならここにif文とかいれる
                        s += b.ToString("X2");
                    }
                    return(s);
                }
                catch
                {
                    return("");
                }
            }
        }
コード例 #10
0
        private async void InitNFC()
        {
            var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc);

            if (m_cardReader == null)
            {
                m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                m_cardReader.CardAdded   += CardReader_CardAdded;
                m_cardReader.CardRemoved += CardReader_CardRemoved;
            }
        }
コード例 #11
0
ファイル: SampleConfiguration.cs プロジェクト: ice0/test
        public async Task <SmartCard> GetSmartCard()
        {
            SmartCardReader reader = await SmartCardReader.FromIdAsync(SmartCardReaderDeviceId);

            IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

            if (1 != cards.Count)
            {
                throw new InvalidOperationException("Reader has an unexpected number of cards (" + cards.Count + ")");
            }

            return(cards[0]);
        }
コード例 #12
0
ファイル: CardReader.cs プロジェクト: tijldeneut/MiFare
        public static async Task <SmartCardReader> FindAsync(Func <DeviceInformationCollection, DeviceInformation> selector = null)
        {
#if WINDOWS_UAP
            // Make sure we have the API we need
            if (!ApiInformation.IsTypePresent(typeof(SmartCardConnection).FullName))
            {
                return(null);
            }
#endif

            var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc));

// if none, fall back to generic
            if (devices.Count == 0)
            {
                devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Generic));
            }

            // 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)
            {
                return(null);
            }

#if WINDOWS_UAP
            // See if one of the reader names contains a -CL
            if (devices.Count > 1 && selector == null)
            {
                var di = devices.SingleOrDefault(d => d.Id.Contains("-CL"));
                if (di != null)
                {
                    return(await SmartCardReader.FromIdAsync(di.Id));
                }
            }
#endif

            var func = selector ?? (d => d.First());
            var dev  = func(devices);
            if (dev == null)
            {
                return(null);
            }

            var reader = await SmartCardReader.FromIdAsync(dev.Id);

            return(reader);
        }
コード例 #13
0
        private async void setupCard()
        {
            var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc);

            if (deviceInfo == null)
            {
                System.Diagnostics.Debug.WriteLine("Failed: No readers!");
                // Bah, device doesn't support NFC.
                CardStatus = ScanningStatus.Other;
                return;
            }


            if (!deviceInfo.IsEnabled)
            {
                System.Diagnostics.Debug.WriteLine("Failed: NFC is off!");
                CardStatus = ScanningStatus.NFCOff;
                return;
            }

            // At this point, deviceInfo should be legit.

            if (m_reader == null)
            {
                System.Diagnostics.Debug.WriteLine("Setting up card for id " + deviceInfo.Id);
                m_reader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                var status = await m_reader.GetStatusAsync();

                System.Diagnostics.Debug.WriteLine("CardStatus is " + status);
                switch (status)
                {
                case SmartCardReaderStatus.Disconnected:
                    CardStatus = ScanningStatus.NFCOff;
                    return;

                case SmartCardReaderStatus.Exclusive:
                    CardStatus = ScanningStatus.Other;
                    return;

                case SmartCardReaderStatus.Ready:
                    CardStatus          = ScanningStatus.NoCard;
                    m_reader.CardAdded += cardEV_Tap;
                    break;

                default:
                    break;
                }
            }
        }
コード例 #14
0
        public async Task StartCardReaderAsync(string deviceId)
        {
            if (cardReader == null)
            {
                if (String.IsNullOrEmpty(deviceId))
                {
                    throw new Exception("device id not supplied");
                }

                cardReader = await SmartCardReader.FromIdAsync(deviceId);

                cardReader.CardAdded   += CardReader_CardAdded;
                cardReader.CardRemoved += CardReader_CardRemoved;
            }
        }
コード例 #15
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            string selector = SmartCardReader.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            foreach (DeviceInformation device in devices)
            {
                SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

                reader.CardAdded   += Reader_CardAdded;
                reader.CardRemoved += Reader_CardRemoved;
                foreach (var foundCard in (await reader.FindAllCardsAsync()))
                {
                    await ReadCard(foundCard);
                }
            }
        }
コード例 #16
0
        public async void Init()
        {
            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);
            }
            proximityDevice = ProximityDevice.GetDefault();
            if (deviceInfo == null)
            {
                if (proximityDevice == null)
                {
                    LogMessage("NFC card reader mode not supported on this device");
                    return;
                }
            }

            if (deviceInfo != null && !deviceInfo.IsEnabled && proximityDevice == null)
            {
                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 && deviceInfo != null)
            {
                m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                m_cardReader.CardAdded   += cardReader_CardAdded;
                m_cardReader.CardRemoved += cardReader_CardRemoved;
            }

            if (proximityDevice != null)
            {
                proximityDevice.DeviceArrived += ProximityDevice_DeviceArrived;
            }
            //return "";
        }
コード例 #17
0
        private async void setupCard()
        {
            var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc);


            if (deviceInfo == null || (deviceInfo != null && !deviceInfo.IsEnabled))
            {
                // the Lumia 950 apparently has a problem where the NFC being off in some builds *disconnects* the device.
                // since we can hope that the device itself has an NFC reader (thanks to the store) we can, with relative
                // safety assume that the device is turned off.
                System.Diagnostics.Debug.WriteLine("Failed: NFC is off!");
                CardStatus = ScanningStatus.NFCOff;
                return;
            }

            // At this point, deviceInfo should be legit.

            if (m_reader == null)
            {
                System.Diagnostics.Debug.WriteLine("Setting up card for id " + deviceInfo.Id);
                m_reader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                var status = await m_reader.GetStatusAsync();

                System.Diagnostics.Debug.WriteLine("CardStatus is " + status);
                switch (status)
                {
                case SmartCardReaderStatus.Disconnected:
                    CardStatus = ScanningStatus.NFCOff;
                    return;

                case SmartCardReaderStatus.Exclusive:
                    CardStatus = ScanningStatus.Other;
                    return;

                case SmartCardReaderStatus.Ready:
                    CardStatus          = ScanningStatus.NoCard;
                    m_reader.CardAdded += cardEV_Tap;
                    break;

                default:
                    break;
                }
            }
        }
コード例 #18
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Starting run of background task...");

            _taskInstance           = taskInstance;
            _deferral               = taskInstance.GetDeferral();
            _taskInstance.Progress  = 1;
            _taskInstance.Canceled += TaskInstance_Canceled;

            string selector = SmartCardReader.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            var reader = await SmartCardReader.FromIdAsync(devices.FirstOrDefault().Id);

            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Got card reader device.");

            reader.CardAdded += Reader_CardAdded;
        }
コード例 #19
0
ファイル: NFC.cs プロジェクト: HackGT/aperture
        public async Task Setup()
        {
            if (reader != null)
            {
                reader.CardAdded -= Reader_CardAdded;
            }

            var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Generic));

            foreach (DeviceInformation device in devices)
            {
                reader = await SmartCardReader.FromIdAsync(device.Id);
            }
            if (reader == null)
            {
                Debug.WriteLine("No NFC reader found");
                return;
            }
            reader.CardAdded += Reader_CardAdded;
        }
コード例 #20
0
        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.Generic);

            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;
            }
            //RegisterDevice("test");
        }
コード例 #21
0
        public async Task InitializeAsync()
        {
            // 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;
            }

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\Data\StationCode.csv";

            m_stationCodeList = await Core.Models.StationCodeData.LoadAsync(path);
        }
コード例 #22
0
        private async Task DoRead()
        {
            string selector = SmartCardReader.GetDeviceSelector();

            DeviceInformationCollection smartCardReaders =
                await DeviceInformation.FindAllAsync(selector);

            var device = smartCardReaders.FirstOrDefault();

            SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

            IReadOnlyList <SmartCard> cards =
                await reader.FindAllCardsAsync();

            var card = cards.FirstOrDefault();

            if (card == null)
            {
                return;
            }

            (Dictionary <byte, string> address, Dictionary <byte, string> identity)? data = null;

            using (SmartCardConnection connection = await card.ConnectAsync())
            {
                data = await connection.ReadEIdData();
            }
            var identityData = data.Value.identity;
            var addressData  = data.Value.address;

            var dateOfBirth = EIdDateHelper.GetDateTime(identityData[Tags.ID_BIRTH_DATE]);

            FullName.Text       = $"{identityData[Tags.ID_FIRST_NAME]} {identityData[Tags.ID_LAST_NAME]}";
            PlaceOfBirth.Text   = identityData[Tags.ID_BIRTH_LOCATION];
            DateOfBirth.Text    = dateOfBirth.Value.ToString("dd/MM/yyyy");
            Gender.Text         = identityData[Tags.ID_SEX];
            Nationality.Text    = identityData[Tags.ID_NATIONALITY];
            NationalNumber.Text = identityData[Tags.ID_NATIONAL_NUMBER];
            Address.Text        = $"{addressData[Tags.ADDRESS_STREET_NUMBER]} {addressData[Tags.ADDRESS_ZIP_CODE]} {addressData[Tags.ADDRESS_MUNICIPALITY]}";
        }
コード例 #23
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            await LogMessageAsync(String.Empty, true);

            this.UpdateTargetCardFlag();

            var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc);

            if (deviceInfo == null)
            {
                deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Any);
            }

            if (deviceInfo == null)
            {
                await LogMessageAsync("NFCカードリーダがサポートされていません");

                return;
            }

            if (!deviceInfo.IsEnabled)
            {
                var msgbox = new Windows.UI.Popups.MessageDialog("設定画面でNFCをONにしてください");
                msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
                await msgbox.ShowAsync();

                LaunchNfcProximitySettingsPage();
                return;
            }

            if (cardReader == null)
            {
                cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                cardReader.CardAdded   += cardReader_CardAdded;
                cardReader.CardRemoved += cardReader_CardRemoved;
            }
        }
コード例 #24
0
        private async void WaitForCard()
        {
            // First try to find a reader that advertises as being NFC
            var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Generic);

            /*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;
            }

            //Should show message async
            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;
            }
        }
コード例 #25
0
        /*public static async void GetSmartCardReader()
         * {
         *  while (true == true)
         *  {
         *      DeviceInformationCollection devices = await DeviceInformation.FindAllAsync
         *          (SmartCardReader.GetDeviceSelector());
         *
         *      if (devices.Count > 0)
         *      {
         *          List<SmartCardReader> readers = new List<SmartCardReader>();
         *
         *          foreach (DeviceInformation device in devices)
         *          {
         *              readers.Add(await SmartCardReader.FromIdAsync(device.Id));
         *          }
         *
         *          Thread scanSmartCard = new Thread(new ParameterizedThreadStart(ScanSmartCard));
         *          scanSmartCard.Start(readers);
         *          Console.WriteLine("Card Reader Ready");
         *          Thread.CurrentThread.Abort();
         *      }
         *
         *      Thread.Sleep(2000);
         *  }
         * }*/


        public static void ScanSmartCard()
        {
            List <SmartCardReader> readers = new List <SmartCardReader>();

            DeviceWatcher smartCardReaderWatcher = DeviceInformation.CreateWatcher();

            smartCardReaderWatcher.Added += async(sender, args) =>
            {
                DeviceInformationCollection devices =
                    await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector());

                foreach (DeviceInformation device in devices)
                {
                    if (device.Id == args.Id)
                    {
                        readers.Add(await SmartCardReader.FromIdAsync(args.Id));
                        readers[readers.Count - 1].CardAdded += GetCardID;
                        Console.WriteLine("{0} is running and ready", readers[readers.Count - 1].Name); //can be changed to output in a popup
                    }
                }
            };

            smartCardReaderWatcher.Removed += (sender, args) =>
            {
                for (int idCounter = 0; idCounter < readers.Count; idCounter++)
                {
                    if (readers[idCounter].DeviceId == args.Id)
                    {
                        readers[idCounter].CardAdded -= GetCardID;
                        Console.WriteLine("{0} has been removed", readers[idCounter].Name); //can be changed to output in a popup
                        readers.RemoveAt(idCounter);
                        break;
                    }
                }
            };
            smartCardReaderWatcher.Start();
        }
コード例 #26
0
        /// <summary>
        /// Click handler for the 'ListSmartCard' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ListSmartCard_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;

            b.IsEnabled = false;
            try
            {
                rootPage.NotifyUser("Enumerating smart cards...", NotifyType.StatusMessage);

                // This list will be bound to our ItemListView once it has been
                // filled with SmartCardListItems.  The SmartCardListItem class
                // is defined above, and describes a reader/card pair with a
                // reader name and a card name.
                List <SmartCardListItem> cardItems = new List <SmartCardListItem>();

                // First we get the device selector for smart card readers using
                // the static GetDeviceSelector method of the SmartCardReader
                // class.  The selector is a string which describes a class of
                // devices to query for, and is used as the argument to
                // DeviceInformation.FindAllAsync.  GetDeviceSelector is
                // overloaded so that you can provide a SmartCardReaderKind
                // to specify if you are only interested in a particular type
                // of card/reader (e.g. TPM virtual smart card.)  In this case
                // we will list all cards and readers.
                string selector = SmartCardReader.GetDeviceSelector();
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

                // DeviceInformation.FindAllAsync gives us a
                // DeviceInformationCollection, which is essentially a list
                // of DeviceInformation objects.  We must iterate through that
                // list and instantiate SmartCardReader objects from the
                // DeviceInformation objects.
                foreach (DeviceInformation device in devices)
                {
                    SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

                    // For each reader, we want to find all the cards associated
                    // with it.  Then we will create a SmartCardListItem for
                    // each (reader, card) pair.
                    IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                    foreach (SmartCard card in cards)
                    {
                        SmartCardProvisioning provisioning = await SmartCardProvisioning.FromSmartCardAsync(card);

                        SmartCardListItem item = new SmartCardListItem()
                        {
                            ReaderName = card.Reader.Name,
                            CardName   = await provisioning.GetNameAsync()
                        };

                        cardItems.Add(item);
                    }
                }

                // Bind the source of ItemListView to our SmartCardListItem list.
                ItemListView.ItemsSource = cardItems;

                rootPage.NotifyUser("Enumerating smart cards completed.", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Enumerating smart cards failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
            }
            finally
            {
                b.IsEnabled = true;
            }
        }
コード例 #27
0
        public void FindCard(int timeoutInSecs = 10,
                             CancellationTokenSource tokenSource = null)
        {
            Task findCardTask = Task.Factory.StartNew(async() =>
            {
                // SmartCardReaderを取得
                var deviceInfo = await SmartCardReaderUtils.GetFirstSmartCardReaderInfo(SmartCardReaderKind.Nfc);

                this.IsSupported = deviceInfo != null;
                this.IsEnabled   = (deviceInfo != null) && deviceInfo.IsEnabled;

                if (!this.IsSupported)
                {
                    throw new FelicaReaderNotSupportedException("NFC is not supported");
                }
                else if (!this.IsEnabled)
                {
                    throw new FelicaReaderNotEnabledException("NFC is not enabled");
                }

                this.reader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

                // Felicaカードを探索
                var cts = tokenSource ?? new CancellationTokenSource();
                try
                {
                    var task = this.FindSmartCard(this.reader, cts.Token);
                    task.Wait(timeoutInSecs * 1000);

                    if (task.Status == TaskStatus.RanToCompletion)
                    {
                        var smartCard = task.Result;
                        SmartCardConnection connection = await smartCard.ConnectAsync();

                        IccDetection cardIdentification = new IccDetection(smartCard, connection);
                        await cardIdentification.DetectCardTypeAync();

                        if (cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass &&
                            cardIdentification.PcscCardName == Pcsc.CardName.FeliCa)
                        {
                            this.felicaCardSubject.OnNext(new FelicaCardMediaImplementation(connection));
                        }
                        else
                        {
                            throw new UnknownCardException(
                                String.Format("Unknown device: PcscDeviceClass={0}, PcscCardName={1}",
                                              cardIdentification.PcscDeviceClass,
                                              cardIdentification.PcscCardName));
                        }
                    }
                    else if (task.Status == TaskStatus.Canceled)
                    {
                        throw new FelicaReaderTimeoutException("Read Timeout");
                    }
                    else
                    {
                        // Timeoutが発生した場合
                        throw new FelicaReaderTimeoutException("Read Timeout");
                    }
                }
                catch (AggregateException)
                {
                    throw new FelicaReaderException();
                }
            });

            return;
        }
コード例 #28
0
        private async Task PerformAuthentication()
        {
            string NanosATR             = "3b00";
            bool   showNotificationFlag = true;

            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            foreach (DeviceInformation device in devices)
            {
                SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

                SmartCardReaderStatus readerstatus = await reader.GetStatusAsync();

                //System.Diagnostics.Debug.WriteLine("Reader : " + reader.Name + " status : " + readerstatus.ToString());
                IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                foreach (SmartCard card in cards)
                {
                    try
                    {
                        IBuffer ATR = await card.GetAnswerToResetAsync();

                        string ATR_str = CryptographicBuffer.EncodeToHexString(ATR);

                        if (ATR_str.Equals(NanosATR))
                        {
                            Task  t = AuthenticateWithSmartCardAsync(card);
                            await t;
                        }
                    }
                    catch (CompanionDeviceNotFoundException ex)
                    {
                        ex.DisplayError();
                        break;
                    }
                    catch (UnableTogetNonceFromDeviceException ex)
                    {
                        ex.DisplayError();
                        showNotificationFlag = false;
                        break;
                    }
                    catch (UnauthorizedUserException ex)
                    {
                        ex.DisplayError();
                        await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                            "",
                            SecondaryAuthenticationFactorAuthenticationMessage.UnauthorizedUser);

                        //ShowToastNotification("Wrong Response");
                        showNotificationFlag = false;
                        break;
                    }
                    catch (LogInDeniedByUserException ex)
                    {
                        ex.DisplayError();
                        await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                            "",
                            SecondaryAuthenticationFactorAuthenticationMessage.TryAgain);

                        showNotificationFlag = false;
                        break;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("[PerformAuthentication] Unhandled Exception / " + ex.Message);
                        showNotificationFlag = false;
                        return;
                    }
                    finally
                    {
                    }
                }
            }
            if (showNotificationFlag)
            {
                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                var str    = loader.GetString("LookingForDevice");

                await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                    str,
                    SecondaryAuthenticationFactorAuthenticationMessage.LookingForDevicePluggedin);
            }
            showNotificationFlag = true;
        }
コード例 #29
0
        private async Task <List <SecondaryAuthenticationFactorInfo> > getConnectedRegisteredDeviceList(IReadOnlyList <SecondaryAuthenticationFactorInfo> devicesToCheck)
        {
            //byte[] deviceConfigurationDataArray;
            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            byte[] response = { 0 };
            string sw1sw2   = null;
            string NanosATR = "3b00";

            byte[] deviceDlockState = new byte[1];
            byte[] deviceIdArray    = new byte[16];

            List <SecondaryAuthenticationFactorInfo> outList = new List <SecondaryAuthenticationFactorInfo>();

            DeviceInformationCollection readers = await DeviceInformation.FindAllAsync(selector);

            foreach (SecondaryAuthenticationFactorInfo device in devicesToCheck)
            {
                //CryptographicBuffer.CopyToByteArray(device.DeviceConfigurationData, out deviceConfigurationDataArray);

                foreach (DeviceInformation smartcardreader in readers)
                {
                    SmartCardReader reader = await SmartCardReader.FromIdAsync(smartcardreader.Id);

                    SmartCardReaderStatus readerstatus = await reader.GetStatusAsync();

                    IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                    foreach (SmartCard card in cards)
                    {
                        try
                        {
                            IBuffer ATR = await card.GetAnswerToResetAsync();

                            string ATR_str = CryptographicBuffer.EncodeToHexString(ATR);

                            if (ATR_str.Equals(NanosATR))
                            {
                                SmartCardConnection connection = await card.ConnectAsync();

                                response = await Apdu.TransmitApduAsync(connection, Apdu.getDeviceGuidCmdApdu);

                                sw1sw2        = Apdu.ApduResponseParser(response, out response);
                                deviceIdArray = response;
                                string deviceId = BitConverter.ToString(response).Replace("-", "");
                                if (deviceId == device.DeviceId) //update config data with dLockState and increment counter
                                {
                                    outList.Add(device);
                                }
                                connection.Dispose();
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(outList);
        }
コード例 #30
0
        private async Task writeConnectedRegisteredDevices()
        {
            string NanosATR = "3b00";
            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            byte[] response = { 0 };
            string sw1sw2   = null;

            byte[] deviceDlockState = new byte[1];
            byte[] deviceIdArray    = new byte[16];
            string txt = "";

            DeviceInformationCollection readers = await DeviceInformation.FindAllAsync(selector);

            IReadOnlyList <SecondaryAuthenticationFactorInfo> RegisteredDeviceList_addEvent = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.User);

            List <SecondaryAuthenticationFactorInfo> ConnectedRegisteredDeviceList = await getConnectedRegisteredDeviceList(RegisteredDeviceList_addEvent);

            foreach (SecondaryAuthenticationFactorInfo device in ConnectedRegisteredDeviceList)
            {
                foreach (DeviceInformation smartcardreader in readers)
                {
                    SmartCardReader reader = await SmartCardReader.FromIdAsync(smartcardreader.Id);

                    SmartCardReaderStatus readerstatus = await reader.GetStatusAsync();

                    IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                    foreach (SmartCard card in cards)
                    {
                        try
                        {
                            IBuffer ATR = await card.GetAnswerToResetAsync();

                            string ATR_str = CryptographicBuffer.EncodeToHexString(ATR);
                            if (ATR_str.Equals(NanosATR))
                            {
                                SmartCardConnection connection = await card.ConnectAsync();

                                response = await Apdu.TransmitApduAsync(connection, Apdu.getDeviceGuidCmdApdu);

                                sw1sw2        = Apdu.ApduResponseParser(response, out response);
                                deviceIdArray = response;
                                string deviceId = BitConverter.ToString(response).Replace("-", "");
                                if (deviceId == device.DeviceId) //update config data with dLockState
                                {
                                    if (device.PresenceMonitoringMode != SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged)
                                    {
                                        // Skip the device which doesn't need to be monitored in the background task
                                        continue;
                                    }

                                    await device.UpdateDevicePresenceAsync(SecondaryAuthenticationFactorDevicePresence.Present);

                                    response = await Apdu.TransmitApduAsync(connection, Apdu.getDlockStateCmdApdu);

                                    sw1sw2           = Apdu.ApduResponseParser(response, out response);
                                    deviceDlockState = response;

                                    string deviceConfigString    = CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData);
                                    char[] deviceConfigCharArray = new char[deviceConfigString.Count()];
                                    deviceConfigCharArray = deviceConfigString.ToCharArray();
                                    string deviceConfigStringNew = "";
                                    int    count = device.DeviceFriendlyName.Count();
                                    if (deviceDlockState[0] == 0)
                                    {
                                        if (deviceConfigCharArray[35] == '0') // Indicates if device was used for last login
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-0-0-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                        else
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-0-1-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                    }
                                    else
                                    {
                                        if (deviceConfigCharArray[35] == '0')
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-1-0-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                        else
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-1-1-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                    }
                                    // Get a Ibuffer from combinedDataArray
                                    IBuffer deviceConfigData = CryptographicBuffer.ConvertStringToBinary(deviceConfigString, 0);

                                    await SecondaryAuthenticationFactorRegistration.UpdateDeviceConfigurationDataAsync(device.DeviceId, deviceConfigData);
                                }
                                connection.Dispose();
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                txt += CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData) + Environment.NewLine;
            }
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile   ConnectedRegisteredDeviceListFile = await folder.CreateFileAsync("connectedRegisteredDeviceList.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(ConnectedRegisteredDeviceListFile, txt);
        }