Пример #1
0
        public static void CreateCardholder()
        {
            Chilkat.Rest rest = new Chilkat.Rest();
            bool         success;
            //  URL: https://api.stripe.com/v1/balance
            bool bTls           = true;
            int  port           = 443;
            bool bAutoReconnect = true;

            success = rest.Connect("api.stripe.com", port, bTls, bAutoReconnect);
            if (success != true)
            {
                Log("ConnectFailReason: " + Convert.ToString(rest.ConnectFailReason));
                Log(rest.LastErrorText);
                return;
            }
            //rest.SetAuthBasic(stripe_testnet, "");
            rest.AddQueryParam("type", "individual");
            rest.AddQueryParam("name", "John Doe");
            rest.AddQueryParam("billing[address][line1]", "1008 Their Address St.");
            rest.AddQueryParam("billing[address][city]", "City");
            rest.AddQueryParam("billing[address][state]", "St");
            rest.AddQueryParam("billing[address][country]", "US");
            rest.AddQueryParam("billing[address][postal_code]", "Zip");
            string strResponseBody = rest.FullRequestFormUrlEncoded("POST", "/v1/issuing/cardholders");

            if (rest.LastMethodSuccess != true)
            {
                Log(rest.LastErrorText);
                return;
            }

            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            jsonResponse.Load(strResponseBody);
        }
Пример #2
0
        public async Task <IActionResult> OnPost()
        {
            IRestClient   client   = new RestClient("http://api.nbp.pl/api");
            IRestRequest  request  = new RestRequest("exchangerates/tables/A?format=json", Method.GET);
            IRestResponse response = client.Get(request);

            Chilkat.JsonObject json = new Chilkat.JsonObject();
            json.Load(response.Content);
            Chilkat.JsonArray jCurrencies = json.ArrayOf("rates");
            int numCurrencies             = jCurrencies.Size;

            for (int i = 0; i < numCurrencies; i++)
            {
                Chilkat.JsonObject empObj = jCurrencies.ObjectAt(i);
                string             tName  = empObj.StringOf("currency");
                string             tCode  = empObj.StringOf("code");
                string             tMid   = empObj.StringOf("mid");
                tMid = tMid.Replace('.', ',');
                decimal  Mid      = Convert.ToDecimal(tMid);
                Currency currency = new Currency(tName, tCode, Mid, DateTime.Now);
                await _db.Currency.AddAsync(currency);

                await _db.SaveChangesAsync();
            }
            return(RedirectToPage("CurrencyList"));
        }
Пример #3
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);
        }
Пример #4
0
        public static string Lithic_GetCardEmbedCode(bool fTestnet, string sCardGuid)
        {
            Chilkat.Rest rest = ConnectToLithic(fTestnet);
            embedRequest e    = new embedRequest();

            e.embed_request = sCardGuid;
            string          lithic_testnet = GetBMSConfigurationKeyValue("lithic_testnet");
            string          lithic_prod    = GetBMSConfigurationKeyValue("lithic_prod");
            string          myKey          = fTestnet ? lithic_testnet : lithic_prod;
            embedSubRequest esr            = new embedSubRequest();

            esr.token = sCardGuid;
            esr.css   = "";
            string embedRequestJson = JsonConvert.SerializeObject(esr);

            e.hmac = GetHMAC(embedRequestJson, myKey);
            string json      = JsonConvert.SerializeObject(e, Formatting.Indented);
            string sResponse = rest.FullRequestString("POST", "/v1/embed/card", json);

            if (rest.LastMethodSuccess != true)
            {
                Log(rest.LastErrorText);
                return("");
            }
            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            jsonResponse.Load(sResponse);
            return("?");
        }
Пример #5
0
        public static void ListAllCardholders()
        {
            Chilkat.Rest rest = new Chilkat.Rest();
            bool         success;
            //  URL: https://api.stripe.com/v1/balance
            bool bTls           = true;
            int  port           = 443;
            bool bAutoReconnect = true;

            success = rest.Connect("api.stripe.com", port, bTls, bAutoReconnect);
            if (success != true)
            {
                Log("ConnectFailReason: " + Convert.ToString(rest.ConnectFailReason));
                Log(rest.LastErrorText);
                return;
            }
            Chilkat.StringBuilder sbResponseBody = new Chilkat.StringBuilder();
            success = rest.FullRequestNoBodySb("GET", "/v1/issuing/cardholders", sbResponseBody);
            if (success != true)
            {
                Log(rest.LastErrorText);
                return;
            }
            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            jsonResponse.LoadSb(sbResponseBody);
            var o        = jsonResponse.StringOf("object");
            var livemode = jsonResponse.BoolOf("livemode");
        }
Пример #6
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);
        }
Пример #7
0
        private string getSavedAccessToken()
        {
            if (m_googleAccessJson == null)
            {
                return("");
            }

            Chilkat.JsonObject json = new Chilkat.JsonObject();
            json.Load(m_googleAccessJson);
            return(json.StringOf("access_token"));
        }
Пример #8
0
        public static string ListCards1(bool fTestnet)
        {
            Chilkat.Rest rest = ConnectToLithic(fTestnet);
            string       s    = rest.FullRequestString("GET", "/v1/card", "");

            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            dynamic            oJson        = JsonConvert.DeserializeObject <dynamic>(s);

            foreach (var card in oJson["data"])
            {
                string token = card["token"].Value;
                return(token);
            }
            return("");
        }
Пример #9
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();
        }
Пример #10
0
        public static void SimulateAuth_Lithic(bool fTestnet)
        {
            Chilkat.Rest rest = ConnectToLithic(fTestnet);
            panObject    p    = new panObject();

            p.amount     = 500;
            p.descriptor = "AMAZON.COM";
            string json      = JsonConvert.SerializeObject(p, Formatting.Indented);
            string sResponse = rest.FullRequestString("POST", "/v1/simulate/authorize", json);

            if (rest.LastMethodSuccess != true)
            {
                Log(rest.LastErrorText);
                return;
            }
            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            jsonResponse.Load(sResponse);
        }
Пример #11
0
        public static void CreateCard_Lithic(bool fTestnet)
        {
            Chilkat.Rest     rest = ConnectToLithic(fTestnet);
            cardobjectlithic c    = new cardobjectlithic();

            c.memo                 = "Memo1";
            c.spend_limit          = 200 * 100;
            c.spend_limit_duration = "TRANSACTION";

            c.type = "MERCHANT_LOCKED";
            string json      = JsonConvert.SerializeObject(c, Formatting.Indented);
            string sResponse = rest.FullRequestString("POST", "/v1/card", json);

            if (rest.LastMethodSuccess != true)
            {
                Log(rest.LastErrorText);
                return;
            }
            Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
            jsonResponse.Load(sResponse);
            string mytest = "";
        }
Пример #12
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);
        }
Пример #13
0
        private void googleDriveListFiles()
        {
            bool success = true;

            Chilkat.AuthGoogle gAuth = new Chilkat.AuthGoogle();
            //  This is our previously obtained access token...
            gAuth.AccessToken = getSavedAccessToken();
            if (gAuth.AccessToken.Length == 0)
            {
                popupError("No previously obtained access token is available.");
                return;
            }

            Chilkat.Rest rest = new Chilkat.Rest();

            //  Connect using TLS.
            bool bAutoReconnect = true;

            success = rest.Connect("www.googleapis.com", 443, true, bAutoReconnect);

            //  Provide the authentication credentials (i.e. the access key)
            rest.SetAuthGoogle(gAuth);

            //  Add a search query parameter to only return files having names matching our criteria
            //  See https://developers.google.com/drive/v3/web/search-parameters
            // ignore = rest.AddQueryParam("q","name contains 'starfish'");
            // ignore = rest.AddQueryParam("maxResults","2");

            //  We are using the Google Drive V3 API... (not V2)
            string jsonResponse = rest.FullRequestNoBody("GET", "/drive/v3/files");

            if (rest.LastMethodSuccess != true)
            {
                fgAppendToErrorLog(rest.LastErrorText);
                popupError("REST request failed.");
                return;
            }

            // A successful JSON response looks like this:
            //{
            //  "kind": "drive#fileList",
            //  "files": [
            //    {
            //      "kind": "drive#file",
            //      "id": "0B53Q6OSTWYolenpjTEU4ekJlQUU",
            //      "name": "test",
            //      "mimeType": "application/vnd.google-apps.folder"
            //    },
            //    {
            //      "kind": "drive#file",
            //      "id": "0B53Q6OSTWYolRm4ycjZtdXhRaEE",
            //      "name": "starfish4.jpg",
            //      "mimeType": "image/jpeg"
            //    },
            //    {
            //      "kind": "drive#file",
            //      "id": "0B53Q6OSTWYolMWt2VzN0Qlo1UjA",
            //      "name": "hamlet2.xml",
            //      "mimeType": "text/xml"
            //    },
            // ...
            //    {
            //      "kind": "drive#file",
            //      "id": "0B53Q6OSTWYolc3RhcnRlcl9maWxlX2Rhc2hlclYw",
            //      "name": "Getting started",
            //      "mimeType": "application/pdf"
            //    }
            //  ]
            //}

            // Iterate over the files and show the name and mimeType of each.
            Chilkat.JsonObject json = new Chilkat.JsonObject();
            json.Load(jsonResponse);
            int numFiles = json.SizeOfArray("files");
            int i        = 0;

            while (i < numFiles)
            {
                json.I = i;
                fgAppendToErrorLog("name: " + json.StringOf("files[i].name") + "\r\n");
                fgAppendToErrorLog("mimeType: " + json.StringOf("files[i].mimeType") + "\r\n");
                i++;
            }
        }
Пример #14
0
        // (for Google authorization)
        // Exchange the code for an access token and refresh token.

        // REMEMBER -- this code is running in a background thread because it is called
        // from listenSocket_OnTaskCompleted.
        private bool googleExchangeCodeForToken(string code, string taskUserData)
        {
            // The taskUserData contains JSON information.
            Chilkat.JsonObject taskData = new Chilkat.JsonObject();
            taskData.Load(taskUserData);
            string redirect_uri  = taskData.StringOf("redirect_uri");
            string code_verifier = taskData.StringOf("code_verifier");

            Chilkat.Rest rest = new Chilkat.Rest();

            bool bTls           = true;
            int  port           = 443;
            bool bAutoReconnect = true;
            bool success        = rest.Connect("www.googleapis.com", port, bTls, bAutoReconnect);

            if (success != true)
            {
                fgAppendToErrorLog(rest.LastErrorText);
                return(false);
            }

            success = rest.AddQueryParam("code", code);
            success = rest.AddQueryParam("client_id", googleAppClientId);
            success = rest.AddQueryParam("client_secret", googleAppClientSecret);
            success = rest.AddQueryParam("redirect_uri", redirect_uri);
            success = rest.AddQueryParam("code_verifier", code_verifier);
            success = rest.AddQueryParam("scope", "");
            success = rest.AddQueryParam("grant_type", "authorization_code");

            rest.VerboseLogging = true;
            string responseJson = rest.FullRequestFormUrlEncoded("POST", "/oauth2/v4/token");

            if (rest.LastMethodSuccess != true)
            {
                fgAppendToErrorLog(rest.LastErrorText);
                return(false);
            }

            //  When successful, the response status code will equal 200.
            if (rest.ResponseStatusCode != 200)
            {
                //  Examine the request/response to see what happened.
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("LastErrorText: " + rest.LastErrorText);
                sb.AppendLine("response status code = " + Convert.ToString(rest.ResponseStatusCode));
                sb.AppendLine("response status text = " + rest.ResponseStatusText);
                sb.AppendLine("response header: " + rest.ResponseHeader);
                sb.AppendLine("response body (if any): " + responseJson);
                sb.AppendLine("---");
                sb.AppendLine("LastRequestStartLine: " + rest.LastRequestStartLine);
                sb.AppendLine("LastRequestHeader: " + rest.LastRequestHeader);
                fgAppendToErrorLog(sb.ToString());
                return(false);
            }

            // A successful response JSON will look like this:
            //{
            // "access_token": "ya29.Ci9ZA-Z0Q7vtnch8xxxxxxxxxxxxxxgDVOOV97-IBvTt958xxxxxx1sasw",
            // "token_type": "Bearer",
            // "expires_in": 3600,
            // "refresh_token": "1/fYjEVR-3Oq9xxxxxxxxxxxxxxLzPtlNOeQ"
            //}
            m_googleAccessJson = responseJson;

            fgAppendToErrorLog(responseJson);

            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);
        }
Пример #16
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;
            }
        }
Пример #17
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);
                }
            }
        }
Пример #18
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());
        }