Пример #1
0
        /// <summary>
        /// Append <c>UserData</c> to the list in preparation to send to Azure
        /// </summary>
        /// <param name="sender">A Sender object</param>
        /// <param name="e">RoutedEventArgs</param>
        private void AddUserDataToListButton_Click(object sender, RoutedEventArgs e)
        {
            //Clear Globals
            personDataName = PersonUserDataNameTextBox.Text;
            personUserData = PersonUserDataTextBox.Text;

            //Reset UI Globals
            SubmissionStatusTextBlock.Text = "";
            TrainStatusTextBlock.Text      = "";

            //Reset UI Colors
            SubmissionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
            TrainStatusTextBlock.Foreground      = new SolidColorBrush(Colors.Black);

            //Logic
            if (personDataName.Length > 0 && personUserData.Length > 0)
            {
                userDataPayload.Add(new UserData()
                {
                    UserDataLabel = personDataName, UserDataValue = personUserData
                });
            }

            jsonString = JsonConvert.SerializeObject(userDataPayload);
            UpdateUserDataStatusTextBlock.Text  = "User Data added to payload with the following User Data: ";
            UpdateUserDataPayloadTextBlock.Text = jsonString;

            //Using Chilkat library to help pretty print the user data
            Chilkat.JsonObject json        = new Chilkat.JsonObject();
            string             emittedJson = "";

            foreach (var j in userDataPayload)
            {
                string jsonStr = JsonConvert.SerializeObject(j);

                bool success = json.Load(jsonStr);
                if (success != true)
                {
                    Debug.WriteLine(json.LastErrorText);
                    return;
                }

                //  To pretty-print, set the EmitCompact property equal to false
                json.EmitCompact = false;

                //  If bare-LF line endings are desired, turn off EmitCrLf
                //  Otherwise CRLF line endings are emitted.
                json.EmitCrLf = true;

                //  Emit the formatted JSON:
                emittedJson = emittedJson + json.Emit();
            }
            JSONTextBlock.Text       = emittedJson;
            JSONHeaderTextBlock.Text = knownPerson.Name + " User Data:";

            PersonUserDataNameTextBox.Text = "";
            PersonUserDataTextBox.Text     = "";

            UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);
        }
Пример #2
0
        public static string CreateToken(List <Claim> claims)
        {
            Chilkat.Jwt jwt = new Chilkat.Jwt();

            //  Build the JOSE header
            Chilkat.JsonObject jose = new Chilkat.JsonObject();
            //  Use HS256.  Pass the string "HS384" or "HS512" to use a different algorithm.
            bool success = jose.AppendString("alg", "HS256");

            jose.AppendString("typ", "JWT");

            //  Now build the JWT claims (also known as the payload)
            Chilkat.JsonObject jsonClaims = new Chilkat.JsonObject();
            //success = jsonClaims.AppendString("issuer", "http://www.vouchers.net");
            //success = jsonClaims.AppendString("aud", "http://www.vouchers.net");

            //  Set the timestamp of when the JWT was created to now.
            int curDateTime = jwt.GenNumericDate(0);

            jsonClaims.AddIntAt(-1, "iat", curDateTime);

            //  Set the "not process before" timestamp to now.
            jsonClaims.AddIntAt(-1, "nbf", curDateTime);

            //  Set the timestamp defining an expiration time (end time) for the token
            //  to be now + 1 hour (3600 seconds)
            jsonClaims.AddIntAt(-1, "exp", curDateTime + 3600);

            //  Produce the smallest possible JWT:
            jwt.AutoCompact = true;

            string strJwt = jwt.CreateJwt(jose.Emit(), jsonClaims.Emit(), "Pa$$w0rd");

            return(strJwt);
        }
Пример #3
0
        public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
        {
            // Arrange
            AuthenticationManager authenticationManager = new AuthenticationManager();

            authenticationManager.client = _factory.CreateClient();
            File.WriteAllBytes("rsaCert.pfx", Startup.RsaCertPfxBytes);
            Chilkat.Pfx pfx = new Chilkat.Pfx();
            if (File.Exists("rsaCert.pfx"))
            {
                pfx.LoadPfxFile("rsaCert.pfx", "12345");
            }

            File.Delete("rsaCert.pfx");

            // Act
            //public key from certificate
            //Chilkat package is used to process X509 certificate 2 from pfx file to JWKS (Json Web Key Set) from which it is possible
            //to extract public key X5c. Key is then compared with the one pulled from mocked server.
            string alias    = "my_ecc_key1";
            string password = "******";

            Chilkat.JavaKeyStore  jks      = pfx.ToJavaKeyStore(alias, password);
            Chilkat.StringBuilder sbJwkSet = new Chilkat.StringBuilder();
            jks.ToJwkSet(password, sbJwkSet);
            Chilkat.JsonObject jwkSet = new Chilkat.JsonObject();
            jwkSet.LoadSb(sbJwkSet);
            jwkSet.EmitCompact = false;
            var               jwksCheck  = jwkSet.Emit();
            JsonWebKeySet     jwkscheck  = new JsonWebKeySet(jwksCheck);
            List <JsonWebKey> keyList2   = new List <JsonWebKey>(jwkscheck.Keys);
            string            publicKey2 = keyList2[0].X5c[0];

            //response from server
            System.Net.Http.HttpResponseMessage response = await authenticationManager.client.GetAsync(url);

            //public key from endpoint
            string publicKey = authenticationManager.GetPublicKey(url);

            // Assert
            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal(publicKey2, publicKey);
            authenticationManager.client.Dispose();
            _factory.Dispose();
        }
Пример #4
0
        // URLs to help understand this topic:
        // https://developers.google.com/identity/protocols/OAuth2InstalledApp
        //
        private bool oauth2_google(string scope)
        {
            // Generates state and PKCE values.
            string state         = m_prng.GenRandom(32, base64Url);
            string code_verifier = m_prng.GenRandom(32, base64Url);

            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.EncodingMode  = base64Url;
            crypt.HashAlgorithm = "SHA256";
            string       code_challenge        = crypt.HashStringENC(code_verifier);
            const string code_challenge_method = "S256";

            //Create a Chilkat socket for listening.  Begin listening asynchronously.
            Chilkat.Socket listenSocket = new Chilkat.Socket();
            int            backlog      = 5;
            int            listenPort   = 0;

            // Passing a listenPort = 0 causes BindAndListen to find a random unused port.
            // The chosen port will be available via the ListenPort property.
            if (!listenSocket.BindAndListen(listenPort, backlog))
            {
                fgAppendToErrorLog(listenSocket.LastErrorText);
                popupError("Failed to BindAndListen");
                return(false);
            }

            // Get the chosen listen port
            // This ListenPort property is available starting in Chilkat v9.5.0.59
            listenPort = listenSocket.ListenPort;

            // Creates a redirect URI using an available port on the loopback address.
            string redirect_uri = "http://127.0.0.1:" + listenPort.ToString() + "/";

            //Wait a max of 5 minutes.  The OnTaskCompleted event is called when an incoming connection
            //arrives, or when the listen failed.
            listenSocket.OnTaskCompleted += listenSocket_OnTaskCompleted;
            Chilkat.Task task = listenSocket.AcceptNextConnectionAsync(5 * 60000);
            if (task == null)
            {
                MessageBox.Show("Failed to start socket accept...");
                return(false);
            }

            // Add some information that will be needed by the TaskCompleted event..
            Chilkat.JsonObject taskData = new Chilkat.JsonObject();
            taskData.AppendString("code_verifier", code_verifier);
            taskData.AppendString("redirect_uri", redirect_uri);
            task.UserData = taskData.Emit();

            // Start the task.
            task.Run();

            // Creates the OAuth 2.0 authorization request.
            Chilkat.StringBuilder sbAuthRequest = new Chilkat.StringBuilder();
            sbAuthRequest.Append(authorizationEndpoint);
            sbAuthRequest.Append("?response_type=code&scope=");
            sbAuthRequest.Append(m_encoder.EncodeString(scope, "utf-8", "url"));
            sbAuthRequest.Append("&redirect_uri=");
            sbAuthRequest.Append(m_encoder.EncodeString(redirect_uri, "utf-8", "url"));
            sbAuthRequest.Append("&client_id=");
            sbAuthRequest.Append(googleAppClientId);
            sbAuthRequest.Append("&state=");
            sbAuthRequest.Append(state);
            sbAuthRequest.Append("&code_challenge=");
            sbAuthRequest.Append(code_challenge);
            sbAuthRequest.Append("&code_challenge_method=");
            sbAuthRequest.Append(code_challenge_method);

            // Here is a shorter way of building the URL in C#
            //string authorizationRequest = string.Format("{0}?response_type=code&scope={6}&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
            //    authorizationEndpoint,  // 0
            //    System.Uri.EscapeDataString(redirect_uri), // 1
            //    googleAppClientId, // 2
            //    state, // 3
            //    code_challenge, // 4
            //    code_challenge_method, // 5
            //    System.Uri.EscapeDataString(scope)); // 6

            // Get authorization from Google account owner...
            webBrowser1.Navigate(sbAuthRequest.GetAsString());

            return(true);
        }
        /// <summary>
        /// Firma del file
        /// </summary>
        /// <param name="SubjectCN">Subject Common Name</param>
        /// <param name="pathFile">file da firmare</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <param name="pin">pin smartcard/usb (opzionale). Se non fornito comparirà una finestra di dialogo del sistema operativo Windows per indicare il pin</param>
        /// <param name="csp">provider csp (opzionale). Se non indicato verrà selezionato automaticamente. Utilizzare questo parametro per indicarne uno specifico. Utilizzare il metodo CSPs per visualizza i csp presenti nel sistema</param>
        /// <returns>firma avvenuta con successo</returns>
        public static bool Firma(string SubjectCN, string pathFile, ref string lastError, string pin = null, string csp = null)
        {
            bool success = false;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

                //  Utilizza il certificato su una smartcard o su USB.
                Chilkat.Cert cert = new Chilkat.Cert();

                // cryptographic service provider
                if (!string.IsNullOrWhiteSpace(csp))
                {
                    success = cert.LoadFromSmartcard(csp);
                    if (success != true)
                    {
                        lastError = cert.LastErrorText;
                        return(success);
                    }
                }

                //  Passa il Subject CN del certificato al metodo LoadByCommonName.
                success = cert.LoadByCommonName(SubjectCN);
                if (success != true)
                {
                    lastError = cert.LastErrorText;
                    return(success);
                }

                //  Fornire il PIN della smartcard.
                //  Se il pin non è fornito esplicitamente qui,
                //  Se non fornito dovrebbe comparire una finestra di dialogo del sistema operativo Windows per indicare il pin
                if (!string.IsNullOrWhiteSpace(pin))
                {
                    cert.SmartCardPin = pin;
                }

                //  Fornisce il certificato per firmarlo
                success = crypt.SetSigningCert(cert);
                if (success != true)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                //  Indica l'algoritmo da utilizzare
                crypt.HashAlgorithm = "sha256";

                //  Specifico gli attributi firmati per essere inclusi.
                //  (Questo è quello che fa un CAdES-BES compliant.)
                Chilkat.JsonObject jsonSignedAttrs = new Chilkat.JsonObject();
                jsonSignedAttrs.UpdateInt("contentType", 1);
                jsonSignedAttrs.UpdateInt("signingTime", 1);
                jsonSignedAttrs.UpdateInt("messageDigest", 1);
                jsonSignedAttrs.UpdateInt("signingCertificateV2", 1);
                crypt.SigningAttributes = jsonSignedAttrs.Emit();


                string sigFile = $"{pathFile}.{Enum.GetName(typeof(EstensioniFile), EstensioniFile.p7m)}";

                //  Creo una firma CAdES-BES, che contiene i dati originali
                success = crypt.CreateP7M(pathFile, sigFile);
                if (!success)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
Пример #6
0
        /// <summary>
        /// Updates Face Resource Person User Data
        /// </summary>
        /// <param name="sender">A sender object</param>
        /// <param name="e">RoutedEventArgs</param>
        /// <remarks>
        /// <para>Can submit a single Key/Value pair without adding to the list using <c>AddUserDataToListButton_Click</c>.</para>
        /// <para>Submission will replace any key/value pairs that already exist for the Person</para>
        /// </remarks>
        private async void UpdateUserDataButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            //Clear Globals
            personDataName = PersonUserDataNameTextBox.Text;
            personUserData = PersonUserDataTextBox.Text;

            //Reset UI Globals
            SubmissionStatusTextBlock.Text = "";
            TrainStatusTextBlock.Text      = "";

            //Reset UI Colors
            SubmissionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
            TrainStatusTextBlock.Foreground      = new SolidColorBrush(Colors.Black);

            //Logic
            if (personDataName.Length > 0 && personUserData.Length > 0)
            {
                userDataPayload.Add(new UserData()
                {
                    UserDataLabel = personDataName, UserDataValue = personUserData
                });
            }

            jsonString = JsonConvert.SerializeObject(userDataPayload);

            //UI Text Change
            UpdateUserDataStatusTextBlock.Text = "User Data added to payload with the following User Data: " + jsonString;
            PersonUserDataNameTextBox.Text     = "";
            PersonUserDataTextBox.Text         = "";

            //UI Color Change
            PersonUserDataTextBox.Foreground     = new SolidColorBrush(Colors.Black);
            PersonUserDataNameTextBox.Foreground = new SolidColorBrush(Colors.Black);

            if (knownGroup != null && knownPerson != null && knownPerson.Name.Length > 0)
            {
                UpdateUserDataErrorText.Visibility = Visibility.Collapsed;
                //Check if this person already exist
                bool     personAlreadyExist = false;
                Person[] ppl = await GetKnownPeople();

                foreach (Person p in ppl)
                {
                    if (p.Name == knownPerson.Name)
                    {
                        personAlreadyExist = true;
                    }
                }

                if (!personAlreadyExist)
                {
                    UpdateUserDataStatusTextBlock.Text = $"Person not found. Fetch a known Person";

                    UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                }

                if (personAlreadyExist)
                {
                    await ApiCallAllowed(true);

                    await faceServiceClient.UpdatePersonAsync(personGroupId, knownPerson.PersonId, knownPerson.Name, jsonString);

                    Person[] people = await GetKnownPeople();

                    var matchedPeople = people.Where(p => p.Name == personName);

                    if (matchedPeople.Count() > 0)
                    {
                        knownPerson = matchedPeople.FirstOrDefault();

                        //Change UI Text
                        UpdateUserDataStatusTextBlock.Text  = "Updated Person: " + knownPerson.Name + " with the following User Data: " + knownPerson.UserData;
                        UpdateUserDataPayloadTextBlock.Text = knownPerson.UserData;

                        //Change UI Colors
                        UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);

                        Chilkat.JsonObject json        = new Chilkat.JsonObject();
                        string             emittedJson = "";

                        foreach (var j in userDataPayload)
                        {
                            string jsonStr = JsonConvert.SerializeObject(j);

                            bool success = json.Load(jsonStr);
                            if (success != true)
                            {
                                Debug.WriteLine(json.LastErrorText);
                                return;
                            }

                            //  To pretty-print, set the EmitCompact property equal to false
                            json.EmitCompact = false;

                            //  If bare-LF line endings are desired, turn off EmitCrLf
                            //  Otherwise CRLF line endings are emitted.
                            json.EmitCrLf = true;

                            //  Emit the formatted JSON:
                            emittedJson = emittedJson + json.Emit();
                        }
                        JSONTextBlock.Text       = emittedJson;
                        JSONHeaderTextBlock.Text = knownPerson.Name + " User Data:";
                    }
                }
            }
            else
            {
                UpdateUserDataErrorText.Text       = "There was a problem with the request. Please check that you have successfully Fetched a Person Group and Person and that you have entered valid User Data";
                UpdateUserDataErrorText.Visibility = Visibility.Visible;
            }
        }
Пример #7
0
        /// <summary>
        /// Check if Person exists and retrieve that Person object to work with.
        /// </summary>
        /// <param name="sender">A sender object</param>
        /// <param name="e">RoutedEventArgs</param>
        /// <remarks>
        /// <para>Can't add/change user data, pictures, and model until Person has been fetched.</para>
        /// </remarks>
        private async void FetchPersonButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            //Clear Globals
            userDataPayload.Clear();
            personName = PersonNameTextBox.Text;
            authKey    = AuthKeyTextBox.Text;

            //Reset UI Globals
            UpdateUserDataStatusTextBlock.Text  = "";
            SubmissionStatusTextBlock.Text      = "";
            TrainStatusTextBlock.Text           = "";
            UpdateUserDataPayloadTextBlock.Text = "";
            JSONTextBlock.Text       = "";
            JSONHeaderTextBlock.Text = "";

            //Reset UI Colors
            UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
            SubmissionStatusTextBlock.Foreground     = new SolidColorBrush(Colors.Black);
            TrainStatusTextBlock.Foreground          = new SolidColorBrush(Colors.Black);
            PersonStatusTextBlock.Foreground         = new SolidColorBrush(Colors.Black);

            //Prep API Call
            await ApiCallAllowed(true);

            faceServiceClient = new FaceServiceClient(authKey);

            //Logic
            if (null != faceServiceClient && null != knownGroup && personName.Length > 0)
            {
                // You may experience issues with this below call, if you are attempting connection with
                // a service location other than 'West US'
                Person[] people = await GetKnownPeople();

                var matchedPeople = people.Where(p => p.Name == personName);

                if (matchedPeople.Count() > 0)
                {
                    knownPerson = matchedPeople.FirstOrDefault();

                    PersonStatusTextBlock.Text = "Found existing: " + knownPerson.Name;

                    try
                    {
                        Attributes attributes = new Attributes();
                        attributes.Data = JsonConvert.DeserializeObject <List <UserData> >(knownPerson.UserData);

                        foreach (var item in attributes.Data)
                        {
                            userDataPayload.Add(new UserData()
                            {
                                UserDataLabel = item.UserDataLabel.ToString(), UserDataValue = item.UserDataValue.ToString()
                            });
                        }
                    }
                    catch
                    {
                        Debug.WriteLine("There was a problem deserializing the User Data");
                    }

                    try
                    {
                        if (knownPerson.UserData == "{}")
                        {
                            //For if the person has had user data in the past but has now been deleted and no longer has user data
                            UpdateUserDataStatusTextBlock.Text  = knownPerson.Name + " does not have user data.";
                            UpdateUserDataPayloadTextBlock.Text = "No User Data List";
                            JSONHeaderTextBlock.Text            = "No user data for " + knownPerson.Name;
                            JSONTextBlock.Text = "To add data to this person, enter one or more Label and a Value pairs in step 4 and select Add To List.\n\rSubmit User Data once all the Label/Value pairs have been added.";
                        }
                        else
                        {
                            UpdateUserDataStatusTextBlock.Text  = "User Data for " + knownPerson.Name + ":";
                            UpdateUserDataPayloadTextBlock.Text = knownPerson.UserData;
                            Chilkat.JsonObject json = new Chilkat.JsonObject();

                            string emittedJson = "";
                            foreach (var j in userDataPayload)
                            {
                                string jsonStr = JsonConvert.SerializeObject(j);

                                bool success = json.Load(jsonStr);
                                if (success != true)
                                {
                                    Debug.WriteLine(json.LastErrorText);
                                    return;
                                }

                                //  To pretty-print, set the EmitCompact property equal to false
                                json.EmitCompact = false;

                                //  If bare-LF line endings are desired, turn off EmitCrLf
                                //  Otherwise CRLF line endings are emitted.
                                json.EmitCrLf = true;

                                //  Emit the formatted JSON:
                                emittedJson = emittedJson + json.Emit();
                            }
                            JSONTextBlock.Text       = emittedJson;
                            JSONHeaderTextBlock.Text = knownPerson.Name + " User Data:";
                        }
                    }
                    catch
                    {
                        //If the person has never had any user data associated with it
                        UpdateUserDataStatusTextBlock.Text = "No User Data";
                        JSONHeaderTextBlock.Text           = "No user data for " + knownPerson.Name;
                        JSONTextBlock.Text = "To add data to this person, enter one or more Label and a Value pairs in step 4 and select Add To List.\n\rSubmit User Data once all the Label/Value pairs have been added.";
                    }
                }

                if (null == knownPerson)
                {
                    PersonStatusTextBlock.Text = "Could not find person: " + personName;
                }

                if (PersonStatusTextBlock.Text.ToLower().Contains("found"))
                {
                    PersonStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);
                }
                else
                {
                    PersonStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                }
            }
        }
Пример #8
0
        public IActionResult Success()
        {
            // Get;
            Chilkat.PublicKey pubKey = new Chilkat.PublicKey();
            bool success             = pubKey.LoadFromFile("qa_data/pem/rsa_public.pem");

            Chilkat.Jwt jwt = new Chilkat.Jwt();

            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

            //  First verify the signature.
            bool sigVerified = jwt.VerifyJwtPk(token, pubKey);

            Console.WriteLine("verified: " + Convert.ToString(sigVerified));

            int  leeway     = 60;
            bool bTimeValid = jwt.IsTimeValid(token, leeway);

            Console.WriteLine("time constraints valid: " + Convert.ToString(bTimeValid));

            //  Now let's recover the original claims JSON (the payload).
            string payload = jwt.GetPayload(token);

            //  The payload will likely be in compact form:
            Console.WriteLine(payload);

            //  We can format for human viewing by loading it into Chilkat's JSON object
            //  and emit.
            Chilkat.JsonObject json = new Chilkat.JsonObject();
            success          = json.Load(payload);
            json.EmitCompact = false;
            Console.WriteLine(json.Emit());

            //  We can recover the original JOSE header in the same way:
            string joseHeader = jwt.GetHeader(token);

            //  The payload will likely be in compact form:
            Console.WriteLine(joseHeader);

            //  We can format for human viewing by loading it into Chilkat's JSON object
            //  and emit.
            success          = json.Load(joseHeader);
            json.EmitCompact = false;
            Console.WriteLine(json.Emit());
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            // JwtDecode Test1=new JwtDecode();
            // var x=Test1.GetName("eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJJU1MiLCJzY29wZSI6Imh0dHBzOi8vbGFyaW0uZG5zY2UuZG91YW5lL2NpZWxzZXJ2aWNlL3dzIiwiYXVkIjoiaHR0cHM6Ly9kb3VhbmUuZmluYW5jZXMuZ291di5mci9vYXV0aDIvdjEiLCJpYXQiOiJcL0RhdGUoMTQ2ODM2MjU5Mzc4NClcLyJ9");
            // // var x= Test1.TestJwtSecurityTokenHandler("CfDJ8JJa5feBk79Hq8LMUg4HHXfoWI4CgZu7vOhujmhfwtEi7rYOFiVzoUBGec1HXm2aOD69Q8AEqARSHvCmyUJAw_opdjsSfIhJS3v-Dbe0MsLw8QvdMMOuNeqEZvB93lH03TM62plyHreR5_D_G7kkvJvg5vaMUOd_GgZMRFkLMlrrcrPM8l2jOVOgD1r4WIEr0oCm9KB_T0Bt5vZ37CnPJJt7r6_yVM5yuAZU3aI92S5EYodHHhVe_OjRDqg1nALC2a2KzHbGnBKfO-7FbyocHU0QRdkl5F5VBRJVsHHNMOZJ3jUhtfflSggP_b5Imk0qNcs39rEUUC8ajLUv3zaFxaCTX6yyj-kqYg2JKYFSw7OXQZl_XiNlB2mY9cdb1xjjpbLM4SxWzB8k1rMMkXETK1ZLFpu9DUiDgoKmTqICaduGdETRjvBsVA4fa2H2ztmNWCEL7huxL41rXjYb4jXSosJ6wLpjFp2j9f1oLymvPVKeeZ_aKaxFHIJF_dUnG-nIuPUtCSAexfp4NLiWaR3ctWvQ4NKeRv-UwaBoSrSt_gSJ3QAqafrmu-vTdwIek6xPb9AWTUAC7TWCgIHgz3pQqJKnPteVWgXXsPSizg2FlcWc5kYTa0PV2kf8g7JYKHPbYPkbjDKUAiYoOG4AkFdV5z6febxVZiC4XQZLM3tZHCBUdTaFHJOwUSOX8aWna-BJBA");
            // // var x= Test1.TestJwtSecurityTokenHandler();
            // System.Console.WriteLine(x);
            // var jwt = "eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw";
            // var handler = new JwtSecurityTokenHandler();
            // var token = handler.ReadJwtToken(jwt);
            // System.Console.WriteLine(token);

            System.Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            // int? y=HttpContext.Session.GetInt32("userid");
            CryptoEngine Encrypter = new CryptoEngine();

            // if (y==null){
            //     return RedirectToAction("Index");
            // }
            // bool Exists=dbContext.users.Any(e=>e.UserId==(int)y);
            // if(Exists==false){
            //     return RedirectToAction("Index");
            // }
            // ViewBag.UserId=(int)y;
            ViewBag.UserId = 5;

            List <Photos> Allphoto = dbContext.photos.ToList();

            foreach (var photo in Allphoto)
            {
                photo.Desc      = Encrypter.Decrypt(photo.Desc);
                photo.PhotoPath = Encrypter.Decrypt(photo.PhotoPath);
            }
            ViewBag.AllPhotos = Allphoto;
            return(View());
        }