首页 新闻 会员 周边 捐助

升级到 .NET 8 遇到问题:" IDX10720: Unable to create KeyedHashAlgorithm for algorithm 'HS256'"

0
悬赏园豆:30 [已解决问题] 解决于 2024-01-01 13:43

下面的代码在 .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);
    }
}
dudu的主页 dudu | 高人七级 | 园豆:30925
提问于:2024-01-01 13:23
< >
分享
最佳答案
1

MD5.HashData() 改为 SHA256.HashData() 解决了

dudu | 高人七级 |园豆:30925 | 2024-01-01 13:42
dudu | 园豆:30925 (高人七级) | 2024-01-01 13:56
其他回答(1)
1

IssuerSigningKey 秘钥太短了 直接弄长点 16位好像不够

魏杨杨 | 园豆:373 (菜鸟二级) | 2024-03-13 02:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册