Getting System.FormatException: while reading "n" and "e" records from jwk file hosted on a server

176 views Asked by At

I am trying to verify the JWT signature using a JWK file hosted on a server.

I have a jwk model in my project Jwk which looks like below:

public class Jwk{
        [JsonProperty("alg")]
        public string Alg { get; set; }

        [JsonProperty("e")]
        public string E { get; set; }

        [JsonProperty("kty")]
        public string Kty { get; set; }

        [JsonProperty("n")]
        public string N { get; set; }

        [JsonProperty("use")]
        public string Use { get; set; }
}

here how I am using it in a code:

public TokenValidationParameters VerifyToken(Jwk jwk)
        {
            // Here I am getting the exception
            RSAParameters rsaParams = new RSAParameters
            {
                Modulus = Convert.FromBase64String(jwk.N),
                Exponent = Convert.FromBase64String(jwk.E),
                
            };

            using RSA rsa = RSA.Create();
            rsa.ImportParameters(rsaParams);

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new RsaSecurityKey(rsa)
            };

            return validationParameters;
        }

I am getting the exception saying:

System.FormatException: 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.'

My data looks like this:

{ 
    "kty": "RSA", 
    "n": "qum6HexDv55WPr9iqoO-yOoqGRiFaF0Vx7YAigPYsLdyAgnmQRKxI81_XgJfH_f18mNO_j4GCVLIzvQYZGFw9cIs3b3kt9frxNssc24_Uh6zccvE2XWn9yr81OYu85OfL4mgA1WQPm- 
ZKIzvPq77ISY51PBSpK6FQkwuc9OhWDk",
    "e": "AQAB", 
    "alg": "RS256", 
    "use": "sig" 
} 
0

There are 0 answers