0

I have seen some examples to convert java.security.PublicKey to JWK but I could not find an example to convert java.security.PrivateKey to JWK (JSON) format in Android. Is that even possible? Is there a way to do this without using any 3rd-party library?

Expecting a function in Java/Kotlin to convert the PrivateKey to JSON (JWK) format.

Ashwin
  • 53
  • 5

1 Answers1

0

Generate the RSA key pair

KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair keyPair = gen.generateKeyPair();

Convert to JWK format

JWK jwk = new RSAKey.Builder((RSAPublicKey)keyPair.getPublic())
    .privateKey((RSAPrivateKey)keyPair.getPrivate())
    .keyUse(KeyUse.SIGNATURE)
    .keyID(UUID.randomUUID().toString())
    .build();
  • 1
    What is `JWK` data type? Which library are you using? Also, my `KeyPair` is `java.security.KeyPair` and cannot be typecasted to `RSAPublicKey`, I cannot generate new keys using 3-rd party libraries. – Ashwin Nov 28 '22 at 09:05