支持的算法:加密JWT安全令牌

6

我在尝试使用以下代码对我的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);

但是当我运行代码时,出现了错误:
加密失败。不支持: 算法: '{0}', 安全密钥: '{1}'。
其中{0}{1}是上述代码中任何组合的XXXXYYYY(是的,我写了一个反射片段并尝试了它们的所有可能组合)。 哪些算法支持编码(和解码)签名的JWT?
2个回答

11

最后我找到了答案:

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作为密钥加密算法,并将SecurityAlgorithms.Aes256CbcHmacSha512用作加密算法就能完成工作。请注意,用于加密算法的密钥应具有256/8的长度。


-2
HmacSha512 使用一个密钥来签名或验证令牌,尝试使用类似 RsaSha256 的算法进行公钥/私钥加密。

1
你能否详细说明一下你的答案?或者附上一些代码示例吗? - rudolf_franek
问题不在于是否有一个或多个键。请再次阅读问题。 - amiry jd
我不是C#专家,但HmacSha512不是SymmetricSecurityKey,请尝试新的ASymmetricSecurityKey或类似的东西。 - Mr. Mostafavi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接