public void _01_BasicInitTokenAndPinTest()
        {
            using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                ISlot slot = Helpers.GetUsableSlot(pkcs11Library);

                ITokenInfo tokenInfo = slot.GetTokenInfo();

                // Check if token needs to be initialized
                if (!tokenInfo.TokenFlags.TokenInitialized)
                {
                    // Initialize token and SO (security officer) pin
                    slot.InitToken(Settings.SecurityOfficerPin, Settings.ApplicationName);

                    // Open RW session
                    using (ISession session = slot.OpenSession(SessionType.ReadWrite))
                    {
                        // Login as SO (security officer)
                        session.Login(CKU.CKU_SO, Settings.SecurityOfficerPin);

                        // Initialize user pin
                        session.InitPin(Settings.NormalUserPin);

                        session.Logout();
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Create a tracking span that is used in a completesion set in the given session.
        /// </summary>
        private ITrackingSpan CreateTrackingSpan(ICompletionSession session, ITokenInfo tokenInfo)
        {
            var triggerPoint    = session.GetTriggerPoint(session.TextView.TextBuffer);
            var currentSnapshot = textBuffer.CurrentSnapshot;

            if (tokenInfo != null)
            {
                var textViewLine = session.TextView.GetTextViewLineContainingBufferPosition(triggerPoint.GetPoint(currentSnapshot));
                var start        = textViewLine.Start.Position;
                var first        = start + tokenInfo.StartIndex;
                int length;
                if (tokenInfo.IsStartStringLiteral)
                {
                    length = 0;
                    first++;
                }
                else
                {
                    length = tokenInfo.EndIndex - tokenInfo.StartIndex + 1;
                }
                return(currentSnapshot.CreateTrackingSpan(first, length, SpanTrackingMode.EdgeInclusive));
            }
            else
            {
                var position   = triggerPoint.GetPosition(currentSnapshot);
                var separators = new[] { '"', '\'', '.', '>', '<', ' ' };
                var text       = currentSnapshot.GetText();
                var first      = (text[position - 1] == ' ')
                                ? position
                                : text.Substring(0, position).LastIndexOfAny(separators);

                return(currentSnapshot.CreateTrackingSpan(first, position - first, SpanTrackingMode.EdgeInclusive));
            }
        }
 /// <summary>
 /// Checks whether this <see cref="ITokenInfo"/> is not null,
 /// its <see cref="ITokenInfo.TokenId"/> is not zero,
 /// its <see cref="ITokenInfo.ExpirationDateUtc"/> is greater than now and
 /// its <see cref="ITokenInfo.Active"/> is true.
 /// </summary>
 /// <param name="this">This <see cref="ITokenInfo"/>.</param>
 /// <param name="allowedDelta">Optional that applies to <see cref="DateTime.UtcNow"/>.</param>
 /// <returns>True if this token info is valid.</returns>
 public static bool IsValid(this ITokenInfo @this, TimeSpan?allowedDelta = null)
 {
     return(@this != null &&
            @this.TokenId > 0 &&
            @this.ExpirationDateUtc > DateTime.UtcNow.Add(allowedDelta ?? TimeSpan.Zero) &&
            @this.Active);
 }
        /// <summary>
        /// Checks whether token information matches PKCS#11 URI
        /// </summary>
        /// <param name="pkcs11Uri">PKCS#11 URI</param>
        /// <param name="tokenInfo">Token information</param>
        /// <returns>True if token information matches PKCS#11 URI</returns>
        public static bool Matches(Pkcs11Uri pkcs11Uri, ITokenInfo tokenInfo)
        {
            if (pkcs11Uri == null)
                throw new ArgumentNullException("pkcs11Uri");

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

            return Pkcs11UriSharedUtils.Matches(pkcs11Uri, tokenInfo.Label, tokenInfo.ManufacturerId, tokenInfo.SerialNumber, tokenInfo.Model);
        }
Example #5
0
 /// <summary>Base constructor for initialisation.</summary>
 private PgpToken(EncryptionServices Cryptography)
 {
     _eStatus      = nStatus.Undefined;
     _eType        = nType.Undefined;
     _sSlotName    = string.Empty;
     _TokenInfo    = null;
     _UserIdPacket = null;
     _Cryptography = Cryptography;
     _KeyPacket    = null;
     _ltSubkeys    = new List <PgpSignature>();
 }
Example #6
0
        // Tokens
        /// <summary> Get information about the currently authorized token </summary>
        public async Task <ITokenInfo> GetTokenInfoAsync(RequestOptions options = null)
        {
            if (TokenInfo != null)
            {
                return(TokenInfo);
            }
            var token = await ClientHelper.GetTokenInfoAsync(this, options).ConfigureAwait(false);

            TokenInfo = token;
            return(token);
        }
Example #7
0
 void Handle_OnScanResult(ZXing.Result result)
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         zxing.IsAnalyzing    = false; //読み取り停止
         ITokenInfo tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);
         HttpPostAddPoint obj = new HttpPostAddPoint(tokenInfo.TOKEN, result.Text);
         string point         = obj.Exe().Point;
         await DisplayAlert("らくXスタ", "ポイントをつけたよ!", "OK");
         zxing.IsAnalyzing = true;   //読み取り再開
     });
 }
Example #8
0
        /// <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 Pkcs11TokenInfo class
        /// </summary>
        /// <param name="tokenInfo">Information about PKCS#11 token (CK_TOKEN_INFO)</param>
        internal Pkcs11TokenInfo(ITokenInfo tokenInfo)
        {
            if (tokenInfo == null)
            {
                throw new ArgumentNullException(nameof(tokenInfo));
            }

            _manufacturer = tokenInfo.ManufacturerId;
            _model        = tokenInfo.Model;
            _serialNumber = tokenInfo.SerialNumber;
            _label        = tokenInfo.Label;
            _hasProtectedAuthenticationPath = tokenInfo.TokenFlags.ProtectedAuthenticationPath;
            _initialized = tokenInfo.TokenFlags.TokenInitialized;
        }
Example #11
0
        private async void madecardList_Refreshing(object sender, EventArgs e)
        {
            await Task.Run(() => System.Threading.Thread.Sleep(3000));

            items.Clear();
            ITokenInfo tokenInfo            = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);
            HttpPostGetCreatedCardsList obj = new HttpPostGetCreatedCardsList(tokenInfo.TOKEN);

            foreach (var item in obj.Exe())
            {
                items.Add(item);
            }
            cardList.EndRefresh();
        }
Example #12
0
        public ActionResult GetAllCerts()
        {
            Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

            using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, DllLibPath, AppType.MultiThreaded))
            {
                ISlot slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent).FirstOrDefault();

                if (slot is null)
                {
                    return(Ok("No slots found"));
                }



                ITokenInfo tokenInfo = slot.GetTokenInfo();

                ISlotInfo slotInfo = slot.GetSlotInfo();

                using (var session = slot.OpenSession(SessionType.ReadWrite))
                {
                    session.Login(CKU.CKU_USER, Encoding.UTF8.GetBytes(TokenPin));


                    var certificateSearchAttributes = new List <IObjectAttribute>()
                    {
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE),
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true),
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509)
                    };

                    IObjectHandle certificate = session.FindAllObjects(certificateSearchAttributes).FirstOrDefault();

                    var certificateValue = session.GetAttributeValue(certificate, new List <CKA>
                    {
                        CKA.CKA_VALUE
                    });


                    var xcert = new X509Certificate2(certificateValue[0].GetValueAsByteArray());

                    return(Ok(

                               new
                    {
                        xcert.Thumbprint,
                        xcert.Subject,
                        xcert.IssuerName,
                        hasKeyNull = xcert.PrivateKey is null
                    }));
Example #13
0
        public void _01_BasicTokenInfoTest()
        {
            using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                ISlot slot = Helpers.GetUsableSlot(pkcs11);

                // Get token info
                ITokenInfo tokenInfo = slot.GetTokenInfo();

                // Do something interesting with token info
                Assert.IsFalse(String.IsNullOrEmpty(tokenInfo.ManufacturerId));
            }
        }
Example #14
0
    private static (string accessToken, ITokenClientFactory tokenClientFactory) MockTokenClientFactory()
    {
        var        accessToken = Guid.NewGuid().ToString();
        ITokenInfo tokenInfo   = Substitute.For <ITokenInfo>();

        tokenInfo.AccessToken.Returns(accessToken);
        ITokenClient tokenClient = Substitute.For <ITokenClient>();

        tokenClient.GetTokenAsync(Arg.Any <bool>()).Returns(Result(tokenInfo));
        ITokenClientFactory tokenClientFactory = Substitute.For <ITokenClientFactory>();

        tokenClientFactory.GetTokenClient(IamClientOptions.IamTokenClientName).Returns(Result(tokenClient));
        return(accessToken, tokenClientFactory);
    }
Example #15
0
        public void PostCreateCardData(object sender, EventArgs e)
        {
            string     name      = card_name.Text;
            string     info      = card_info.Text;
            string     img       = card_img.Text;
            ITokenInfo tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);

            HttpPostCreateCard obj = new HttpPostCreateCard(name, info, img, tokenInfo.TOKEN);
            var card_data          = obj.Exe();

            var result = DisplayAlert(card_data.CardName, "が作成されたよ", "OK");

            card_name.Text = "";
            card_info.Text = "";
            card_img.Text  = "";
        }
Example #16
0
        public HomePage(/*string token*/)
        {
            InitializeComponent();
            //Token 取得 global だからOK
            ITokenInfo           tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);
            HttpPostGetCardsList obj       = new HttpPostGetCardsList(tokenInfo.TOKEN);

            items = obj.Exe();

            // ListViewにデータソースをセット
            cardList.ItemsSource = items;
            //押したときのデータ
            cardList.ItemSelected += (sender, e) =>
            {
                Navigation.PushAsync(new DetailPage((ItemIncludeImages)e.SelectedItem));
            };
        }
Example #17
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);
            }
        }
Example #18
0
        private async Task LogoutInternalAsync()
        {
            if (LoginState == LoginState.LoggedOut)
            {
                return;
            }
            LoginState = LoginState.LoggingIn;

            await ApiClient.LogoutAsync().ConfigureAwait(false);

            await OnLogoutAsync().ConfigureAwait(false);

            TokenInfo  = null;
            LoginState = LoginState.LoggedOut;

            await _loggedOutEvent.InvokeAsync().ConfigureAwait(false);
        }
Example #19
0
        public MadePage()
        {
            InitializeComponent();
            //起動時所持カード読み取り処理(仮)
            ITokenInfo tokenInfo            = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);
            HttpPostGetCreatedCardsList obj = new HttpPostGetCreatedCardsList(tokenInfo.TOKEN);

            items = obj.Exe();

            // ListViewにデータソースをセット
            cardList.ItemsSource = items;
            //押したときのデータ
            cardList.ItemSelected += (sender, e) =>
            {
                Navigation.PushAsync(new DetailPage2((CreatedItems)e.SelectedItem));
            };
        }
Example #20
0
        public string Get(ITokenInfo info)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_authenticationSettings.SecretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, info.Username),
                    new Claim(JwtRegisteredClaimNames.Jti, info.Id.ToString()),
                    new Claim(ClaimTypes.Role, Roles.Dictionary[info.Role])
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Example #21
0
        internal virtual async Task OnLoginAsync(bool validateToken)
        {
            if (!validateToken)
            {
                return;
            }

            var tokenInfo = await GetTokenInfoAsync().ConfigureAwait(false);

            if (!tokenInfo.IsValid)
            {
                await RestLogger.ErrorAsync("Token is not valid").ConfigureAwait(false);
                await LogoutAsync().ConfigureAwait(false);

                return;
            }

            TokenInfo = tokenInfo;
        }
Example #22
0
        public static ISlot GetUsableSlot(IPkcs11Library pkcs11Library)
        {
            // Get list of available slots with token present
            List <ISlot> slots = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent);

            // First slot with token present is OK...
            ISlot matchingSlot = slots[0];

            // ...unless there are matching criteria specified in Settings class
            {
                matchingSlot = null;

                foreach (ISlot slot in slots)
                {
                    ITokenInfo tokenInfo = null;

                    try
                    {
                        tokenInfo = slot.GetTokenInfo();
                    }
                    catch (Pkcs11Exception ex)
                    {
                        if (ex.RV != CKR.CKR_TOKEN_NOT_RECOGNIZED && ex.RV != CKR.CKR_TOKEN_NOT_PRESENT)
                        {
                            throw;
                        }
                    }

                    if (tokenInfo == null)
                    {
                        continue;
                    }

                    matchingSlot = slot;
                    break;
                }
            }

            return(matchingSlot);
        }
Example #23
0
 internal Pkcs11TokenInfo(ITokenInfo tokenInfo)
 {
     Label                       = tokenInfo.Label;
     ManufacturerId              = tokenInfo.ManufacturerId;
     Model                       = tokenInfo.Model;
     SerialNumber                = tokenInfo.SerialNumber;
     Flags                       = tokenInfo.TokenFlags.Flags;
     Rng                         = tokenInfo.TokenFlags.Rng;
     WriteProtected              = tokenInfo.TokenFlags.WriteProtected;
     LoginRequired               = tokenInfo.TokenFlags.LoginRequired;
     UserPinInitialized          = tokenInfo.TokenFlags.UserPinInitialized;
     RestoreKeyNotNeeded         = tokenInfo.TokenFlags.RestoreKeyNotNeeded;
     ClockOnToken                = tokenInfo.TokenFlags.ClockOnToken;
     ProtectedAuthenticationPath = tokenInfo.TokenFlags.ProtectedAuthenticationPath;
     DualCryptoOperations        = tokenInfo.TokenFlags.DualCryptoOperations;
     TokenInitialized            = tokenInfo.TokenFlags.TokenInitialized;
     SecondaryAuthentication     = tokenInfo.TokenFlags.SecondaryAuthentication;
     UserPinCountLow             = tokenInfo.TokenFlags.UserPinCountLow;
     UserPinFinalTry             = tokenInfo.TokenFlags.UserPinFinalTry;
     UserPinLocked               = tokenInfo.TokenFlags.UserPinLocked;
     UserPinToBeChanged          = tokenInfo.TokenFlags.UserPinToBeChanged;
     SoPinCountLow               = tokenInfo.TokenFlags.SoPinCountLow;
     SoPinFinalTry               = tokenInfo.TokenFlags.SoPinFinalTry;
     SoPinLocked                 = tokenInfo.TokenFlags.SoPinLocked;
     SoPinToBeChanged            = tokenInfo.TokenFlags.SoPinToBeChanged;
     MaxSessionCount             = tokenInfo.MaxSessionCount;
     SessionCount                = tokenInfo.SessionCount;
     MaxRwSessionCount           = tokenInfo.MaxRwSessionCount;
     RwSessionCount              = tokenInfo.RwSessionCount;
     MaxPinLen                   = tokenInfo.MaxPinLen;
     MinPinLen                   = tokenInfo.MinPinLen;
     TotalPublicMemory           = tokenInfo.TotalPublicMemory;
     FreePublicMemory            = tokenInfo.FreePublicMemory;
     TotalPrivateMemory          = tokenInfo.TotalPrivateMemory;
     FreePrivateMemory           = tokenInfo.FreePrivateMemory;
     HardwareVersion             = tokenInfo.HardwareVersion;
     FirmwareVersion             = tokenInfo.FirmwareVersion;
     UtcTime                     = tokenInfo.UtcTimeString;
 }
Example #24
0
        public LoginPage()
        {
            InitializeComponent();
            ITokenInfo tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);

            loginButton.Clicked += async(sender, e) =>
            {
                HttpPostLogin regster = new HttpPostLogin(Username.Text, Password.Text);
                var           token   = new Token
                {
                    CachedToken = regster.Exe().Token
                };
                await BlobCache.LocalMachine.InsertObject("cache", token);

                tokenInfo.TOKEN = token.CachedToken;
                await Navigation.PushAsync(new Pages.MainPage());
            };

            signupButton.Clicked += (sender, e) =>
            {
                Navigation.PushAsync(new Pages.SignUpPage());
            };
        }
Example #25
0
        protected override void OnStart()
        {
            var startButton = new Button {
                Text = "スタート"
            };

            ITokenInfo tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);

            startButton.Clicked += async(sender, e) =>
            {
                try
                {
                    var loaded = await BlobCache.LocalMachine.GetObject <Token>("cache");

                    tokenInfo.TOKEN = loaded.CachedToken;
                    MainPage        = new NavigationPage(new Pages.MainPage());
                }
                catch
                {
                    //飛ばない
                    MainPage = new NavigationPage(new Pages.LoginPage());
                }
            };

            MainPage = new ContentPage
            {
                Padding = new Thickness(20),
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children        =
                    {
                        startButton,
                    }
                }
            };
        }
Example #26
0
 /// <summary>
 /// Create a new completion set for the given completions.
 /// </summary>
 private CompletionSet CreateCompletionSet(IEnumerable <XmlResourceCompletion> completions, ICompletionSession session, ITokenInfo tokenInfo)
 {
     return(new XmlResourceCompletionSet("Dot42", "Dot42",
                                         CreateTrackingSpan(session, tokenInfo),
                                         completions,
                                         null));
 }
 /// <summary>
 /// Create a new completion set for the given completions.
 /// </summary>
 private CompletionSet CreateCompletionSet(IEnumerable<XmlResourceCompletion> completions, ICompletionSession session, ITokenInfo tokenInfo)
 {
     return new XmlResourceCompletionSet("Dot42", "Dot42",
         CreateTrackingSpan(session, tokenInfo),
         completions,
         null);
 }
Example #28
0
 internal virtual Task OnLogoutAsync()
 {
     TokenInfo = null;
     return(Task.Delay(0));
 }
        /// <summary>
        /// Create a tracking span that is used in a completesion set in the given session.
        /// </summary>
        private ITrackingSpan CreateTrackingSpan(ICompletionSession session, ITokenInfo tokenInfo)
        {
            var triggerPoint = session.GetTriggerPoint(session.TextView.TextBuffer);
            var currentSnapshot = textBuffer.CurrentSnapshot;
            if (tokenInfo != null)
            {
                var textViewLine = session.TextView.GetTextViewLineContainingBufferPosition(triggerPoint.GetPoint(currentSnapshot));
                var start = textViewLine.Start.Position;
                var first = start + tokenInfo.StartIndex;
                int length;
                if (tokenInfo.IsStartStringLiteral)
                {
                    length = 0;
                    first++;
                }
                else
                {
                    length = tokenInfo.EndIndex - tokenInfo.StartIndex + 1;
                }
                return currentSnapshot.CreateTrackingSpan(first, length, SpanTrackingMode.EdgeInclusive);
            }
            else
            {
                var position = triggerPoint.GetPosition(currentSnapshot);
                var separators = new[] {'"', '\'', '.', '>', '<', ' '};
                var text = currentSnapshot.GetText();
                var first = (text[position - 1] == ' ')
                                ? position
                                : text.Substring(0, position).LastIndexOfAny(separators);

                return currentSnapshot.CreateTrackingSpan(first, position - first, SpanTrackingMode.EdgeInclusive);
            }
        }
Example #30
0
        public ItemIncludeImages(string Name, string Img, string Info, string Id, string Point)
        {
            ITokenInfo tokenInfo = DependencyService.Get <ITokenInfo>(DependencyFetchTarget.GlobalInstance);

            this.Name  = Name;
            this.Img   = Img;
            this.Info  = Info;
            this.Id    = Id;
            this.Point = Point;
            if (int.Parse(Point) == 0)
            {
                this.Image1  = "circle.png";
                this.Image2  = "circle.png";
                this.Image3  = "circle.png";
                this.Image4  = "circle.png";
                this.Image5  = "circle.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 1)
            {
                this.Image1  = "good.png";
                this.Image2  = "circle.png";
                this.Image3  = "circle.png";
                this.Image4  = "circle.png";
                this.Image5  = "circle.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 2)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "circle.png";
                this.Image4  = "circle.png";
                this.Image5  = "circle.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 3)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "circle.png";
                this.Image5  = "circle.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 4)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "circle.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 5)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "circle.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 6)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "good.png";
                this.Image7  = "circle.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 7)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "good.png";
                this.Image7  = "good.png";
                this.Image8  = "circle.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 8)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "good.png";
                this.Image7  = "good.png";
                this.Image8  = "good.png";
                this.Image9  = "circle.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) == 9)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "good.png";
                this.Image7  = "good.png";
                this.Image8  = "good.png";
                this.Image9  = "good.png";
                this.Image10 = "circle.png";
            }
            else if (int.Parse(Point) >= 10)
            {
                this.Image1  = "good.png";
                this.Image2  = "good.png";
                this.Image3  = "good.png";
                this.Image4  = "good.png";
                this.Image5  = "good.png";
                this.Image6  = "good.png";
                this.Image7  = "good.png";
                this.Image8  = "good.png";
                this.Image9  = "good.png";
                this.Image10 = "good.png";
            }
        }
Example #31
0
 /// <summary>
 /// Create a new instance.
 /// </summary>
 /// <param name="accessToken">The access token.</param>
 /// <param name="refreshToken">The refresh token.</param>
 public TokenPair(ITokenInfo accessToken, ITokenInfo refreshToken)
 {
     AccessToken  = accessToken;
     RefreshToken = refreshToken;
 }
Example #32
0
        /// <summary>
        /// Finds slot containing the token that matches criteria specified in Settings class
        /// </summary>
        /// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
        /// <returns>Slot containing the token that matches criteria</returns>
        public static IRutokenSlot GetUsableSlot(IRutokenPkcs11Library pkcs11)
        {
            // Get list of available slots with token present
            List <IRutokenSlot> slots = pkcs11.GetRutokenSlotList(SlotsType.WithTokenPresent);

            Assert.IsNotNull(slots);
            Assert.IsTrue(slots.Count > 0);

            // First slot with token present is OK...
            IRutokenSlot matchingSlot = slots[0];

            // ...unless there are matching criteria specified in Settings class
            if (Settings.TokenSerial != null || Settings.TokenLabel != null)
            {
                matchingSlot = null;

                foreach (IRutokenSlot slot in slots)
                {
                    ITokenInfo tokenInfo = null;

                    try
                    {
                        tokenInfo = slot.GetTokenInfo();
                    }
                    catch (Pkcs11Exception ex)
                    {
                        if (ex.RV != CKR.CKR_TOKEN_NOT_RECOGNIZED && ex.RV != CKR.CKR_TOKEN_NOT_PRESENT)
                        {
                            throw;
                        }
                    }

                    if (tokenInfo == null)
                    {
                        continue;
                    }

                    if (!string.IsNullOrEmpty(Settings.TokenSerial))
                    {
                        if (0 != string.Compare(Settings.TokenSerial, tokenInfo.SerialNumber, StringComparison.Ordinal))
                        {
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(Settings.TokenLabel))
                    {
                        if (0 != string.Compare(Settings.TokenLabel, tokenInfo.Label, StringComparison.Ordinal))
                        {
                            continue;
                        }
                    }

                    matchingSlot = slot;
                    break;
                }
            }

            Assert.IsTrue(matchingSlot != null, "Token matching criteria specified in Settings class is not present");
            return(matchingSlot);
        }