c# - 加密 JWT 安全 token 支持的算法

标签 c# .net-core jwt encryption-symmetric netcoreapp2.1

我正在尝试使用此代码段对我的 JWt 进行签名和编码:

var claims = new Claim[] { new SomeClaimes() };
var scKey = Encoding.UTF8.GetBytes("SOME KEY");
var ecKey = Encoding.UTF8.GetBytes("SOME OTHER KEY");
var tokenDescriptor = new SecurityTokenDescriptor {
    Subject = new ClaimsIdentity(claims),
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(
            scKey),
            SecurityAlgorithms.HmacSha512),
    EncryptingCredentials = new EncryptingCredentials(
        new SymmetricSecurityKey(
            ecKey),
            // I tryied all possible combination of algorithms here:
            SecurityAlgorithms.XXXX,
            SecurityAlgorithms.YYYY), 
    Issuer = "My Jwt Issuer",
    Audience = "My Jwt Audience",
    IssuedAt = DateTime.UtcNow,
    Expires = DateTime.Now.AddDays(7),
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);

但是当我运行代码时,出现错误:

Encryption failed. No support for: Algorithm: '{0}', SecurityKey: '{1}'.

其中{0}{1}是上面代码中XXXXYYYY的任意组合(是的,我写了一个反射片段并尝试了它们的所有可能组合)。编码(和解码)签名的 JWT 支持哪些算法?

最佳答案

终于找到答案了:

var claims = new Claim[] { new SomeClaimes() };
var scKey = Encoding.UTF8.GetBytes("SOME KEY");
var ecKeyTemp = Encoding.UTF8.GetBytes("SOME OTHER KEY");

// Note that the ecKey should have 256 / 8 length:
byte[] ecKey = new byte[256 / 8];
Array.Copy(ecKeyTemp, ecKey, 256 / 8);

var tokenDescriptor = new SecurityTokenDescriptor {
    Subject = new ClaimsIdentity(claims),
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(
            scKey),
            SecurityAlgorithms.HmacSha512),
    EncryptingCredentials = new EncryptingCredentials(
        new SymmetricSecurityKey(
            ecKey),
            SecurityAlgorithms.Aes256KW,
            SecurityAlgorithms.Aes256CbcHmacSha512), 
    Issuer = "My Jwt Issuer",
    Audience = "My Jwt Audience",
    IssuedAt = DateTime.UtcNow,
    Expires = DateTime.Now.AddDays(7),
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);

如您所见,使用 SecurityAlgorithms.Aes256KW 作为 key 加密算法SecurityAlgorithms.Aes256CbcHmacSha512 作为加密算法 将完成这项工作。请注意,用于加密算法的 key 应具有 256/8 长度。

关于c# - 加密 JWT 安全 token 支持的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53487247/

相关文章:

java - Box2D:我可以将固定装置转移到其他物体吗?

c# - 带有 BackgroundTask 的 UWP 应用程序将不再构建错误 80080204

C# Windows 服务文本编写器

azure - 在 .NET Core 控制台应用程序中以编程方式创建 New-AzureRmRoleAssignment

c# - 如何在 .net core/Linux 中实现 Diffie Hellman

c# - 如何在.NET Core 3.1中使用用户名和密码获取AWS Cognito访问 token ?

angular - 将 JWT token 存储到 HttpOnly cookie 中

C#:选择具有包含子字符串的属性的节点的 XPath?

Spring OAuth + JWT --/oauth/token

Angular 4 - TypeError : Cannot read property 'length' of null