我正在尝试运行我的应用程序,但它遇到以下错误:
System.NotSupportedException HResult=0x80131515 消息=IDX10634: 无法创建 SignatureProvider。算法:'[PII 被隐藏 默认。将 IdentityModelEventSource.cs 中的“ShowPII”标志设置为 true 显示它。]', SecurityKey: '[PII 默认情况下是隐藏的。设置 IdentityModelEventSource.cs 中的“ShowPII”标志设置为 true 以显示它。]' 不支持。
哪里
算法为RS256
执行这条指令时卡住了:
var sectoken = tokenHandler.CreateToken(tokenDescriptor);
这是什么意思?我的代码出了什么问题?我该如何解决这个问题?
这是我的代码:
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
//...
public class TokenManager
{
private string unencoded_key = "CaptainDeadpool";
private string encoded_key = "CaptainDeadpool";
//...
public TokenManager()
{
var plainTextBytes = Encoding.UTF8.GetBytes(unencoded_key);
encoded_key = Convert.ToBase64String(plainTextBytes);
}
public string CreateFromUsername(string usr, int? timer)
{
if (timer == null) { timer = 30; }
double timeadd = Convert.ToDouble(timer);
var secret = Convert.FromBase64String(encoded_key);
var tokenHandler = new JwtSecurityTokenHandler();
var actual = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, usr) }),
Expires = actual.AddMinutes(timeadd),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.RsaSha256Signature)
};
var sectoken = tokenHandler.CreateToken(tokenDescriptor);
var stringtoken = tokenHandler.WriteToken(sectoken);
return stringtoken;
}
//...
这是我发出错误时
tokenDescriptor
的内容:
不知道该错误消息意味着什么,但我认为这并不重要,因为您的代码在逻辑上是错误的。 RSA 是不对称算法,但您尝试将
SymmetricSecurityKey
与它一起使用。
因此,要么使用另一种(对称)签名算法(并确保您的密钥大小对于该算法有效),例如:
// adjust key size
private string unencoded_key = "CaptainDeadpool!";
private string encoded_key = "CaptainDeadpool!";
// ...
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(secret),
SecurityAlgorithms.HmacSha256Signature)
或者提供有效的密钥,例如:
private readonly RSA _rsa;
public TokenManager() {
// import instead of creating new, if necessary
_rsa = new RSACryptoServiceProvider(2048);
}
// ...
SigningCredentials = new SigningCredentials(
new RsaSecurityKey(_rsa),
SecurityAlgorithms.RsaSha256Signature)
我在使用 hmacSha256 时遇到了同样的问题。如果您的安全密钥太短,您可能会收到该错误。我增加了秘密 secureKey 的大小,这解决了我的问题。
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("You_Need_To_Provide_A_Longer_Secret_Key_Here"));
密钥必须至少包含 32 个字符。
我在安装.net 8时也遇到了这个错误。 ArgumentOutOfRangeException:IDX10720:无法为算法创建 KeyedHashAlgorithm
所以根据 Mehdi 编写的上述回复,解决方案是正确的 “密钥必须至少有 32 个字符。” 像下面这样 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("b693a53f-ad24-4fb0-bca0-92f56ae6406b"));