Skip to content

Instantly share code, notes, and snippets.

@simon04
Created Feb 10, 2021
Embed
What would you like to do?
Configure RSA512 algorithm for com.auth0.jwt.JWT using an RSA private/public key generated by openssl
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.bouncycastle.util.io.pem.PemReader;
import org.junit.Test;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* Configure RSA512 algorithm for com.auth0.jwt.JWT using an RSA private/public key generated by openssl.
*
* See also: https://www.baeldung.com/java-read-pem-file-keys
*/
public class JwtTest {
@Test
public void test() throws Exception {
// Generate RSA private/public key
// $ openssl genrsa -out private.key 4096
// $ openssl rsa -in private.key -pubout -out public.key
// $ openssl pkcs8 -topk8 -nocrypt -in private.key -out private.pkcs8.key
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey;
try (BufferedReader reader = Files.newBufferedReader(Paths.get("public.key"))) {
byte[] publicKeyBytes = new PemReader(reader).readPemObject().getContent();
publicKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
}
RSAPrivateKey privateKey;
try (BufferedReader reader = Files.newBufferedReader(Paths.get("private.pkcs8.key"))) {
byte[] privateKeyBytes = new PemReader(reader).readPemObject().getContent();
privateKey = (RSAPrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
}
Algorithm algorithm = Algorithm.RSA512(publicKey, privateKey);
String token = JWT.create().withSubject("foobar").sign(algorithm);
System.out.println(token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment