public void _01_BasicLoggingTest()
        {
            // Specify path to the log file
            string logFilePath = Path.Combine(Path.GetTempPath(), @"Pkcs11Interop.log");

            DeleteFile(logFilePath);

            // Setup logger factory implementation
            var loggerFactory = new SimplePkcs11InteropLoggerFactory();

            loggerFactory.MinLogLevel = Pkcs11InteropLogLevel.Trace;
            loggerFactory.DisableConsoleOutput();
            loggerFactory.DisableDiagnosticsTraceOutput();
            loggerFactory.EnableFileOutput(logFilePath);

            // Set logger factory implementation that will be used by Pkcs11Interop library
            Pkcs11InteropLoggerFactory.SetLoggerFactory(loggerFactory);

            // Use Pkcs11Interop library as usual
            using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();

                // Verify that log file was created and contains some logs
                Assert.IsTrue(File.Exists(logFilePath));
                Assert.IsTrue(File.ReadAllText(logFilePath).Contains("Loading PKCS#11 library"));
            }

            DeleteFile(logFilePath);
        }
 internal Pkcs11LibraryInfo(string libraryPath, ILibraryInfo libraryInfo)
 {
     LibraryPath        = libraryPath;
     CryptokiVersion    = libraryInfo.CryptokiVersion;
     ManufacturerId     = libraryInfo.ManufacturerId;
     Flags              = libraryInfo.Flags;
     LibraryDescription = libraryInfo.LibraryDescription;
     LibraryVersion     = libraryInfo.LibraryVersion;
 }
Beispiel #3
0
        public void _01_BasicGetInfoTest()
        {
            using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();

                // Do something interesting with library information
                Assert.IsFalse(String.IsNullOrEmpty(libraryInfo.ManufacturerId));
            }
        }
        /// <summary>
        /// Checks whether PKCS#11 library information matches PKCS#11 URI
        /// </summary>
        /// <param name="pkcs11Uri">PKCS#11 URI</param>
        /// <param name="libraryInfo">PKCS#11 library information</param>
        /// <returns>True if PKCS#11 library information matches PKCS#11 URI</returns>
        public static bool Matches(Pkcs11Uri pkcs11Uri, ILibraryInfo libraryInfo)
        {
            if (pkcs11Uri == null)
                throw new ArgumentNullException("pkcs11Uri");

            if (libraryInfo == null)
                throw new ArgumentNullException("libraryInfo");

            return Pkcs11UriSharedUtils.Matches(pkcs11Uri, libraryInfo.ManufacturerId, libraryInfo.LibraryDescription, libraryInfo.LibraryVersion);
        }
        /// <summary>
        /// Obtains a list of all PKCS#11 URI matching slots
        /// </summary>
        /// <param name="pkcs11Uri">PKCS#11 URI</param>
        /// <param name="pkcs11">High level PKCS#11 wrapper</param>
        /// <param name="slotsType">Type of slots to be obtained</param>
        /// <returns>List of slots matching PKCS#11 URI</returns>
        public static List <ISlot> GetMatchingSlotList(Pkcs11Uri pkcs11Uri, IPkcs11 pkcs11, SlotsType slotsType)
        {
            if (pkcs11Uri == null)
            {
                throw new ArgumentNullException("pkcs11Uri");
            }

            if (pkcs11 == null)
            {
                throw new ArgumentNullException("pkcs11");
            }

            List <ISlot> matchingSlots = new List <ISlot>();

            ILibraryInfo libraryInfo = pkcs11.GetInfo();

            if (!Matches(pkcs11Uri, libraryInfo))
            {
                return(matchingSlots);
            }

            List <ISlot> slots = pkcs11.GetSlotList(SlotsType.WithOrWithoutTokenPresent);

            if ((slots == null) || (slots.Count == 0))
            {
                return(matchingSlots);
            }

            foreach (ISlot slot in slots)
            {
                ISlotInfo slotInfo = slot.GetSlotInfo();
                if (Matches(pkcs11Uri, slotInfo))
                {
                    if (slotInfo.SlotFlags.TokenPresent)
                    {
                        ITokenInfo tokenInfo = slot.GetTokenInfo();
                        if (Matches(pkcs11Uri, tokenInfo))
                        {
                            matchingSlots.Add(slot);
                        }
                    }
                    else
                    {
                        if (slotsType == SlotsType.WithOrWithoutTokenPresent && Pkcs11UriSharedUtils.Matches(pkcs11Uri, null, null, null, null))
                        {
                            matchingSlots.Add(slot);
                        }
                    }
                }
            }

            return(matchingSlots);
        }
        public void TestAccess()
        {
            // Specify the path to unmanaged PKCS#11 library provided by the cryptographic device vendor
            string pkcs11LibraryPath = @"d:\Program Files\SoftHSM2\lib\softhsm2-x64.dll";

            // Create factories used by Pkcs11Interop library
            Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

            // Load unmanaged PKCS#11 library
            using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, pkcs11LibraryPath, AppType.MultiThreaded))
            {
                // Show general information about loaded library
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();

                Console.WriteLine("Library");
                Console.WriteLine("  Manufacturer:       " + libraryInfo.ManufacturerId);
                Console.WriteLine("  Description:        " + libraryInfo.LibraryDescription);
                Console.WriteLine("  Version:            " + libraryInfo.LibraryVersion);

                // Get list of all available slots
                foreach (ISlot slot in pkcs11Library.GetSlotList(SlotsType.WithOrWithoutTokenPresent))
                {
                    // Show basic information about slot
                    ISlotInfo slotInfo = slot.GetSlotInfo();

                    Console.WriteLine();
                    Console.WriteLine("Slot");
                    Console.WriteLine("  Manufacturer:       " + slotInfo.ManufacturerId);
                    Console.WriteLine("  Description:        " + slotInfo.SlotDescription);
                    Console.WriteLine("  Token present:      " + slotInfo.SlotFlags.TokenPresent);

                    if (slotInfo.SlotFlags.TokenPresent)
                    {
                        // Show basic information about token present in the slot
                        ITokenInfo tokenInfo = slot.GetTokenInfo();

                        Console.WriteLine("Token");
                        Console.WriteLine("  Manufacturer:       " + tokenInfo.ManufacturerId);
                        Console.WriteLine("  Model:              " + tokenInfo.Model);
                        Console.WriteLine("  Serial number:      " + tokenInfo.SerialNumber);
                        Console.WriteLine("  Label:              " + tokenInfo.Label);

                        // Show list of mechanisms (algorithms) supported by the token
                        Console.WriteLine("Supported mechanisms: ");
                        foreach (CKM mechanism in slot.GetMechanismList())
                        {
                            Console.WriteLine("  " + mechanism);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Creates new instance of Pkcs11X509StoreInfo class
        /// </summary>
        /// <param name="libraryPath">Name of or path to PKCS#11 library</param>
        /// <param name="libraryInfo">General information about PKCS#11 library (CK_INFO)</param>
        internal Pkcs11X509StoreInfo(string libraryPath, ILibraryInfo libraryInfo)
        {
            if (string.IsNullOrEmpty(libraryPath))
            {
                throw new ArgumentNullException(nameof(libraryPath));
            }

            if (libraryInfo == null)
            {
                throw new ArgumentNullException(nameof(libraryInfo));
            }

            _libraryPath  = libraryPath;
            _manufacturer = libraryInfo.ManufacturerId;
            _description  = libraryInfo.LibraryDescription;
        }
Beispiel #8
0
        public void _02_LibraryInfoMatches()
        {
            using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();

                // Empty URI
                Pkcs11Uri pkcs11uri = new Pkcs11Uri(@"pkcs11:");
                Assert.IsTrue(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));

                // Unknown path attribute in URI
                pkcs11uri = new Pkcs11Uri(@"pkcs11:vendor=foobar");
                Assert.IsFalse(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));

                // All attributes matching
                Pkcs11UriBuilder pkcs11UriBuilder = new Pkcs11UriBuilder();
                pkcs11UriBuilder.LibraryManufacturer = libraryInfo.ManufacturerId;
                pkcs11UriBuilder.LibraryDescription  = libraryInfo.LibraryDescription;
                pkcs11UriBuilder.LibraryVersion      = libraryInfo.LibraryVersion;
                pkcs11uri = pkcs11UriBuilder.ToPkcs11Uri();
                Assert.IsTrue(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));

                // LibraryManufacturer nonmatching
                pkcs11UriBuilder = new Pkcs11UriBuilder();
                pkcs11UriBuilder.LibraryManufacturer = "foobar";
                pkcs11UriBuilder.LibraryDescription  = libraryInfo.LibraryDescription;
                pkcs11UriBuilder.LibraryVersion      = libraryInfo.LibraryVersion;
                pkcs11uri = pkcs11UriBuilder.ToPkcs11Uri();
                Assert.IsFalse(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));

                // LibraryDescription nonmatching
                pkcs11UriBuilder = new Pkcs11UriBuilder();
                pkcs11UriBuilder.LibraryManufacturer = libraryInfo.ManufacturerId;
                pkcs11UriBuilder.LibraryDescription  = "foobar";
                pkcs11UriBuilder.LibraryVersion      = libraryInfo.LibraryVersion;
                pkcs11uri = pkcs11UriBuilder.ToPkcs11Uri();
                Assert.IsFalse(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));

                // LibraryVersion nonmatching
                pkcs11UriBuilder = new Pkcs11UriBuilder();
                pkcs11UriBuilder.LibraryManufacturer = libraryInfo.ManufacturerId;
                pkcs11UriBuilder.LibraryDescription  = libraryInfo.LibraryDescription;
                pkcs11UriBuilder.LibraryVersion      = "0";
                pkcs11uri = pkcs11UriBuilder.ToPkcs11Uri();
                Assert.IsFalse(Pkcs11UriUtils.Matches(pkcs11uri, libraryInfo));
            }
        }
Beispiel #9
0
        public void _02_EjectTokenTest()
        {
            using (IPkcs11Library pkcs11Library = _mockFactories.Pkcs11LibraryFactory.LoadPkcs11Library(_mockFactories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();
                if (libraryInfo.LibraryDescription != "Mock module" && libraryInfo.ManufacturerId != "Pkcs11Interop Project")
                {
                    Assert.Inconclusive("Test cannot be executed with this PKCS#11 library");
                }

                // Find first slot with token present
                ISlot slot = Helpers.GetUsableSlot(pkcs11Library);

                // Eject token via vendor specific function C_EjectToken
                ((IMockSlot)slot).EjectToken();
            }
        }
Beispiel #10
0
        public void _06_GetMatchingSlotList()
        {
            using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Get all slots
                List <ISlot> allSlots = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent);
                Assert.IsTrue(allSlots != null && allSlots.Count > 0);

                // Empty URI
                Pkcs11Uri    pkcs11uri    = new Pkcs11Uri(@"pkcs11:");
                List <ISlot> matchedSlots = Pkcs11UriUtils.GetMatchingSlotList(pkcs11uri, pkcs11Library, SlotsType.WithTokenPresent);
                Assert.IsTrue(matchedSlots.Count == allSlots.Count);

                // Unknown path attribute in URI
                pkcs11uri    = new Pkcs11Uri(@"pkcs11:vendor=foobar");
                matchedSlots = Pkcs11UriUtils.GetMatchingSlotList(pkcs11uri, pkcs11Library, SlotsType.WithTokenPresent);
                Assert.IsTrue(matchedSlots.Count == 0);

                // All attributes matching one slot
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();
                ISlotInfo    slotInfo    = allSlots[0].GetSlotInfo();
                ITokenInfo   tokenInfo   = allSlots[0].GetTokenInfo();

                Pkcs11UriBuilder pkcs11UriBuilder = new Pkcs11UriBuilder();
                pkcs11UriBuilder.LibraryManufacturer = libraryInfo.ManufacturerId;
                pkcs11UriBuilder.LibraryDescription  = libraryInfo.LibraryDescription;
                pkcs11UriBuilder.LibraryVersion      = libraryInfo.LibraryVersion;
                pkcs11UriBuilder.SlotManufacturer    = slotInfo.ManufacturerId;
                pkcs11UriBuilder.SlotDescription     = slotInfo.SlotDescription;
                pkcs11UriBuilder.SlotId       = slotInfo.SlotId;
                pkcs11UriBuilder.Token        = tokenInfo.Label;
                pkcs11UriBuilder.Manufacturer = tokenInfo.ManufacturerId;
                pkcs11UriBuilder.Serial       = tokenInfo.SerialNumber;
                pkcs11UriBuilder.Model        = tokenInfo.Model;
                pkcs11uri = pkcs11UriBuilder.ToPkcs11Uri();

                matchedSlots = Pkcs11UriUtils.GetMatchingSlotList(pkcs11uri, pkcs11Library, SlotsType.WithTokenPresent);
                Assert.IsTrue(matchedSlots.Count == 1);

                // One attribute nonmatching
                pkcs11UriBuilder.Serial = "foobar";
                pkcs11uri    = pkcs11UriBuilder.ToPkcs11Uri();
                matchedSlots = Pkcs11UriUtils.GetMatchingSlotList(pkcs11uri, pkcs11Library, SlotsType.WithTokenPresent);
                Assert.IsTrue(matchedSlots.Count == 0);
            }
        }
Beispiel #11
0
        public void _03_InteractiveLoginTest()
        {
            using (IPkcs11Library pkcs11Library = _mockFactories.Pkcs11LibraryFactory.LoadPkcs11Library(_mockFactories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();
                if (libraryInfo.LibraryDescription != "Mock module" && libraryInfo.ManufacturerId != "Pkcs11Interop Project")
                {
                    Assert.Inconclusive("Test cannot be executed with this PKCS#11 library");
                }

                // Find first slot with token present
                ISlot slot = Helpers.GetUsableSlot(pkcs11Library);

                // Open RO session
                using (ISession session = slot.OpenSession(SessionType.ReadOnly))
                {
                    // Login interactively via vendor specific function C_EjectToken
                    ((IMockSession)session).InteractiveLogin();
                }
            }
        }
Beispiel #12
0
        public EncryptionServices()
        {
            _AesServices = new AesCng
            {
                BlockSize   = ciAesBlockLength << 3,
                    Mode    = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
            };

            _MD5Services            = new MD5Cng();
            _SHA1Services           = new SHA1Cng();
            _SHA256Services         = new SHA256Cng();
            _SHA384Services         = new SHA384Cng();
            _SHA512Services         = new SHA512Cng();
            _RsaServices            = new RSACng();
            _Randomness             = new RNGCryptoServiceProvider();
            _abInitialisationVector = new byte[ciAesBlockLength];

            _sPkcs11Library    = string.Empty;
            _Pkcs11LibraryInfo = null;
            CheckForOpenSc();
        }
Beispiel #13
0
        /// <summary></summary>
        private void CheckForOpenSc()
        {
            string sProgramFiles;
            object ModuleValue;

            using (RegistryKey Pkcs11Key = Registry.LocalMachine.OpenSubKey(csOpenScSubkey, false))
            {
                if (Pkcs11Key != null)
                {
                    ModuleValue = Pkcs11Key.GetValue("Module");
                    if ((ModuleValue != null) && (File.Exists((string)ModuleValue)))
                    {
                        _sPkcs11Library = (string)ModuleValue;
                    }
                }
            }

            if (string.IsNullOrEmpty(_sPkcs11Library))
            {
                sProgramFiles = Environment.GetEnvironmentVariable("ProgramFiles");
                if (File.Exists(sProgramFiles + csOpenScSubpath))
                {
                    _sPkcs11Library = sProgramFiles + csOpenScSubpath;
                }
            }

            if (string.IsNullOrEmpty(_sPkcs11Library))
            {
                _Pkcs11Factories = null;
                _Pkcs11Library   = null;
            }
            else
            {
                _Pkcs11Factories   = new Pkcs11InteropFactories();
                _Pkcs11Library     = _Pkcs11Factories.Pkcs11LibraryFactory.LoadPkcs11Library(_Pkcs11Factories, _sPkcs11Library, AppType.SingleThreaded);
                _Pkcs11LibraryInfo = _Pkcs11Library.GetInfo();
            }
        }
Beispiel #14
0
        public void _01_StructSizeListTest()
        {
            using (IPkcs11Library pkcs11Library = _mockFactories.Pkcs11LibraryFactory.LoadPkcs11Library(_mockFactories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                ILibraryInfo libraryInfo = pkcs11Library.GetInfo();
                if (libraryInfo.LibraryDescription != "Mock module" && libraryInfo.ManufacturerId != "Pkcs11Interop Project")
                {
                    Assert.Inconclusive("Test cannot be executed with this PKCS#11 library");
                }

                // Obtain a list of unmanaged struct sizes via vendor specific function C_GetUnmanagedStructSizeList
                List <ulong> unmanagedSizes = ((IMockPkcs11Library)pkcs11Library).GetUnmanagedStructSizeList();

                // Obtain a list of managed struct sizes
                List <ulong> managedSizes = GetManagedStructSizeList();

                // Compare sizes of unmanaged and managed structs
                Assert.IsTrue(unmanagedSizes.Count == managedSizes.Count);
                for (int i = 0; i < unmanagedSizes.Count; i++)
                {
                    Assert.IsTrue(unmanagedSizes[i] == managedSizes[i]);
                }
            }
        }
Beispiel #15
0
        public void ListForTreeview()
        {
            try
            {
                Node Tree = new Node();

                // Show general information about loaded library
                ILibraryInfo libraryInfo = PKCS11Library.GetInfo();
                Node         Library     = new Node()
                {
                    Header = "PKCS11 Library " + libraryInfo.LibraryDescription, IconURI = "resm:PKCS11Explorer.Assets.baseline_layers_grey_18dp.png"
                };
                Library.Children.Add(new Node()
                {
                    Header = "Filepath: " + LibraryFilePath, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                });
                Library.Children.Add(new Node()
                {
                    Header = "Manufacturer: " + libraryInfo.ManufacturerId, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                });
                Library.Children.Add(new Node()
                {
                    Header = "Description: " + libraryInfo.LibraryDescription, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                });
                Library.Children.Add(new Node()
                {
                    Header = "Version: " + libraryInfo.LibraryVersion, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                });
                var assets = AvaloniaLocator.Current.GetService <IAssetLoader>();
                Tree.Children.Add(Library);
                // Get list of all available slots
                foreach (ISlot slot in PKCS11Library.GetSlotList(SlotsType.WithOrWithoutTokenPresent))
                {
                    // Show basic information about slot
                    ISlotInfo slotInfo = slot.GetSlotInfo();
                    Node      Slot;
                    if (slotInfo.SlotFlags.TokenPresent)
                    {
                        Slot = new Node()
                        {
                            Header = "Slot " + slot.GetSlotInfo().SlotId, IconURI = "resm:PKCS11Explorer.Assets.baseline_scanner_green_18dp.png"
                        }
                    }
                    ;
                    else
                    {
                        Slot = new Node()
                        {
                            Header = "Slot " + slot.GetSlotInfo().SlotId, IconURI = "resm:PKCS11Explorer.Assets.baseline_scanner_red_18dp.png"
                        }
                    };
                    Slot.Children.Add(new Node()
                    {
                        Header = "Manufacturer: " + slotInfo.ManufacturerId, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                    });
                    Slot.Children.Add(new Node()
                    {
                        Header = "Description: " + slotInfo.SlotDescription, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                    });
                    Slot.Children.Add(new Node()
                    {
                        Header = "Token present: " + slotInfo.SlotFlags.TokenPresent, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                    });

                    if (slotInfo.SlotFlags.TokenPresent)
                    {
                        // Show basic information about token present in the slot
                        ITokenInfo tokenInfo = slot.GetTokenInfo();

                        Node Token = new Node()
                        {
                            Header = "Token " + tokenInfo.SerialNumber, IconURI = "resm:PKCS11Explorer.Assets.baseline_sim_card_green_18dp.png"
                        };
                        Token.Children.Add(new Node()
                        {
                            Header = "Manufacturer: " + tokenInfo.ManufacturerId, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                        });
                        Token.Children.Add(new Node()
                        {
                            Header = "Model: " + tokenInfo.Model, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                        });
                        Token.Children.Add(new Node()
                        {
                            Header = "Serial number: " + tokenInfo.SerialNumber, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                        });
                        Token.Children.Add(new Node()
                        {
                            Header = "Label: " + tokenInfo.Label, IconURI = "resm:PKCS11Explorer.Assets.baseline_info_blue_18dp.png"
                        });

                        /*
                         * if (tokenInfo.FreePublicMemory != uint.MaxValue)
                         *  Token.Children.Add(new Node() { Header = "Available public objects memory: " + tokenInfo.FreePublicMemory + " / " + tokenInfo.TotalPublicMemory, IconURI = "resm:PKCS11Explorer.Assets.baseline_memory_black_18dp.png" });
                         * if (tokenInfo.TotalPrivateMemory != uint.MaxValue)
                         *  Token.Children.Add(new Node() { Header = "Available private objects memory: " + tokenInfo.FreePrivateMemory + " / " + tokenInfo.TotalPrivateMemory, IconURI = "resm:PKCS11Explorer.Assets.baseline_memory_black_18dp.png" });
                         */

                        // Show public keys name
                        Node pubkeyNode = new Node()
                        {
                            Header = "Public keys", IconURI = "resm:PKCS11Explorer.Assets.baseline_search_grey_18dp.png"
                        };
                        using (ISession session = slot.OpenSession(SessionType.ReadOnly))
                        {
                            // Do something interesting in RO session
                            var attrList = new List <IObjectAttribute>();
                            attrList.Add(Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PUBLIC_KEY));
                            attrList.Add(Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true));
                            var objects = session.FindAllObjects(attrList);
                            foreach (var obj in objects)
                            {
                                if (obj.ObjectId != CK.CK_INVALID_HANDLE)
                                {
                                    var        objectHandle = Factories.ObjectHandleFactory.Create(obj.ObjectId);
                                    List <CKA> attributes   = new List <CKA>();
                                    attributes.Add(CKA.CKA_LABEL);
                                    List <IObjectAttribute> objectAttributes = session.GetAttributeValue(objectHandle, attributes);
                                    pubkeyNode.Children.Add(new Node()
                                    {
                                        Header = objectAttributes[0].GetValueAsString(), IconURI = "resm:PKCS11Explorer.Assets.baseline_vpn_key_green_18dp.png"
                                    });
                                    Console.WriteLine("Found: " + objectAttributes[0].GetValueAsString());
                                }
                            }
                            session.CloseSession();
                        }
                        Token.Children.Add(pubkeyNode);


                        // Show private keys name

                        /*Node privkeyNode = new Node() { Header = "Private keys", IconURI = "resm:PKCS11Explorer.Assets.baseline_search_black_18dp.png" };
                         * using (ISession session = slot.OpenSession(SessionType.ReadOnly))
                         * {
                         *  session.Login(CKU.CKU_USER, "");
                         *  // Do something interesting in RO session
                         *  var attrList = new List<IObjectAttribute>();
                         *  attrList.Add(factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
                         *  attrList.Add(factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true));
                         *  var objects = session.FindAllObjects(attrList);
                         *  foreach (var obj in objects)
                         *  {
                         *      if (obj.ObjectId != CK.CK_INVALID_HANDLE)
                         *      {
                         *          var objectHandle = factories.ObjectHandleFactory.Create(obj.ObjectId);
                         *          List<CKA> attributes = new List<CKA>();
                         *          attributes.Add(CKA.CKA_LABEL);
                         *          List<IObjectAttribute> objectAttributes = session.GetAttributeValue(objectHandle, attributes);
                         *          privkeyNode.Children.Add(new Node() { Header = objectAttributes[0].GetValueAsString(), IconURI = "resm:PKCS11Explorer.Assets.baseline_vpn_key_black_18dp.png" });
                         *          Console.WriteLine("Found: " + objectAttributes[0].GetValueAsString());
                         *      }
                         *  }
                         *  session.Logout();
                         *  session.CloseSession();
                         * }
                         * Token.Children.Add(privkeyNode);
                         */

                        // Show certs name
                        Node certsNode = new Node()
                        {
                            Header = "Certificates", IconURI = "resm:PKCS11Explorer.Assets.baseline_search_grey_18dp.png"
                        };
                        using (ISession session = slot.OpenSession(SessionType.ReadOnly))
                        {
                            // Do something interesting in RO session
                            var attrList = new List <IObjectAttribute>();
                            attrList.Add(Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
                            attrList.Add(Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true));
                            var objects = session.FindAllObjects(attrList);
                            foreach (var obj in objects)
                            {
                                if (obj.ObjectId != CK.CK_INVALID_HANDLE)
                                {
                                    var        objectHandle = Factories.ObjectHandleFactory.Create(obj.ObjectId);
                                    List <CKA> attributes   = new List <CKA>();
                                    attributes.Add(CKA.CKA_LABEL);
                                    List <IObjectAttribute> objectAttributes = session.GetAttributeValue(objectHandle, attributes);
                                    certsNode.Children.Add(new Node()
                                    {
                                        Header = objectAttributes[0].GetValueAsString(), IconURI = "resm:PKCS11Explorer.Assets.baseline_list_alt_green_18dp.png"
                                    });
                                    Console.WriteLine("Found: " + objectAttributes[0].GetValueAsString());
                                }
                            }
                            session.CloseSession();
                        }
                        Token.Children.Add(certsNode);


                        // Show list of mechanisms (algorithms) supported by the token
                        Node SupportedMechanisms = new Node()
                        {
                            Header = "Supported mechanisms", IconURI = "resm:PKCS11Explorer.Assets.baseline_memory_grey_18dp.png"
                        };
                        foreach (CKM mechanism in slot.GetMechanismList())
                        {
                            SupportedMechanisms.Children.Add(new Node()
                            {
                                Header = mechanism.ToString(), IconURI = "resm:PKCS11Explorer.Assets.baseline_check_circle_green_18dp.png"
                            });
                        }
                        Token.Children.Add(SupportedMechanisms);
                        Slot.Children.Add(Token);
                    }
                    Assert.AssertTrue(slot.GetTokenInfo().RwSessionCount == 0);
                    Assert.AssertTrue(slot.GetTokenInfo().SessionCount == 0);
                    Tree.Children.Add(Slot);
                }
                ListForTreeviewFinished?.Invoke(Tree, new ListForTreeviewEventArgs()
                {
                    MainNode = Tree, Success = true
                });
            }
            catch (Net.Pkcs11Interop.Common.UnmanagedException exception)
            {
                ListForTreeviewFinished?.Invoke(exception, new ListForTreeviewEventArgs()
                {
                    UnmanagedException = exception, Success = false
                });
            }
            catch (Net.Pkcs11Interop.Common.Pkcs11Exception exception)
            {
                ListForTreeviewFinished?.Invoke(exception, new ListForTreeviewEventArgs()
                {
                    Pkcs11Exception = exception, Success = false
                });
            }
            return;
        }