下面的代码在 .NET 7 中正常
var token = handler.CreateEncodedJwt(configToken(new SecurityTokenDescriptor
{
Issuer = _options.Issuer,
Audience = _options.Audience,
SigningCredentials = _options.GenerateCredentials(),
Subject = identity,
Expires = expiration
}));
升级到 .NET 8 后出现下面的错误
System.ArgumentOutOfRangeException : IDX10720: Unable to create KeyedHashAlgorithm for algorithm 'HS256', the key size must be greater than: '256' bits, key has '128' bits. (Parameter 'keyBytes')
Stack Trace:
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.ValidateKeySize(Byte[] keyBytes, String algorithm, Int32 expectedNumberOfBytes)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateKeyedHashAlgorithm(Byte[] keyBytes, String algorithm)
请问如何解决这个问题?
GenerateCredentials 方式对应的实现代码
public class SymmetricJwtOptions : JwtOptions
{
private readonly byte[] _secretBytes;
private static byte[] GetMd5(string str)
{
return MD5.HashData(Encoding.UTF8.GetBytes(str));
}
public SymmetricJwtOptions(string secret)
{
_secretBytes = GetMd5(secret);
}
public override SecurityKey GenerateKey()
{
return new SymmetricSecurityKey(_secretBytes);
}
public override SigningCredentials GenerateCredentials()
{
return new SigningCredentials(GenerateKey(), SecurityAlgorithms.HmacSha256);
}
}
IssuerSigningKey 秘钥太短了 直接弄长点 16位好像不够