Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT Encryption Error when using EncryptingCredentials in token generation method

I implemented JWT token in my ASP.net core 3.1 web api. In the token generation method when I try to use EncryptingCredentials I got the below error :

IDX10662: The KeyWrap algorithm 'System.String' requires a key size of 'System.Int32' bits. Key '', is of size:'System.Int32'. (Parameter 'Length')

This is my Token generation method :

public async Task<string> GenerateAsync(User user)
    {
        var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); //"SampleSecretKeyChange" 
        var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);

        var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey);  //"AbcdefgHijklmnopk123456"
        var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);

        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = _siteSetting.JwtSettings.Issuer,
            Audience = _siteSetting.JwtSettings.Audience,
            IssuedAt = DateTime.Now,
            NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes),
            Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes),
            SigningCredentials = signingCredentials,
            EncryptingCredentials = encryptingCredentials,
            Subject = new ClaimsIdentity(_getClaims(user))
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var securityToken = tokenHandler.CreateToken(descriptor);
        var jwt = tokenHandler.WriteToken(securityToken);           
        return await Task.FromResult(jwt);
    }
like image 896
Matt Ghafouri Avatar asked Oct 19 '25 14:10

Matt Ghafouri


1 Answers

After of all research that I did, I found the problem. When you want to use EncryptingCredentials with the conditions that I described the Encryptkey key length must be equal 16 characters.

like image 148
Matt Ghafouri Avatar answered Oct 22 '25 03:10

Matt Ghafouri