/// <summary> /// Kind of jwks /// </summary> /// <returns></returns> private IEnumerable <JsonWebKey> GetKeys() { var jwks = new List <JsonWebKey>(); // Get keys from DataProtectionKeys var storedKey = _keyManager.GetAllKeys(); foreach (var key in storedKey.OrderByDescending(b => b.CreationDate)) { var defaultKeyId = key.KeyId; // Export for Xml to get access to masterkey var descriptorXmlInfo = key.Descriptor.ExportToXml(); var keyData = new XElement("key", descriptorXmlInfo.SerializedDescriptorElement.LastNode).Value; var bKey = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetBytes(keyData); var symetricKey = new HMACSHA256(bKey); var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(symetricKey.Key)); jwk.KeyId = Base64UrlEncoder.Encode(defaultKeyId.ToString()); jwks.Add(jwk); } return(jwks); }
private JsonWebKey GenerateHMAC(Algorithm algorithms) { var key = CryptoService.CreateHmacSecurityKey(algorithms); var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(key.Key)); jwk.KeyId = CryptoService.CreateUniqueId(); return(jwk); }
private JsonWebKey CreateJWK() { var key = (HMAC) new HMACSHA256(CreateRandomKey(64)); var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(key.Key)); SaveKey(jwk); return(jwk); }
private static JsonWebKey CreateJWK() { var symetricKey = new HMACSHA256(GenerateKey(64)); var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(symetricKey.Key)); jwk.KeyId = Base64UrlEncoder.Encode(GenerateKey(16)); return(jwk); }
/// <summary> /// Creates a <see cref="JsonWebKey"/> from the passed secret. /// </summary> /// <param name="key">The secret.</param> /// <param name="use">The key use.</param> /// <param name="keyOperations">The key operations</param> public static JsonWebKey CreateJwk(this string key, string use, params string[] keyOperations) { if (key.Length < 16) { throw new ArgumentException(Strings.Key16char, nameof(key)); } var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(securityKey); jwk.Alg = SecurityAlgorithms.HmacSha256; jwk.Kty = JsonWebAlgorithmsKeyTypes.Octet; jwk.Use = use; jwk.Kid = securityKey.KeyId ?? Id.Create(); foreach (var keyOperation in keyOperations) { jwk.KeyOps.Add(keyOperation); } return(jwk); }
public static void Run() { var tokenHandler = new JsonWebTokenHandler(); // HMAC Key var key = AutoGeneratedHmac(64); // Hmac Sha256 Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}"); // HMAC Sha 384 key = AutoGeneratedHmac(128); Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha384); Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}"); // Hmac Sha 512 Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512); Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}"); var lastJws = tokenHandler.CreateToken(Jwt); // Store HMAC os Filesystem, recover and test if it's valid var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(key); jwk.KeyId = Guid.NewGuid().ToString(); File.WriteAllText("current-hmac.key", JsonConvert.SerializeObject(jwk)); var storedJwk = JsonConvert.DeserializeObject <JsonWebKey>(File.ReadAllText("current-hmac.key")); TokenValidationParams.IssuerSigningKey = storedJwk; var validationResult = tokenHandler.ValidateToken(lastJws, TokenValidationParams); Console.WriteLine(validationResult.IsValid); }
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); }
private JsonWebKey GenerateAES(Algorithm algorithms) { var key = CryptoService.CreateAESSecurityKey(algorithms); return(JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(key.Key))); }