Reputation: 457
We have a remote application sending us a JWT. They used “RSA-OAEP-256” algorithm and “A256CBC-HS512” encryption and our public key to encode the token, and now I am trying to decrypt it and parse the claims. I generated the keys with openssl rsa -in <myPrivateKey> -pubout -out <myPublicKey>
, then I converted myPrivateKey
to a .der based on the suggestion of this SO post. Following the guide at nimbus, I came up with the following.
@Test
public void testDecryptJwtWithRsa() {
String filename = <myPrivateKey.der>;
String tokenString = <encryptedTokenString>;
try {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
byte[] encodedPk = pk.getEncoded();
JWEObject jweObject = JWEObject.parse(tokenString);
jweObject.decrypt(new DirectDecrypter(encodedPk));
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
String jsonToken = jweObject.getPayload().toJSONObject().toJSONString();
System.out.println(jsonToken);
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
}
}
The java.security.PrivateKey parses correctly, but I am getting an error at jweObject.decrypt(new DirectDecrypter(encodedPk));
:
The Content Encryption Key length must be 128 bits (16 bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 bits (48 bytes) or 512 bites (64 bytes)
Also, in the debugger, I can see that jwe.payload
is null, though i don't know if this should be populated before decryption.
Do I need to generate the key differently, or is there another step that I have omitted? Do I need to specify the algorithm somewhere, or use a different decryptor method/class?
Upvotes: 2
Views: 6217
Reputation: 457
Turns out, I was using the methods for decrypting with symmetric keys rather than public/private. The following handles decryption successfully and allows me to view the claims.
@Test
public void decryptBlazemeterJwt() {
try {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
EncryptedJWT jwt = EncryptedJWT.parse(tokenString);
RSADecrypter decrypter = new RSADecrypter(pk);
jwt.decrypt(decrypter);
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
}
}
Upvotes: 4