JWT: jwtk / jjwt with public / private keys

Auth0 provides two JWT libraries, one for Node: node-jsonwebtoken and one for Java: java-jwt . It turns out that java-jwt does not support public / private key pairs.

However, another java library, the jjwt library , claims to support this feature. However, the documentation does not show how you can use your own public / private key pairs in jjwt .

I created a private / public key pair and successfully used it in Node with node-jsonwebtoken :

var key = fs.readFileSync('private.key');
var pem = fs.readFileSync('public.pem');

var header = {...};
var payload = {...};

header.algorithm = "RS256";
var message = jsonwebtoken.sign(payload, key, header);
var decoded = jsonwebtoken.verify(message, pem, {algorithm: "RS256"});

But I did not find a way to do the same in Java with jjwt .

Anyone have a working example of using private / public keys for JWT in Java with jjwt ?

+4
source share
1 answer

Here is what I followed

Create Keystore

keytool -genkey -keyalg RSA -alias self -igned -keystore keystore.jks -storepass password -validity 360 -keysize 2048

You can create a keystore from an existing private key and public key. Google how to do it.

Download Keystore

    KeyStore ks = KeyStore.getInstance("JKS");
    InputStream readStream = // Use file stream to load from file system or class.getResourceAsStream to load from classpath
    ks.load(readStream, "password".toCharArray());
    Key key = ks.getKey("selfsigned", "password".toCharArray());
    readStream.close();

Use JJwt api to sign a message

String s = Jwts.builder().setSubject("Abc").signWith(SignatureAlgorithm.RS512, key).compact();

Use JJwt api to request a message

X509Certificate certificate = (X509Certificate) keyEntry.getCertificate();
Jwts.parser().setSigningKey(certificate.getPublicKey()).parseClaimsJws(s).getBody().getSubject().equals("Abc");
+1
source

All Articles