juanchito
juanchito

Reputation: 519

Given a public key string, how to create an instance of RSAPublicKey

I have an actual public key string like:

-----BEGIN PUBLIC KEY-----
flajeleofancncMFLDFJOEEFJC9209ueq33rlsjfa3B ...
-----END PUBLIC KEY-----

In order to create an auth0/java-jwt-library Algorithm to sign my JWT, I need a java.security.interfaces.RSAPublicKey-implementation instance. How would I go about creating that instance given public key string? If it helps, I also have the private key string. I'm just starting out. So, I'm open to simpler ways to signing my JWT.

Upvotes: 2

Views: 2275

Answers (1)

juanchito
juanchito

Reputation: 519

import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.interfaces.RSAPrivateKey;

...

String algorithm = "RSA" // for example
KeyFactory kf = KeyFactory.getInstance(algorithm);
String publicKeyStr = "-----BEGIN PUBLIC KEY-----f24Defosfvak-----END PUBLIC KEY-----"
EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyStr.getBytes());
RSAPublicKey publicKey = kf.generatePublic(keySpec);

Upvotes: 2

Related Questions