简体   繁体   中英

How to decrypt a JWT with RSA private key

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?

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM