0

My target is generate JWT token using RS256 algorithm using RSA private key. My steps for this:

I have generated a rsa private key using following command:

openssl genrsa -out private_key.pem 2048

after that I write below code to generate JWT token:

 var claims = ......(list of claims)...
 string privateKey = File.ReadAllText(@"C:\Users\FazlaElahiMdJubayer\private_key.pem");
 CreateToken(privateKey, claims);

 private static void CreateToken(string privateKey, List<Claim> claims)
    {
        RSAParameters rsaParams;
        using (var tr = new StringReader(privateKey))
        {
            var pemReader = new PemReader(tr);
            var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
            if (keyPair == null)
            {
                throw new Exception("Could not read RSA private key");
            }
            var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters;
            rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
        }
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            rsa.ImportParameters(rsaParams);
            Dictionary<string, object> payload = claims.ToDictionary(k => k.Type, v => (object)v.Value);
            var token = Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256);
        }
    }

but somehow the keyPair is null and throw Could not read RSA private key even though my code successfully read the private key from the .pem file. Is there anything wrong with my private key? What steps I am missing? my private key is below:

-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCu7awWqTY3RtPT
APwkC/4ufWSEkm/fieobjkZHUjpUU836me1enYncEXJue6t9bB7SQck7THgG1O12
jxT9mCbQWSmwdWUpIj6AvGkyAGuMAJzfzrU0x95SJEtIjOnIA0gPQQ3UR7oKgO7I
K2z40qpuy9l2NxZ1YxffBRkqpV16LHD9KuFOsd0iMWnViJI3yLqsUMwOKaj+L9aR
yCGGZ0Y8oFBCzZyY5irtyVHlzlI+kZRmi4N3ZxAEmXYVO4jOtlIj47RpK3WWBEGa
kTLkdTLkMaR/WCHIhvOl/vtgK0PEc18+fbFGUlOiPuIqyXGtnzOPdvVm2WCF+U25
eoxCbjJbAgMBAAECggEAOZf8HFvrA0kZDfRZj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LgjkcuJZfdKkgz4zOJS2jwnTKV1gfS1UAEA1vNs9qmX71FzV/Su55Fgr1feljef
LBrHllWAWRHQNcRsjIOljLcF3yCsE5NZsn9HPEFlhYIMXi5ZbDpWvSkO7zp9QQNa
ci9m4h9FKl2AjrWWco32yQ==
-----END PRIVATE KEY-----

and my claims are like this:

var claims = new[]
        {
            new Claim("partnerUrl", "https://www.my-domain.com"),
            new Claim("offerId", "adsaddsadadsad"),
            new Claim("returnUrl", "https://demo.com/lend/"),
            new Claim("expireOn", "2006-09-18T00:00:00.000Z"),
        };
  • Maybe it is worth trying to read the file directly as stream: https://stackoverflow.com/a/72260086 instead of first loading it as string and then reading the key from that string. Bascially try `var tr = new StreamReader(@"C:\Users\FazlaElahiMdJubayer\private_key.pem")` – rene Mar 26 '23 at 06:34
  • 1
    Your key has the PKCS#8 format, the code requires the PKCS#1 format. You can convert the key online, e.g. [here](https://8gwifi.org/pemconvert.jsp) (for security reasons not for productive keys), or create a key in PKCS#1 format *directly* with OpenSSL or adapt the code (the latter depends on the .NET version, which you should also specify). – Topaco Mar 26 '23 at 07:12
  • @Topaco after converting to PKCS#1 it works, however the token I got showing invalid signature in this https://jwt.io/ website, any idea why my code generating invalid signature? – Fazla Elahi Md Jubayer Mar 26 '23 at 13:06
  • I can verify the generated token on *https://jwt.io/* using your code and private key (with my own `claims`). Why it doesn't work for you can probably be answered if you provide the missing information: `claims`-part of the code, generated token, public key used (and private key if different from the posted one). – Topaco Mar 26 '23 at 13:31
  • @Topaco i have added my claims, could you please check in the question again – Fazla Elahi Md Jubayer Mar 26 '23 at 13:36
  • Works for me. RS256 is deterministic, post the generated token for comparison. Check if the public key is valid (i.e. related to the private one) or post it. – Topaco Mar 26 '23 at 13:52
  • how you generate public key after converting to PKCS#1 ? @Topaco – Fazla Elahi Md Jubayer Mar 26 '23 at 14:07
  • anyway it works for me after generating public key from new private key @Topaco – Fazla Elahi Md Jubayer Mar 26 '23 at 14:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/252790/discussion-between-fazla-elahi-md-jubayer-and-topaco). – Fazla Elahi Md Jubayer Mar 26 '23 at 14:55

0 Answers0