Extracting private key for jwt library from jwks

Hello,
I am following https://developer.okta.com/docs/guides/implement-oauth-for-okta/use-client-credentials-grant-flow to implement client credentials grant flow. Following this doc, I created test jwks from https://mkjwk.org/.
However, in the subsequent steps (https://developer.okta.com/docs/guides/build-self-signed-jwt/java/jwt-with-private-key/ ) to sign with the private key, I dont see how the public private key pair in jwks format gets converted into java’s private key.
The documentation talks of loading the private key from configuration. Can anyone help me convert a jwks of this format:
{
“p”: “…”,
“kty”: “RSA”,
“q”: “…”,
“d”: “…”,
“e”: “…”,
“qi”: “…”,
“dp”: “…”,
“dq”: “…”,
“n”: “…”
}
to a variable of java.security.PrivateKey;

I think you’d need a tool to convert it into something which can be used by Java. There are converters jwk -> pem

Hi Nacha,
You can use the java security classes to build a java Private key using the n and d parameters of the jwk:
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
new BigInteger(1, Base64.getUrlDecoder().decode(/* keyModulus, n */)),
new BigInteger(1, Base64.getUrlDecoder().decode(/* privateExponent, d */)
);
KeyFactory factory = KeyFactory.getInstance(“RSA”);
PrivateKey privateKey = factory.generatePrivate(rsaPrivateKeySpec);

https://docs.oracle.com/javase/8/docs/api/java/security/spec/RSAPrivateKeySpec.html
https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html
https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
https://docs.oracle.com/javase/8/docs/api/java/security/KeyFactory.html

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.