private RsaJsonWebKeyPair(string privateKeyXml, DateTime?createdTime = null)
        {
            CreatedTime = createdTime ?? DateTime.Now;

            _privateKeyXml = privateKeyXml;

            var rsaPrivateKey = RSA.Create();

            rsaPrivateKey.FromXmlString(privateKeyXml);

            var rsaPublicKey = RSA.Create();

            rsaPublicKey.FromXmlString(rsaPrivateKey.ToXmlString(false));

            var privateRsaSecurityKey = new RsaSecurityKey(rsaPrivateKey);

            PrivateKey = JsonWebKeyConverter.ConvertFromRSASecurityKey(privateRsaSecurityKey);
            PublicKey  = JsonWebKeyConverter.ConvertFromRSASecurityKey(new RsaSecurityKey(rsaPublicKey));

            SigningCredentials = new SigningCredentials(privateRsaSecurityKey, SecurityAlgorithms.RsaSha256Signature);
            SecurityKeyInfo    = new SecurityKeyInfo
            {
                Key = privateRsaSecurityKey,
                SigningAlgorithm = PrivateKey.Alg
            };
        }
Esempio n. 2
0
        /// <summary>
        /// 產生jwk檔
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddCustomCredential(
            this IIdentityServerBuilder builder)
        {
            bool   persistKey = true;
            string filename   = "Credential.jwk";

            IdentityServerConstants.RsaSigningAlgorithm signingAlgorithm = IdentityServerConstants.RsaSigningAlgorithm.RS256;
            if (File.Exists(filename))
            {
                var json = File.ReadAllText(filename);
                var jwk  = new JsonWebKey(json);

                return(builder.AddSigningCredential(jwk, jwk.Alg));
            }
            else
            {
                var key = CryptoHelper.CreateRsaSecurityKey();
                var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
                jwk.Alg = signingAlgorithm.ToString();

                if (persistKey)
                {
                    File.WriteAllText(filename, System.Text.Json.JsonSerializer.Serialize(jwk));
                }
                return(builder.AddSigningCredential(key, signingAlgorithm));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Sets the temporary signing credential.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="persistKey">Specifies if the temporary key should be persisted to disk.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="signingAlgorithm">The signing algorithm (defaults to RS256)</param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddDeveloperSigningCredential(
            this IIdentityServerBuilder builder,
            bool persistKey = true,
            string filename = null,
            IdentityServerConstants.RsaSigningAlgorithm signingAlgorithm = IdentityServerConstants.RsaSigningAlgorithm.RS256)
        {
            if (filename == null)
            {
                filename = Path.Combine(Directory.GetCurrentDirectory(), "tempkey.jwk");
            }

            if (File.Exists(filename))
            {
                var json = File.ReadAllText(filename);
                var jwk  = new JsonWebKey(json);

                return(builder.AddSigningCredential(jwk, jwk.Alg));
            }
            else
            {
                var key = CryptoHelper.CreateRsaSecurityKey();
                var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
                jwk.Alg = signingAlgorithm.ToString();

                if (persistKey)
                {
                    File.WriteAllText(filename, JsonConvert.SerializeObject(jwk));
                }

                return(builder.AddSigningCredential(key, signingAlgorithm));
            }
        }
Esempio n. 4
0
        private Task <string> CreateToken(IClient client)
        {
            using ILifetimeScope scope = _container.BeginLifetimeScope();
            SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
            RSAParameters   rsaParameters   = CreateRSAParameter();
            //RSA rsa = new RSACryptoServiceProvider(2048);
            //Debug.WriteLine(Convert.ToBase64String(rsa.ExportRSAPublicKey()));
            RsaSecurityKey securityKey = new RsaSecurityKey(rsaParameters);
            JsonWebKey     jsonWebKey  = JsonWebKeyConverter.ConvertFromRSASecurityKey(securityKey);
            //Debug.WriteLine(JsonConvert.SerializeObject(jsonWebKey));
            SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha512);
            List <Claim>       claims      = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N"))
            };

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, client.ClientId.ToString("N")));
            claims.Add(new Claim("accounts", client.AccountId.ToString("N")));
            JwtSecurityToken token = new JwtSecurityToken(
                "urn:brassloon",
                "urn:brassloon",
                claims,
                expires: DateTime.Now.AddHours(6),
                signingCredentials: credentials
                );

            return(Task.FromResult <string>(new JwtSecurityTokenHandler().WriteToken(token)));
        }
        public static void Run()
        {
            var tokenHandler = new JsonWebTokenHandler();
            var key          = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };

            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSsaPssSha256);
            var lastJws = tokenHandler.CreateToken(Jwt);

            Console.WriteLine($"{lastJws}{Environment.NewLine}");

            // Store in filesystem
            // Store HMAC os Filesystem, recover and test if it's valid
            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            File.WriteAllText("current-rsa.key", JsonConvert.SerializeObject(jwk));


            var storedJwk = JsonConvert.DeserializeObject <JsonWebKey>(File.ReadAllText("current-rsa.key"));

            TokenValidationParams.IssuerSigningKey = storedJwk;
            var validationResult = tokenHandler.ValidateToken(lastJws, TokenValidationParams);

            Console.WriteLine(validationResult.IsValid);
        }
Esempio n. 6
0
        static int Main(string[] args)
        {
            var path = args.Length > 0
                ? args[0]
                : "rotation";

            var keyOrder =
                Directory.EnumerateFiles(path)
                .Select(x => Int32.Parse(x.Split('.')[1]))
                .OrderByDescending(x => x)
                .ToList();

            var nextFilename = $"pkey.{keyOrder.FirstOrDefault() + 1}.jwk";
            var key          = CryptoHelper.CreateRsaSecurityKey();
            var jwk          = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
            var json         = JsonSerializer.Serialize(jwk);

            File.WriteAllText($"{path}/{nextFilename}", json);
            foreach (var retire in keyOrder.Skip(2))
            {
                File.Delete($"{path}/pkey.{retire}.jwk");
            }

            return(1);
        }
Esempio n. 7
0
        public JsonWebKey GetPublicJsonWebKey()
        {
            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(GetRsaKey(RsaKeyType.Public));

            jwk.Use = AiofClaims.Sig;
            jwk.Alg = AlgType.RS256.ToString();

            return(jwk);
        }
Esempio n. 8
0
        public JsonWebKey GetJWKFromPK(PublicKeyTE pke)
        {
            RSA rsa = RSA.Create();

            rsa.ImportRSAPublicKey(Convert.FromBase64String(pke.PublicKey), out _);
            RsaSecurityKey rsaSecurity = new RsaSecurityKey(rsa);

            rsaSecurity.KeyId = pke.RowKey;

            return(JsonWebKeyConverter.ConvertFromRSASecurityKey(rsaSecurity));
        }
        private static JsonWebKey GenerateRSA()
        {
            var key = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };

            var newJwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            return(newJwk);
        }
Esempio n. 10
0
        private JsonWebKey CreateJWK()
        {
            var key = new RsaSecurityKey(RSA.Create(Keysize))
            {
                KeyId = Guid.NewGuid().ToString()
            };
            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            SaveKey(jwk);
            return(jwk);
        }
Esempio n. 11
0
        public Result <JsonWebKey> GetJWK()
        {
            var publicKeyRaw = Convert.FromBase64String(_configs.JwtConfigs.PublicKey);

            using var rsa = RSA.Create();
            rsa.ImportSubjectPublicKeyInfo(publicKeyRaw, out _);
            var key = new RsaSecurityKey(rsa);

            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            return(new Result <JsonWebKey>(jwk));
        }
Esempio n. 12
0
        public static (string PrivateKey, string PublicKey) Generate()
        {
            var rsa = new RSACryptoServiceProvider(2048);

            var privateKey = rsa.ExportParameters(true);
            var publicKey  = rsa.ExportParameters(false);

            var publicRsaSecurityKey = new RsaSecurityKey(publicKey);
            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(publicRsaSecurityKey);

            var privateKeyJson = JsonConvert.SerializeObject(privateKey, _serializerSettings);
            var publicKeyJson  = JsonConvert.SerializeObject(jwk, _serializerSettings);

            return(privateKeyJson, publicKeyJson);
        }
Esempio n. 13
0
            /// <summary>
            /// Generate a signed JaaS JWT token string.
            /// </summary>
            /// <param name="privateKey">The private key used to sign the JWT.</param>
            /// <returns></returns>
            public String SignWith(RSA privateKey)
            {
                var rsaSecurityKey = new RsaSecurityKey(privateKey);
                var jwk            = JsonWebKeyConverter.ConvertFromRSASecurityKey(rsaSecurityKey);

                jwk.KeyId = apiKey;

                var context = new Dictionary <String, Object>();

                context.Add("user", userClaims);
                context.Add("features", featureClaims);
                payload.Add("context", context);

                var cred       = new SigningCredentials(jwk, SecurityAlgorithms.RsaSha256);
                var secToken   = new JwtSecurityToken(new JwtHeader(cred), this.payload);
                var jwtHandler = new JwtSecurityTokenHandler();

                return(jwtHandler.WriteToken(secToken));
            }
Esempio n. 14
0
 public async Task <IActionResult> Get()
 {
     try
     {
         var            jsonWebKeySet = new { Keys = new List <object>() };
         RsaSecurityKey securityKey   = GetSecurityKey(_settings.Value.TknCsp);
         JsonWebKey     jsonWebKey    = JsonWebKeyConverter.ConvertFromRSASecurityKey(securityKey);
         jsonWebKeySet.Keys.Add(jsonWebKey);
         return(Content(JsonConvert.SerializeObject(jsonWebKeySet, new JsonSerializerSettings {
             ContractResolver = new CamelCasePropertyNamesContractResolver()
         }), "appliation/json"));
     }
     catch (Exception ex)
     {
         using (ILifetimeScope scope = _container.BeginLifetimeScope())
         {
             await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
         }
         return(StatusCode(StatusCodes.Status500InternalServerError));
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Creates the JWK.
        /// </summary>
        /// <param name="rsa">The RSA.</param>
        /// <param name="keyId">The key identifier.</param>
        /// <param name="use">The use.</param>
        /// <param name="includePrivateParameters">if set to <c>true</c> [include private parameters].</param>
        /// <param name="keyops">The keyops.</param>
        /// <returns></returns>
        public static JsonWebKey CreateJwk(
            this RSA rsa,
            string keyId,
            string use,
            bool includePrivateParameters = false,
            params string[] keyops)
        {
            var parameters = rsa.ExportParameters(includePrivateParameters);
            var key        = new RsaSecurityKey(parameters);
            var jwk        = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            jwk.Use = use;
            jwk.Kid = keyId;
            jwk.Alg = SecurityAlgorithms.RsaSha256;
            jwk.CryptoProviderFactory = CryptoProviderFactory.Default;
            foreach (var keyop in keyops)
            {
                jwk.KeyOps.Add(keyop);
            }

            return(jwk);
        }
Esempio n. 16
0
        public Jwks GetJwks()
        {
            _rsa.ImportRSAPublicKey(_publicKey, out _);

            RsaSecurityKey key = new RsaSecurityKey(_rsa);

            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            jwk.Alg = "RSA256";
            jwk.Kid = _kid;
            jwk.Use = "sig";
            var jwks = new Jwks
            {
                keys = new[] {
                    new { alg = jwk.Alg, e = jwk.E, kid = jwk.Kid, kty = jwk.Kty, n = jwk.N, use = jwk.Use }
                }
            };

            return(jwks);

            //var jwksJson = JsonSerializer.Serialize(Jwks);

            //return jwksJson;
        }
        public static RootOptions UseApiKey(this RootOptions options, string algorithmName, string subject, JwtPayload customPayload, out string token, out SecurityKey privateKey)
        {
            if (null == options.Authentication)
            {
                options.Authentication = new AuthenticationOptions();
            }

            if (null == options.Authentication.MonitorApiKey)
            {
                options.Authentication.MonitorApiKey = new MonitorApiKeyOptions();
            }

            SigningCredentials signingCreds;
            JsonWebKey         exportableJwk;

            switch (algorithmName)
            {
            case SecurityAlgorithms.EcdsaSha256:
            case SecurityAlgorithms.EcdsaSha256Signature:
            case SecurityAlgorithms.EcdsaSha384:
            case SecurityAlgorithms.EcdsaSha384Signature:
            case SecurityAlgorithms.EcdsaSha512:
            case SecurityAlgorithms.EcdsaSha512Signature:
                ECDsa            ecDsa    = ECDsa.Create(GetEcCurveFromName(algorithmName));
                ECDsaSecurityKey ecSecKey = new ECDsaSecurityKey(ecDsa);
                signingCreds = new SigningCredentials(ecSecKey, algorithmName);
                ECDsa            pubEcDsa    = ECDsa.Create(ecDsa.ExportParameters(false));
                ECDsaSecurityKey pubEcSecKey = new ECDsaSecurityKey(pubEcDsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(pubEcSecKey);
                privateKey    = ecSecKey;
                break;

            case SecurityAlgorithms.RsaSha256:
            case SecurityAlgorithms.RsaSha256Signature:
            case SecurityAlgorithms.RsaSha384:
            case SecurityAlgorithms.RsaSha384Signature:
            case SecurityAlgorithms.RsaSha512:
            case SecurityAlgorithms.RsaSha512Signature:
                RSA            rsa       = RSA.Create(GetRsaKeyLengthFromName(algorithmName));
                RsaSecurityKey rsaSecKey = new RsaSecurityKey(rsa);
                signingCreds = new SigningCredentials(rsaSecKey, algorithmName);
                RSA            pubRsa       = RSA.Create(rsa.ExportParameters(false));
                RsaSecurityKey pubRsaSecKey = new RsaSecurityKey(pubRsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(pubRsaSecKey);
                privateKey    = rsaSecKey;
                break;

            case SecurityAlgorithms.HmacSha256:
            case SecurityAlgorithms.HmacSha384:
            case SecurityAlgorithms.HmacSha512:
                HMAC hmac = HMAC.Create(GetHmacAlgorithmFromName(algorithmName));
                SymmetricSecurityKey hmacSecKey = new SymmetricSecurityKey(hmac.Key);
                signingCreds  = new SigningCredentials(hmacSecKey, algorithmName);
                exportableJwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(hmacSecKey);
                privateKey    = hmacSecKey;
                break;

            default:
                throw new ArgumentException($"Algorithm name '{algorithmName}' not supported", nameof(algorithmName));
            }

            JwtHeader               newHeader    = new JwtHeader(signingCreds, null, JwtConstants.HeaderType);
            JwtSecurityToken        newToken     = new JwtSecurityToken(newHeader, customPayload);
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string resultToken = tokenHandler.WriteToken(newToken);

            JsonSerializerOptions serializerOptions = JsonSerializerOptionsFactory.Create(JsonSerializerOptionsFactory.JsonIgnoreCondition.WhenWritingNull);
            string publicKeyJson = JsonSerializer.Serialize(exportableJwk, serializerOptions);

            string publicKeyEncoded = Base64UrlEncoder.Encode(publicKeyJson);

            options.Authentication.MonitorApiKey.Subject   = subject;
            options.Authentication.MonitorApiKey.PublicKey = publicKeyEncoded;

            token = resultToken;

            return(options);
        }
        public JwtRequestAuthorizeTests()
        {
            IdentityModelEventSource.ShowPII = true;

            _rsaKey = CryptoHelper.CreateRsaSecurityKey();

            _mockPipeline.Clients.AddRange(new Client[]
            {
                _client = new Client
                {
                    ClientName           = "Client with keys",
                    ClientId             = "client",
                    Enabled              = true,
                    RequireRequestObject = true,

                    RedirectUris = { "https://client/callback" },

                    ClientSecrets =
                    {
                        new Secret
                        {
                            // x509 cert as base64 string
                            Type  = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        },
                        new Secret
                        {
                            // symmetric key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = _symmetricJwk
                        },
                        new Secret
                        {
                            // RSA key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromRSASecurityKey(_rsaKey))
                        },
                        new Secret
                        {
                            // x509 cert as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromX509SecurityKey(new X509SecurityKey(TestCert.Load())))
                        }
                    },

                    AllowedGrantTypes = GrantTypes.Implicit,

                    AllowedScopes = new List <string>
                    {
                        "openid", "profile", "api1", "api2"
                    }
                },
            });

            _mockPipeline.Users.Add(new TestUser
            {
                SubjectId = "bob",
                Username  = "******",
                Claims    = new Claim[]
                {
                    new Claim("name", "Bob Loblaw"),
                    new Claim("email", "*****@*****.**"),
                    new Claim("role", "Attorney")
                }
            });

            _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            });
            _mockPipeline.ApiScopes.AddRange(new ApiResource[] {
                new ApiResource
                {
                    Name   = "api",
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "api1"
                        },
                        new Scope
                        {
                            Name = "api2"
                        }
                    }
                }
            });

            _mockPipeline.Initialize();
        }
Esempio n. 19
0
        private JsonWebKey GenerateRsa()
        {
            var key = CryptoService.CreateRsaSecurityKey();

            return(JsonWebKeyConverter.ConvertFromRSASecurityKey(key));
        }