what should be the key length in signingCredentials jwt asp.net core

Viewed 10322
public static string GenerateToken(string Username)
{
    var claimsdata = new[] { new Claim(ClaimTypes.Name, Username) };
    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes("qwertyuioplkjhgfdsazxcvbnmqwertlkjfdslkjflksjfklsjfklsjdflskjflyuioplkjhgfdsazxcvbnmmnbv"));
    var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha384Signature);
    var token = new JwtSecurityToken(
        issuer: "mysite",
        audience: "mysite",
        expires: DateTime.Now.AddMinutes(60),
        claims: claimsdata,
        signingCredentials: signInCred);
    var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
    return tokenString;
}

//the length of the key is 88 characters. if i reduce it to less than 16 characters it gives an exception:

System.ArgumentOutOfRangeException: 'IDX10603: Decryption failed. Keys tried: '[PII is hidden]'. Exceptions caught: '[PII is hidden]'. token: '[PII is hidden]''

3 Answers

the minimum length in sha256 in 16 characters because they are 256 hexadecimal bits, then 256/16 = 16

For .NET/.NET Core, the key Secret key should be a minimum of 128 bits i.e (16 bytes)

example:

"JwtToken": {
    "SecretKey": "minimumSixteenCharacters",
    "Issuer": "https://localhost:44378"
  }

From microsoft documentation:

enter image description here

So I presume if you use less than this once converted to bytes it should be padded with 0s.

Related