Generate JWE (Encrypted JWT) using Json Web Token JJWT

822 Views Asked by At

I am trying to generate JWE using JJWT in Java.

As per the documentation https://github.com/jwtk/jjwt#creating-a-jwe there has to be an encryptWith method in JwtBuilder class but I am not able to find it and I am using the latest available version with JDK 8

implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

Currently, I am using JWS and want to replace it with JWE

String token = Jwts.builder().setClaims(claims).setIssuer(jwtIssuer)
                .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date
                        .from(currentTime.plusMinutes(accessTokenExpiryMin).atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(getSigningKey()).compact();

How to use the encryptWith method? Am I missing something?

Thanks in advance.

1

There are 1 best solutions below

1
Sumit Kumar On
String token = Jwts.builder().setClaims(claims).setIssuer(jwtIssuer)
                .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date
                        .from(currentTime.plusMinutes(accessTokenExpiryMin).atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(getSigningKey()).compact();

private static final String encryptSecret = "ThisisnotSecret"; //This must be a 256 bit long
byte[] encryptSecretBytes = encryptSecret.getBytes();
Key key = new AesKey(encryptSecretBytes);
JsonWebEncryption jwe = new JsonWebEncryption();
jwe.setPayload(token);
jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A256KW); 
jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512);
jwe.setKey(key);
String encryptedToken = jwe.getCompactSerialization();   

 implementation 'org.bitbucket.b_c:jose4j:0.9.4'
 runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.3'
 runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.3'