public ContainerRegistryRecordedTestBase(bool isAsync, RecordedTestMode?mode = default) : base(isAsync, mode)
        {
            DateTimeOffset expiresOn         = DateTimeOffset.UtcNow + TimeSpan.FromDays(365 * 30); // Never expire in software years
            string         encodedBody       = Base64Url.EncodeString($"{{\"exp\":{expiresOn.ToUnixTimeSeconds()}}}");
            var            jwtSanitizedValue = $"{SanitizeValue}.{encodedBody}.{SanitizeValue}";

            BodyKeySanitizers.Add(new BodyKeySanitizer(jwtSanitizedValue)
            {
                JsonPath = "$..refresh_token"
            });
            BodyRegexSanitizers.Add(new BodyRegexSanitizer(@"access_token=(?<group>.*?)(?=&|$)", SanitizeValue)
            {
                GroupForReplace = "group"
            });
            BodyRegexSanitizers.Add(new BodyRegexSanitizer(@"refresh_token=(?<group>.*?)(?=&|$)", SanitizeValue)
            {
                GroupForReplace = "group"
            });
        }
        void IJsonSerializable.WriteProperties(Utf8JsonWriter json)
        {
            if (Value != null)
            {
                string encoded = Base64Url.Encode(Value);
                json.WriteString(s_valuePropertyNameBytes, encoded);
            }

            if (!string.IsNullOrEmpty(Password))
            {
                json.WriteString(s_passwordPropertyNameBytes, Password);
            }

            if (Policy != null)
            {
                json.WriteStartObject(s_policyPropertyNameBytes);

                ((IJsonSerializable)Policy).WriteProperties(json);

                json.WriteEndObject();
            }

            if (Enabled.HasValue)
            {
                json.WriteStartObject(s_attributesPropertyNameBytes);

                json.WriteBoolean(s_enabledPropertyNameBytes, Enabled.Value);

                json.WriteEndObject();
            }

            if (_tags != null && _tags.Count > 0)
            {
                json.WriteStartObject(s_tagsPropertyNameBytes);

                foreach (KeyValuePair <string, string> kvp in _tags)
                {
                    json.WriteString(kvp.Key, kvp.Value);
                }

                json.WriteEndObject();
            }
        }
Esempio n. 3
0
        public void CheckClaim(JToken token)
        {
            JArray signatures    = (JArray)token;
            string payloadString = Base64Url.Encode(Encoding.UTF8.GetBytes(payload.ToString(Formatting.None)));

            foreach (JToken signature in signatures)
            {
                var protectedPart = signature["protected"];
                var signaturePart = signature["signature"];

                var compactJWS = protectedPart + "." + payloadString + "." + signaturePart;

                var headers = JWT.Headers(compactJWS);

                // Get jwk and it's kid
                var    jwk = JObject.FromObject(headers["jwk"]);
                string kid = jwk["kid"].ToString();

                // compute the actual key's thumbprint
                string computedThumbprint = Base64Url.Encode(Util.Sha256Hash(Encoding.ASCII.GetBytes(
                                                                                 $"{{\"crv\":\"{jwk["crv"]}\",\"kty\":\"{jwk["kty"]}\",\"x\":\"{jwk["x"]}\",\"y\":\"{jwk["y"]}\"}}")));

                // Based on the kid - check that recently computed thumbprint is matching with one of the sent in the claims
                var claimToCheck = kid.Substring(0, kid.Length - "_jwk".Length);
                if (payload[claimToCheck] == null)
                {
                    throw new ValidationException("Missing app signed claim");
                }
                if (payload[claimToCheck].ToString().Equals(computedThumbprint) == false)
                {
                    throw new ValidationException($"Bad signiture {claimToCheck}");
                }
                // - check the signature
                try
                {
                    Util.VerifyTokenSignature(compactJWS, jwk);
                }
                catch (Exception)
                {
                    throw new ValidationException("Invalid signatures");
                }
            }
        }
        public void CanConvertKeyToJwkWithPublicParametersAndDefaultValues()
        {
            var key = JwkNetExtensions.CreateKey();
            var jwt = key.ToJsonWebKey();

            Assert.That(jwt.HasPrivateKey, Is.False);
            Assert.That(jwt.Kid.Length, Is.EqualTo(32));
            var e = Base64Url.Decode(jwt.E);

            Assert.That(e.Length, Is.EqualTo(3)); // Always 65537, which needs 3 bytes (2^16 + 1)
            Assert.That(e[0], Is.EqualTo(1));     // 1 x 2^0 = 1
            Assert.That(e[1], Is.EqualTo(0));     // 0 x 2^8 = 0
            Assert.That(e[2], Is.EqualTo(1));     // 1 x 2^16 = 65536
            var n = Base64Url.Decode(jwt.N);

            Assert.That(n.Length, Is.EqualTo(key.KeySize / 8)); // KeySize is in bits, so / 8 for bytes
            Assert.That(jwt.Kty, Is.EqualTo("RSA"));
            Assert.That(jwt.Alg, Is.EqualTo("RS256"));
        }
Esempio n. 5
0
        public ActionResult AfterRedirectPage(string code)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ViewBag.Message = "Your page is redirected after the authorization.";
            var client = new RestClient("https://zoom.us/oauth/token?grant_type=authorization_code&code=" + code + "&redirect_uri=" + ZoomModel.RedirectUrl);

            client.Timeout = -1;
            var request      = new RestRequest(Method.POST);
            var encodedToken = Base64Url.Encode(ZoomModel.ClientId + ":" + ZoomModel.ClientSecret);

            request.AddHeader("Authorization", "Basic " + encodedToken);
            IRestResponse  response            = client.Execute(request);
            var            objResponseData     = response.Content;
            GetAccessModel myDeserializedClass = JsonConvert.DeserializeObject <GetAccessModel>(response.Content);

            AccessToken.GetAccessTokenValue = myDeserializedClass.access_token;
            Console.WriteLine(response.Content);
            return(View());
        }
Esempio n. 6
0
        public void TestKeyMangling()
        {
            string keyString = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs";

            byte[] keyBytes = Base64Url.Decode(keyString);

            ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey(keyString);

            byte[] outBytes = clientKey.GetDerEncoded();

            string outString = Convert.ToBase64String(outBytes);

            Console.WriteLine(Package.HexDump(keyBytes));
            Console.WriteLine(Package.HexDump(outBytes));

            Assert.AreEqual(keyBytes, outBytes);

            Assert.AreEqual(keyString, outString);
        }
Esempio n. 7
0
        public void A3()
        {
            const string TOKEN = ""
                                 + "eyJhbGciOiJFUzI1NiJ9"
                                 + "."
                                 + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt"
                                 + "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
                                 + "."
                                 + "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSA"
                                 + "pmWQxfKTUJqPP3-Kg6NU1Q";
            const string PAYLOAD = ""
                                   + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt"
                                   + "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
            string json = this.GetResource("RFC7515_A3.json");
            JWK    jwk  = JWK.Parse(json);
            string s    = JWT.Decode(TOKEN, jwk.Key);

            Assert.Equal(Encoding.UTF8.GetString(Base64Url.Decode(PAYLOAD)), s);
        }
Esempio n. 8
0
        public async Task <IActionResult> Login()
        {
            var pkce = new Pkce
            {
                // uses the IdentityModel NuGet package to create a strongly random URL safe identifier
                // this will be our Code Verifier
                CodeVerifier = CryptoRandom.CreateUniqueId(32)
            };

            using (var sha256 = SHA256.Create())
            {
                // Here we create a hash of the code verifier
                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(pkce.CodeVerifier));

                // and produce the "Code Challenge"  from it by base64Url encoding it.
                pkce.CodeChallenge = Base64Url.Encode(challengeBytes);
            }

            // Save the CodeVerifier in the memorycache so we are able to use it later
            // This is just for demonstration. Please consider saving this in a more robust solution.
            _memoryCache.Set(AppConstants.PKCECacheKey, pkce);

            // Build the authorize url
            var authorizeArgs = new Dictionary <string, string>
            {
                { "client_id", _appConfiguration.ClientId },
                { "scope", "read:core:entities read:owneraccounts offline_access" },
                { "redirect_uri", "http://localhost:55183/Auth/LoginCallback" },
                { "response_type", "code" },

                // Provide the Code Challenge along with the method (Sha256)
                { "code_challenge", pkce.CodeChallenge },
                { "code_challenge_method", "S256" }
            };

            var content         = new FormUrlEncodedContent(authorizeArgs);
            var contentAsString = await content.ReadAsStringAsync();

            // prepare the URL for the authorize endpoint
            var url = $"{_appConfiguration.TapkeyAuthorizationServerUrl}/{_appConfiguration.TapkeyAuthorizationEndpointPath}?{contentAsString}";

            return(Redirect(url));
        }
Esempio n. 9
0
        public override bool IsValid(byte[] signedBytes, byte[] signature, Jwk key)
        {
            var(hasher, algorithName) = CreateHasher();

            using (hasher)
            {
                var hash = hasher.ComputeHash(signedBytes);

                using var provider = new RSACryptoServiceProvider();
                provider.ImportParameters(new RSAParameters
                {
                    Modulus  = Base64Url.DeserializeBytes(key.N, "RSA key modulus"),
                    Exponent = Base64Url.DeserializeBytes(key.E, "RSA key exponent")
                });
                var rsaDeformatter = new RSAPKCS1SignatureDeformatter(provider);
                rsaDeformatter.SetHashAlgorithm(algorithName);
                return(rsaDeformatter.VerifySignature(hash, signature));
            }
        }
        public void Encrypt()
        {
            var enc = _encAlgorithms[(Encryptions)_protectedHeader.EncryptionAlgorithm];

            if (enc == null)
            {
                throw new Exception("Unsupported JWE encryption requested");
            }

            var recipients = new JsonRecipientCollection();
            var cek        = Utils.Random(enc.KeySize);
            var iv         = Utils.Random(128);

            foreach (var recipient in _recipients)
            {
                var alg = _keyAlgorithms[(Algorithms)recipient.Header.Algorithm];

                if (alg == null)
                {
                    throw new Exception("Unsupported JWA algorithm requested");
                }

                var encryptedCek = alg.WrapKey(cek, recipient.EncryptionKey);

                recipients.Add(new JsonRecipient
                {
                    Header       = recipient.Header,
                    EncryptedKey = Base64Url.Encode(encryptedCek),
                });
            }

            var encParts = enc.Encrypt(Base64Url.Decode(_message), cek, iv, _aad != null ? Base64Url.Decode(_aad) : new byte[0]);

            _result = new JsonGeneral
            {
                ProtectedHeader             = Base64Url.Encode(JsonConvert.SerializeObject(_protectedHeader)),
                Recipients                  = recipients,
                AdditionalAuthenticatedData = _aad,
                InitializationVector        = Base64Url.Encode(iv),
                CipherText                  = Base64Url.Encode(encParts[0]),
                AuthenticationTag           = Base64Url.Encode(encParts[1]),
            };
        }
Esempio n. 11
0
        public RsaSignatureVerifier(RsaJwk key, SignatureAlgorithm algorithm)
            : base(algorithm)
        {
            Debug.Assert(key != null);
            Debug.Assert(key.SupportSignature(algorithm));

            if (key.KeySizeInBits < 1024)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_SigningKeyTooSmall(key, 1024);
            }

            _hashAlgorithm    = algorithm.HashAlgorithm;
            _sha              = algorithm.Sha;
            _signaturePadding = RsaHelper.GetSignaturePadding(algorithm.Id);

            _hashSizeInBytes       = key.KeySizeInBits >> 3;
            _base64HashSizeInBytes = Base64Url.GetArraySizeRequiredToEncode(_hashSizeInBytes);
            _rsaPool = new ObjectPool <RSA>(new RsaObjectPoolPolicy(key.ExportParameters()));
        }
        public static string GenerateSessionStateValue(this ValidatedAuthorizeRequest request)
        {
            if (!request.IsOpenIdRequest)
            {
                return(null);
            }

            if (request.SessionId.IsMissing())
            {
                return(null);
            }
            if (request.ClientId.IsMissing())
            {
                return(null);
            }
            if (request.RedirectUri.IsMissing())
            {
                return(null);
            }

            var clientId  = request.ClientId;
            var sessionId = request.SessionId;
            var salt      = CryptoRandom.CreateUniqueId(16);

            var uri    = new Uri(request.RedirectUri);
            var origin = uri.Scheme + "://" + uri.Host;

            if (!uri.IsDefaultPort)
            {
                origin += ":" + uri.Port;
            }

            var bytes = Encoding.UTF8.GetBytes(clientId + origin + sessionId + salt);

            byte[] hash;

            using (var sha = SHA256.Create())
            {
                hash = sha.ComputeHash(bytes);
            }

            return(Base64Url.Encode(hash) + "." + salt);
        }
Esempio n. 13
0
        private static async Task <ClaimsPrincipal> ValidateJwt(string jwt)
        {
            // read discovery document to find issuer and key material
            var disco = await DiscoveryClient.GetAsync(Constants.Authority);

            var keys = new List <SecurityKey>();

            foreach (var webKey in disco.KeySet.Keys)
            {
                var e = Base64Url.Decode(webKey.E);
                var n = Base64Url.Decode(webKey.N);

                var key = new RsaSecurityKey(new RSAParameters {
                    Exponent = e, Modulus = n
                })
                {
                    KeyId = webKey.Kid
                };

                keys.Add(key);
            }

            var parameters = new TokenValidationParameters
            {
                ValidIssuer       = disco.Issuer,
                ValidAudience     = "mvc.manual",
                IssuerSigningKeys = keys,

                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,

                RequireSignedTokens = true
            };

            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();

            var user = handler.ValidateToken(jwt, parameters, out var _);

            return(user);
        }
Esempio n. 14
0
        private async Task <TokenResponse> TestAuthCode(ClientConfig clientConfig, HttpClient client, string discoTokenEndpoint, string discoAuthorizeEndpoint)
        {
            var ru = new RequestUrl(discoAuthorizeEndpoint);

            string codeVerifier = CryptoRandom.CreateUniqueId(50);
            string codeChallenge;

            using (var sha256 = SHA256.Create())
            {
                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                codeChallenge = Base64Url.Encode(challengeBytes);
            }

            var url = ru.CreateAuthorizeUrl(
                codeChallenge: codeChallenge,
                codeChallengeMethod: "S256",
                clientId: clientConfig.Id,
                responseType: "code",
                redirectUri: clientConfig.RedirectUris[0],
                scope: string.Join(" ", clientConfig.AllowedScopes));

            OpenUrl(url);
            _logger.LogInformation(url);
            //dopo il login l'utente viene rediretto alla pagina del redirectUri e tra i parametri in querystring c'è il code
            _logger.LogInformation("insert code:");
            var code = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(code))
            {
                code = "code_missing";
            }
            return(await client.RequestAuthorizationCodeTokenAsync(
                       new AuthorizationCodeTokenRequest
            {
                Address = discoTokenEndpoint,
                ClientId = clientConfig.Id,
                ClientSecret = clientConfig.Password,
                RedirectUri = clientConfig.RedirectUris[0],
                Code = code,
                CodeVerifier = codeVerifier
            }));
        }
        public static void Show(this TokenResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            if (!response.IsError)
            {
                ConsoleHelper.WriteGreenLine("Token response:");
                ConsoleHelper.WriteLine(response.Json);

                // ReSharper disable InvertIf
                if (response.AccessToken.Contains("."))
                {
                    ConsoleHelper.WriteGreenLine("Access Token (decoded):");

                    var parts  = response.AccessToken.Split('.');
                    var header = parts[0];
                    var claims = parts[1];

                    ConsoleHelper.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(header))));
                    ConsoleHelper.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims))));
                }
                // ReSharper restore InvertIf
            }
            else
            {
                if (response.ErrorType == ResponseErrorType.Http)
                {
                    ConsoleHelper.WriteGreenLine("HTTP error:");
                    ConsoleHelper.WriteLine(response.Error);
                    ConsoleHelper.WriteGreenLine("HTTP status code:");
                    ConsoleHelper.WriteLine(response.HttpStatusCode);
                }
                else
                {
                    ConsoleHelper.WriteGreenLine("Protocol error response:");
                    ConsoleHelper.WriteLine(response.Raw);
                }
            }
        }
        public void InvalidCurveAttack()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "This requires CNG, which is Windows Only.");

            // https://www.cs.bris.ac.uk/Research/CryptographySecurity/RWC/2017/nguyen.quan.pdf
            // Attack exploits some ECDH implementations which do not check
            // that ephemeral public key is on the private key's curve.

            byte[] x = Base64Url.Decode("weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ");
            byte[] y = Base64Url.Decode("e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck");
            byte[] d = Base64Url.Decode("VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw");

            var privateKey = EccKey.New(x, y, d, usage: CngKeyUsages.KeyAgreement);

            //JWT encrypted with attacker private key, which is equals to (reciever_pk mod 113)
            var attackMod113 =
                "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZ1RsaTY1ZVRRN3otQmgxNDdmZjhLM203azJVaURpRzJMcFlrV0FhRkpDYyIsInkiOiJjTEFuakthNGJ6akQ3REpWUHdhOUVQclJ6TUc3ck9OZ3NpVUQta2YzMEZzIiwiY3J2IjoiUC0yNTYifX0.qGAdxtEnrV_3zbIxU2ZKrMWcejNltjA_dtefBFnRh9A2z9cNIqYRWg.pEA5kX304PMCOmFSKX_cEg.a9fwUrx2JXi1OnWEMOmZhXd94-bEGCH9xxRwqcGuG2AMo-AwHoljdsH5C_kcTqlXS5p51OB1tvgQcMwB5rpTxg.72CHiYFecyDvuUa43KKT6w";

            //JWT encrypted with attacker private key, which is equals to (reciever_pk mod 2447)
            var attackMod2447 =
                "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiWE9YR1E5XzZRQ3ZCZzN1OHZDSS1VZEJ2SUNBRWNOTkJyZnFkN3RHN29RNCIsInkiOiJoUW9XTm90bk56S2x3aUNuZUprTElxRG5UTnc3SXNkQkM1M1ZVcVZqVkpjIiwiY3J2IjoiUC0yNTYifX0.UGb3hX3ePAvtFB9TCdWsNkFTv9QWxSr3MpYNiSBdW630uRXRBT3sxw.6VpU84oMob16DxOR98YTRw.y1UslvtkoWdl9HpugfP0rSAkTw1xhm_LbK1iRXzGdpYqNwIG5VU33UBpKAtKFBoA1Kk_sYtfnHYAvn-aes4FTg.UZPN8h7FcvA5MIOq-Pkj8A";

            try
            {
                JWT.Decode(attackMod113, privateKey);
                Assert.True(false, "Should fail with CrytographicException");
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e);
            }

            try
            {
                JWT.Decode(attackMod2447, privateKey);
                Assert.True(false, "Should fail with CrytographicException");
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e);
            }
        }
        private async Task <IEndpointResult> ExecuteJwksAsync(HttpContext context)
        {
            _logger.LogTrace("Start key discovery request");

            if (_options.DiscoveryOptions.ShowKeySet == false)
            {
                _logger.LogInformation("Key discovery disabled. 404.");
                return(new StatusCodeResult(404));
            }

            var webKeys = new List <JsonWebKey>();

            foreach (var pubKey in await _keyService.GetValidationKeysAsync())
            {
                if (pubKey != null)
                {
                    var cert64     = Convert.ToBase64String(pubKey.RawData);
                    var thumbprint = Base64Url.Encode(pubKey.GetCertHash());

                    // todo
                    //var key = pubKey.PublicKey.Key as RSACryptoServiceProvider;
                    //var parameters = key.ExportParameters(false);
                    //var exponent = Base64Url.Encode(parameters.Exponent);
                    //var modulus = Base64Url.Encode(parameters.Modulus);

                    var webKey = new JsonWebKey
                    {
                        kty = "RSA",
                        use = "sig",
                        kid = await _keyService.GetKidAsync(pubKey),
                        x5t = thumbprint,
                        //e = exponent,
                        //n = modulus,
                        x5c = new[] { cert64 }
                    };

                    webKeys.Add(webKey);
                }
            }

            return(new JsonWebKeysResult(webKeys));
        }
Esempio n. 18
0
        public JsonResult MakeCredentialOptionsTest([FromBody] TEST_MakeCredentialParams opts)
        {
            var attType = opts.Attestation;

            var username = new byte[] { };

            try
            {
                username = Base64Url.Decode(opts.Username);
            }
            catch (FormatException)
            {
                username = System.Text.Encoding.UTF8.GetBytes(opts.Username);
            }

            // 1. Get user from DB by username (in our example, auto create missing users)
            var user = DemoStorage.GetOrAddUser(opts.Username, () => new User
            {
                DisplayName = opts.DisplayName,
                Name        = opts.Username,
                Id          = username // byte representation of userID is required
            });

            // 2. Get user existing keys by username
            var existingKeys = DemoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();

            var exts = new AuthenticationExtensionsClientInputs()
            {
                Extensions = true, UserVerificationIndex = true, Location = true, UserVerificationMethod = true, BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds {
                    FAR = float.MaxValue, FRR = float.MaxValue
                }
            };

            // 3. Create options
            var options = _lib.RequestNewCredential(user, existingKeys, opts.AuthenticatorSelection, opts.Attestation, exts);

            // 4. Temporarily store options, session/in-memory cache/redis/db
            HttpContext.Session.SetString("fido2.attestationOptions", options.ToJson());

            // 5. return options to client
            return(Json(options));
        }
Esempio n. 19
0
        private async void Authorize_Click(object sender, RoutedEventArgs e)
        {
            var state = CryptoRandom.CreateRandomKeyString(25);

            CodeVerifier = CryptoRandom.CreateRandomKeyString(50);

            var codeVerifierBytes = Encoding.ASCII.GetBytes(CodeVerifier);
            var hashedBytes       = SHA256.Create().ComputeHash(codeVerifierBytes);
            var codeChallenge     = Base64Url.Encode(hashedBytes);



            var url = "http://localhost:5000/connect/authorize" +
                      "?client_id=native_client" +
                      "&scope=wiredbrain_api.rewards" +
                      "&redirect_uri=com.pluralsight.windows:/callback" +
                      "&response_type=code" +
                      $"&state={WebUtility.UrlEncode(state)}" +
                      $"&code_challenge={WebUtility.UrlEncode(codeChallenge)}" +
                      "&code_challenge_method=S256";

            ResultFeed.Text += "\nStarting Authorization";
            ResultFeed.Text += $"\nState = {state}";
            ResultFeed.Text += $"\nCode Verifier = {CodeVerifier}";
            ResultFeed.Text += $"\nCode Challange = {codeChallenge}";

            var result = await new SystemBrowser().InvokeAsync(url);

            ResultFeed.Text += "\n\nAuthorization callback received...";

            if (result.State != state)
            {
                ResultFeed.Text += "\nState not recognised. Cannot trust response.";
                return;
            }

            Code = result.Code;

            ResultFeed.Text += "\nApplication Authorized!";
            ResultFeed.Text += $"\nAuthorization Code: {result.Code}";
            ResultFeed.Text += $"\nState: {result.State}";
        }
        public virtual byte[] Unwrap(byte[] encryptedCek, object privateKey, int cekSizeBits, IDictionary <string, object> header)
        {
            Ensure.Contains(header, new[] { "epk" }, "EcdhKeyManagement algorithm expects 'epk' key param in JWT header, but was not found");
            Ensure.Contains(header, new[] { BCRYPT_ALG_ID_HEADER },
                            "EcdhKeyManagement algorithm expects 'enc' header to be present in JWT header, but was not found");

            var epk = (IDictionary <string, object>)header["epk"];

            Ensure.Contains(epk, new[] { "x", "y", "crv" },
                            "EcdhKeyManagement algorithm expects 'epk' key to contain 'x','y' and 'crv' fields.");

            var x = new BigInteger(Base64Url.Decode(epk["x"].ToString()));
            var y = new BigInteger(Base64Url.Decode(epk["y"].ToString()));
            var externalPubKeyPoint = _brainpoolP256R1.Curve.CreatePoint(x, y);

            var domainParams   = new ECDomainParameters(_brainpoolP256R1.Curve, _brainpoolP256R1.G, _brainpoolP256R1.N, _brainpoolP256R1.H);
            var externalPubKey = new ECPublicKeyParameters(externalPubKeyPoint, domainParams);

            return(DeriveKey(header, cekSizeBits, externalPubKey, privateKey as ECPrivateKeyParameters));
        }
Esempio n. 21
0
        public EcdsaSigner(ECJwk key, SignatureAlgorithm algorithm)
            : base(algorithm)
        {
            if (key is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }

            if (key.KeySizeInBits < 256)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_SigningKeyTooSmall(key, 256);
            }

            _canOnlyVerify  = !key.HasPrivateKey;
            _hashAlgorithm  = algorithm.HashAlgorithm;
            _hashSize       = key.Crv.HashSize;
            _base64HashSize = Base64Url.GetArraySizeRequiredToEncode(_hashSize);

            _ecdsaPool = new ObjectPool <ECDsa>(new ECDsaObjectPoolPolicy(key, algorithm));
        }
Esempio n. 22
0
        public void Encode()
        {
            Action TestCase(int testNumber, byte[] bytes, bool padding, string expected, Type expectedExceptionType = null) => () => {
                new TestCaseRunner($"No.{testNumber}")
                .Run(() => Base64Url.Encode(bytes, padding))
                .Verify(expected, expectedExceptionType);
            };

            new[] {
                TestCase(0, null, false, null, typeof(ArgumentNullException)),
                TestCase(10, Bin(), false, ""),
                TestCase(11, Bin(0), false, "AA"),
                TestCase(12, Bin(250), false, "-g"),
                TestCase(13, Bin(255, 0), false, "_wA"),
                TestCase(20, Bin(), true, ""),
                TestCase(21, Bin(0), true, "AA=="),
                TestCase(22, Bin(250), true, "-g=="),
                TestCase(23, Bin(255, 0), true, "_wA="),
            }.Run();
        }
Esempio n. 23
0
        public void ValidateEncodeDecodeStringRandom()
        {
            var seed = new Random().Next();

            var rand = new Random(seed);

            for (int i = 1; i <= 512; i++)
            {
                for (int j = 0; j < 32; j++)
                {
                    var data = GenerateRandomString(rand, i);

                    var encoded = Base64Url.EncodeString(data);

                    var decoded = Base64Url.DecodeString(encoded);

                    Assert.AreEqual(data, decoded, "String round trip failed. Seed {0}", seed);
                }
            }
        }
Esempio n. 24
0
        public byte[] Unwrap([ReadOnlyArray] byte[] encryptedCek, object key, uint cekSizeBits, JsonObject header)
        {
            var sharedPassphrase = Ensure.Type <string>(key, "Pbse2HmacShaWithAesKWKeyManagement management algorithm expectes key to be string.");

            byte[] sharedKey = Encoding.UTF8.GetBytes(sharedPassphrase);

            Ensure.Contains(header, "p2c", "Pbse2HmacShaWithAesKWKeyManagement algorithm expects 'p2c' param in JWT header, but was not found");
            Ensure.Contains(header, "p2s", "Pbse2HmacShaWithAesKWKeyManagement algorithm expects 'p2s' param in JWT header, but was not found");

            byte[] algId          = Encoding.UTF8.GetBytes(header["alg"].GetString());
            int    iterationCount = (int)header["p2c"].GetNumber();

            byte[] saltInput = Base64Url.Decode(header["p2s"].GetString());

            byte[] salt = Arrays.Concat(algId, Arrays.Zero, saltInput);

            byte[] kek = PBKDF2.DeriveKey(sharedKey, salt, iterationCount, keySizeBits, Prf);

            return(aesKW.Unwrap(encryptedCek, kek, cekSizeBits, header));
        }
Esempio n. 25
0
        public Part[] WrapNewKey(uint cekSizeBits, object key, JsonObject header)
        {
            var sharedPassphrase = Ensure.Type <string>(key, "Pbse2HmacShaWithAesKWKeyManagement management algorithm expectes key to be string.");

            byte[] sharedKey = Encoding.UTF8.GetBytes(sharedPassphrase);
            byte[] algId     = Encoding.UTF8.GetBytes(header["alg"].GetString());

            const int iterationCount = 8192;

            var saltInput = Buffer.ToBytes(CryptographicBuffer.GenerateRandom(12));

            header["p2c"] = JsonValue.CreateNumberValue(iterationCount);
            header["p2s"] = JsonValue.CreateStringValue(Base64Url.Encode(saltInput));

            byte[] salt = Arrays.Concat(algId, Arrays.Zero, saltInput);

            byte[] kek = PBKDF2.DeriveKey(sharedKey, salt, iterationCount, keySizeBits, Prf);

            return(aesKW.WrapNewKey(cekSizeBits, kek, header));
        }
        void IJsonSerializable.WriteProperties(Utf8JsonWriter json)
        {
            json.WriteString("alg", Algorithm.ToString());
            json.WriteString("value", Base64Url.Encode(Ciphertext));

            if (Iv != null)
            {
                json.WriteString("iv", Base64Url.Encode(Iv));
            }

            if (AuthenticationTag != null)
            {
                json.WriteString("tag", Base64Url.Encode(AuthenticationTag));
            }

            if (AdditionalAuthenticatedData != null)
            {
                json.WriteString("aad", Base64Url.Encode(AdditionalAuthenticatedData));
            }
        }
Esempio n. 27
0
        public void TestGenerateSecret()
        {
            string keyString = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs";

            byte[] keyBytes = Base64Url.Decode(keyString);

            ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey(keyString);

            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(384);

            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            ecKey.SecretPrepend         = new byte[128];     // Server token
            //ecKey.SecretPrepend = new byte[0]; // Server token

            Console.WriteLine(ecKey.HashAlgorithm);
            Console.WriteLine(ecKey.KeyExchangeAlgorithm);

            byte[] secret = ecKey.DeriveKeyMaterial(clientKey);
        }
Esempio n. 28
0
        public static IdentityModel.Jwk.JsonWebKeySet CreateKeySet(RsaSecurityKey key)
        {
            var parameters = key.Rsa?.ExportParameters(false) ?? key.Parameters;
            var exponent   = Base64Url.Encode(parameters.Exponent);
            var modulus    = Base64Url.Encode(parameters.Modulus);

            var webKey = new IdentityModel.Jwk.JsonWebKey
            {
                Kty = "RSA",
                Use = "sig",
                Kid = key.KeyId,
                E   = exponent,
                N   = modulus,
            };

            var set = new IdentityModel.Jwk.JsonWebKeySet();

            set.Keys.Add(webKey);
            return(set);
        }
Esempio n. 29
0
        public void FromJson(string json)
        {
            // https://tools.ietf.org/html/rfc7517#appendix-C.1
            var key = Jwk.FromJson(json);

            Assert.NotNull(key);
            var jwk = Assert.IsType <RsaJwk>(key);

            Assert.Equal("*****@*****.**", jwk.Kid.ToString());
            Assert.True(JwkUseValues.Enc.Equals(jwk.Use));

            Assert.Equal(jwk.N.ToArray(), Base64Url.Decode("t6Q8PWSi1dkJj9hTP8hNYFlvadM7DflW9mWepOJhJ66w7nyoK1gPNqFMSQRyO125Gp-TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR0-Iqom-QFcNP8Sjg086MwoqQU_LYywlAGZ21WSdS_PERyGFiNnj3QQlO8Yns5jCtLCRwLHL0Pb1fEv45AuRIuUfVcPySBWYnDyGxvjYGDSM-AqWS9zIQ2ZilgT-GqUmipg0XOC0Cc20rgLe2ymLHjpHciCKVAbY5-L32-lSeZO-Os6U15_aXrk9Gw8cPUaX1_I8sLGuSiVdt3C_Fn2PZ3Z8i744FPFGGcG1qs2Wz-Q"));
            Assert.Equal(jwk.E.ToArray(), Base64Url.Decode("AQAB"));
            Assert.Equal(jwk.D.ToArray(), Base64Url.Decode("GRtbIQmhOZtyszfgKdg4u_N-R_mZGU_9k7JQ_jn1DnfTuMdSNprTeaSTyWfSNkuaAwnOEbIQVy1IQbWVV25NY3ybc_IhUJtfri7bAXYEReWaCl3hdlPKXy9UvqPYGR0kIXTQRqns-dVJ7jahlI7LyckrpTmrM8dWBo4_PMaenNnPiQgO0xnuToxutRZJfJvG4Ox4ka3GORQd9CsCZ2vsUDmsXOfUENOyMqADC6p1M3h33tsurY15k9qMSpG9OX_IJAXmxzAh_tWiZOwk2K4yxH9tS3Lq1yX8C1EWmeRDkK2ahecG85-oLKQt5VEpWHKmjOi_gJSdSgqcN96X52esAQ"));
            Assert.Equal(jwk.P.ToArray(), Base64Url.Decode("2rnSOV4hKSN8sS4CgcQHFbs08XboFDqKum3sc4h3GRxrTmQdl1ZK9uw-PIHfQP0FkxXVrx-WE-ZEbrqivH_2iCLUS7wAl6XvARt1KkIaUxPPSYB9yk31s0Q8UK96E3_OrADAYtAJs-M3JxCLfNgqh56HDnETTQhH3rCT5T3yJws"));
            Assert.Equal(jwk.Q.ToArray(), Base64Url.Decode("1u_RiFDP7LBYh3N4GXLT9OpSKYP0uQZyiaZwBtOCBNJgQxaj10RWjsZu0c6Iedis4S7B_coSKB0Kj9PaPaBzg-IySRvvcQuPamQu66riMhjVtG6TlV8CLCYKrYl52ziqK0E_ym2QnkwsUX7eYTB7LbAHRK9GqocDE5B0f808I4s"));
            Assert.Equal(jwk.DP.ToArray(), Base64Url.Decode("KkMTWqBUefVwZ2_Dbj1pPQqyHSHjj90L5x_MOzqYAJMcLMZtbUtwKqvVDq3tbEo3ZIcohbDtt6SbfmWzggabpQxNxuBpoOOf_a_HgMXK_lhqigI4y_kqS1wY52IwjUn5rgRrJ-yYo1h41KR-vz2pYhEAeYrhttWtxVqLCRViD6c"));
            Assert.Equal(jwk.DQ.ToArray(), Base64Url.Decode("AvfS0-gRxvn0bwJoMSnFxYcK1WnuEjQFluMGfwGitQBWtfZ1Er7t1xDkbN9GQTB9yqpDoYaN06H7CFtrkxhJIBQaj6nkF5KKS3TQtQ5qCzkOkmxIe3KRbBymXxkb5qwUpX5ELD5xFc6FeiafWYY63TmmEAu_lRFCOJ3xDea-ots"));
            Assert.Equal(jwk.QI.ToArray(), Base64Url.Decode("lSQi-w9CpyUReMErP1RsBLk7wNtOvs5EQpPqmuMvqW57NBUczScEoPwmUqqabu9V0-Py4dQ57_bapoKRu1R90bvuFnU63SHWEFglZQvJDMeAvmj4sm-Fp0oYu_neotgQ0hzbI5gry7ajdYy9-2lNx_76aBZoOUu9HCJ-UsfSOI8"));
        }
Esempio n. 30
0
        internal static JwtPayload DecodeJwtPayload(string token)
        {
            const string TokenNotFormattedCorrectly = "Token is not formatted correctly.";

            var tokenParts = token.Split('.');

            if (tokenParts.Length < 2)
            {
                throw new FormatException(TokenNotFormattedCorrectly);
            }

            try
            {
                return(JsonSerializer.Deserialize <JwtPayload>(Base64Url.DecodeString(tokenParts[1])));
            }
            catch (JsonException ex)
            {
                throw new FormatException(TokenNotFormattedCorrectly, ex);
            }
        }