尝试在C#Web API应用程序中创建JWT令牌时,我遇到异常。
测试环境
以下是负责生成RSA密钥的代码:
public SignatureInformation CreateNewSignatureInformation(int length = 0)
{
try
{
var signatureInformation = new SignatureInformation();
var rsaProvider = new RSACryptoServiceProvider(length);
var publicKey = rsaProvider.ToXmlString(false);
signatureInformation.Public = publicKey;
var privateKey = rsaProvider.ToXmlString(true);
signatureInformation.Private = privateKey;
return signatureInformation;
}
catch (Exception)
{
return null;
}
}
以下是负责生成使用上述代码生成的RSA密钥对签名的JTW令牌的代码:
private string GenerateToken(string privateKeyInXml)
{
var cryptoServiceProvider = new RSACryptoServiceProvider();
cryptoServiceProvider.FromXmlString(privateKeyInXml);
var creds = new SigningCredentials(new RsaSecurityKey(cryptoServiceProvider),
SecurityAlgorithms.RsaSha256Signature,
SecurityAlgorithms.Sha256Digest);
var nbf = DateTime.UtcNow;
var exp = nbf.AddMinutes(10);
var jwtToken = new JwtSecurityToken("SAMPLE_ISSUER",
"SAMPLE_AUDIENCE",
null, //null is given as claims list in this sample
nbf,
exp,
creds);
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.WriteToken(jwtToken); //the exception is thrown here
return token;
}
抛出的异常是System.ArgumentOutOfRangeException
类型,消息是:
"IDX10630: The 'System.IdentityModel.Tokens.RsaSecurityKey' for signing cannot be smaller than '2048' bits.\r\nParameter name: key.KeySize\r\nActual value was 512."
问题
如何使用密钥大小小于2048的RSA安全密钥生成JWT令牌?
答案 0 :(得分:0)
在这种情况下,对最小密钥大小的限制由SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning
属性控制。不幸的是,还有一个绝对的"最小值,由readonly字段SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForSigning
控制,这个"绝对值"最小值设为2048。
您必须使用反射将该只读字段的值修改为您想要的值。之后,您可以将MinimumAsymmetricKeySizeInBitsForSigning
设置为相同的所需值。
示例代码:
var absoluteField = typeof(SignatureProviderFactory).GetField(nameof(SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForSigning), BindingFlags.Public | BindingFlags.Static);
absoluteField.SetValue(null, 512);
SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning = 512;
之后,您的代码应该可以正常工作并接受任何大小为512及以上的不对称密钥。