Skip to content

Instantly share code, notes, and snippets.

@brunohbrito

brunohbrito/hmacautokey.cs

Last active Feb 26, 2020
Embed
What would you like to do?
static void Main(string[] args)
{
var tokenHandler = new JsonWebTokenHandler();
SecurityKey key = null;
// HMAC Key
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}");
}
private static RandomNumberGenerator Rng = RandomNumberGenerator.Create();
private static DateTime Now = DateTime.Now;
private static SecurityTokenDescriptor Jwt = new SecurityTokenDescriptor
{
Issuer = "www.mysite.com",
Audience = "your-spa",
IssuedAt = Now,
NotBefore = Now,
Expires = Now.AddHours(1),
Subject = new ClaimsIdentity(new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Email, "meuemail@gmail.com", ClaimValueTypes.Email),
new Claim(JwtRegisteredClaimNames.GivenName, "Bruno Brito"),
new Claim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString())
})
};
private static SecurityKey AutoGeneratedHmac(int bytes)
{
return new SymmetricSecurityKey(GenerateHmacKey(bytes));
}
private static byte[] GenerateHmacKey(int bytes)
{
byte[] data = new byte[bytes];
Rng.GetBytes(data);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.