3

I am attempting to write code to sign a JWT token using a private key from a certificate. I have been attempting to adapt this StackOverflow answer (which uses jose-jwt) to use Microsoft.IdentityModel instead.

Having retrieved a X509Certificate2 (called certificate in the code below), the following code successfully generates a token. (The payload below is a non-empty Dictionary<string, object>)

var privateKey = certificate.GetRSAPrivateKey();
var tokenString = Jose.JWT.Encode(payload, privateKey, Jose.JwsAlgorithm.RS256);

However, an attempted equivalent implementation using Microsoft's IdentityModel doesn't work:

var privateKey = certificate.GetRSAPrivateKey();
var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(privateKey);
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256);

var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

var token = handler.CreateJwtSecurityToken(signingCredentials: credentials);

var tokenString = handler.WriteToken(token);

This code errors on the CreateJwtSecurityToken line with the error:

IDX10630: The 'Microsoft.IdentityModel.Tokens.RsaSecurityKey' for signing cannot be smaller than 'System.Int32' bits. KeySize: 'System.Int32'. Parameter name: key

Does anybody know what is causing this error, and what could be done to resolve this?

Daniel
  • 31
  • 2
  • The certificate you are using seems to have a key smaller than 2048. Try generating one with a 2048 or larger key size – Alex Jul 10 '20 at 13:58
  • Thanks Alex, that has worked! I could have sworn I'd checked that already, but apparently not. The lack of a value in the exception message made me think there was something deeper wrong. – Daniel Jul 13 '20 at 13:29

0 Answers0