gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:20:05 30 4
gpt4 key购买 nike

我正在尝试使用此代码段对我的 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com