Created
February 10, 2021 10:54
-
-
Save simon04/b30c8400f09648b794c25a1f3f1edb32 to your computer and use it in GitHub Desktop.
Configure RSA512 algorithm for com.auth0.jwt.JWT using an RSA private/public key generated by openssl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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