9

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 that feature. However, the documentation does not show how one can use own public/private key pairs in jjwt.

I created the private/public key pair, and used it successfully 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 found no way of doing the same in Java with jjwt.

Anyone has a working example of how to use private/public keys for JWT in Java with jjwt?

Community
  • 1
  • 1
Predrag Stojadinović
  • 3,439
  • 6
  • 34
  • 52
  • FWIW: I'd advise you to use jose4j, https://bitbucket.org/b_c/jose4j/wiki/Home, the leading Java implementation of JOSE/JWT – Hans Z. Jun 13 '16 at 17:21

1 Answers1

1

Here is what I have followed

Create Keystore

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

You can create Key store from existing private key and public key. Google it how to do it.

Load 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 the message

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

Use JJwt api to claim the message

X509Certificate certificate = (X509Certificate) keyEntry.getCertificate();
Jwts.parser().setSigningKey(certificate.getPublicKey()).parseClaimsJws(s).getBody().getSubject().equals("Abc");
Sangram Jadhav
  • 2,438
  • 16
  • 17