1 year ago

#98875

test-img

tutiplain

Verify JWT Token data with C#

I am trying to verify a JWT token signed with RSA256 in C#. The token was created on the server side in Javascript with the jwt library called Jose-jwt. I am veryfing the token in a WinForms app using C#'s System.Security.Cryptography namespace classes. I tried using jose-jwt for C# but apparently it doesn't support loading keys from PEM-encoded files.

Here is my verification code:

public static string IsCertValid()
    {
        string token = System.IO.File.ReadAllText(TokenLocation);
        var stream = System.IO.File.OpenRead(PublicKeyLocation);
        var reader = new PemReader(stream);
        var rsaParameters = reader.ReadRsaKey();

        var rsa = System.Security.Cryptography.RSA.Create();
        rsa.ImportParameters(rsaParameters);

        string[] tokenparts = token.Split('.');

        byte[] signature = Encoding.UTF8.GetBytes(tokenparts[2]);
        string dataToVerify = tokenparts[0] + '.' + tokenparts[1];
        byte[] bytesToVerify = Encoding.UTF8.GetBytes(dataToVerify);
        //string decoded = JWT.Decode(token,rsaParameters);
        bool result = rsa.VerifyData(bytesToVerify, signature, System.Security.Cryptography.HashAlgorithmName.SHA256, System.Security.Cryptography.RSASignaturePadding.Pkcs1);
        return result.ToString();
    }

This validates as false, even though I know that the token is valid for this key. Does verification need to happen with the private key? That doesn't seem very secure. What am I doing wrong? Any help will be greatly appreciated.

c#

jwt

.net-4.6

jose

0 Answers

Your Answer

Accepted video resources