【问题标题】:How to decrypt a JWT with RSA private key如何使用 RSA 私钥解密 JWT
【发布时间】:2017-08-31 12:19:11
【问题描述】:

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

    @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 为空,但我不知道是否应该在解密之前填充它。

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

【问题讨论】:

    标签: java spring rsa jwt jose


    【解决方案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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2012-07-13
      • 2013-06-08
      • 2017-05-11
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多