2017-04-05 554 views
0

我们有一个远程应用程序向我们发送JWT。他们使用“RSA-OAEP-256”算法和“A256CBC-HS512”加密和我们的公钥来对令牌进行编码,现在我试图解密并解析这些声明。我使用openssl rsa -in <myPrivateKey> -pubout -out <myPublicKey>生成密钥,然后根据此SO post的建议将myPrivateKey转换为.der。按照nimbus的指南,我想出了以下内容。如何使用RSA私钥解密JWT

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

的为java.security.PrivateKey分析正确,但我在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)

而且,在调试器,我可以看到,jwe.payload是空的,虽然我不知道这是否应该在解密之前填充。

我是否需要以不同的方式生成密钥,还是有另一个步骤,我省略了?我需要在某处指定算法,还是使用不同的解密方法/类?

回答

1

原来,我使用的是使用对称密钥而不是公共/私人解密的方法。以下处理成功解密,并允许我查看索赔。

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