Search code examples
asp.net-coreencryptionjwtblazor-webassembly

How to decrypt token Encrypted with the following codes?


I have a jwt that is encrypted using these statements:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

// Credentials that are encrypted which can only be created by our server using the private key
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var encryptingCredentials = new EncryptingCredentials(
         new SymmetricSecurityKey(Encoding.Default.GetBytes(_config["Jwt:DecryptionKey"])),
         SecurityAlgorithms.Aes256KW,
         SecurityAlgorithms.Aes256CbcHmacSha512);
    
    
     var handler = new JwtSecurityTokenHandler();
     JwtSecurityToken token2 = null;
    
     token2 = handler.CreateJwtSecurityToken(
         _config["Jwt:Issuer"],
         _config["Jwt:Audience"],
         new ClaimsIdentity(claims),
         null,
         expires: DateTime.Now.AddMinutes(double.Parse(_config["Jwt:ExpireTime"])),
         null,
         signingCredentials: creds,
         encryptingCredentials);
     
    
     return new JwtSecurityTokenHandler().WriteToken(token2);

my question is how to decrypt returned token manually?


Solution

  • I modified part of your codes to make it easeier to be understood:

    create token:

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ProEMLh5e_qnzdNUQrqdHPgpsswertxyz"));
    var anotherkey = new SymmetricSecurityKey(Encoding.Default.GetBytes("ProEMLh5e_qnzdNUQrqdHPssqwertxyz"));
    
    // Credentials that are encrypted which can only be created by our server using the private key
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var encryptingCredentials = new EncryptingCredentials
        (
         anotherkey,
         SecurityAlgorithms.Aes256KW,
         SecurityAlgorithms.Aes256CbcHmacSha512
         );
    
    
    var handler = new JwtSecurityTokenHandler();
    
    var claims = new Claim[] { new Claim(ClaimTypes.Name, "Jhon") };
    
    var token2 = handler.CreateJwtSecurityToken(
        "Issuer",
       "Audience",
        new ClaimsIdentity(claims),
        null,
        expires: DateTime.Now.AddMinutes(1),
        null,
        signingCredentials: creds,
        encryptingCredentials);
    
    
    var jwttoken=new JwtSecurityTokenHandler().WriteToken(token2);
    

    decrypt,read claims from the token:

    var tokenValidationParameters = new TokenValidationParameters()
    {
        ValidAudiences = new string[]
        {
           "Audience"
         },
        ValidIssuers = new string[]
        {
           "Issuer"
         },
        IssuerSigningKey = key,
    
        TokenDecryptionKey = anotherkey
    };
    
    
    
    var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwttoken, tokenValidationParameters, out var securitytoken);
    

    It works as expected:

    enter image description here